blob: 5f2e16076c40bd0c3b690ffc80f39d32d6487648 [file] [log] [blame]
Just van Rossum52e14d62002-12-30 22:08:05 +00001#include "Python.h"
2#include "structmember.h"
3#include "osdefs.h"
4#include "marshal.h"
Just van Rossum52e14d62002-12-30 22:08:05 +00005#include <time.h>
6
7
8#define IS_SOURCE 0x0
9#define IS_BYTECODE 0x1
10#define IS_PACKAGE 0x2
11
12struct st_zip_searchorder {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013 char suffix[14];
14 int type;
Just van Rossum52e14d62002-12-30 22:08:05 +000015};
16
17/* zip_searchorder defines how we search for a module in the Zip
18 archive: we first search for a package __init__, then for
19 non-package .pyc, .pyo and .py entries. The .pyc and .pyo entries
20 are swapped by initzipimport() if we run in optimized mode. Also,
21 '/' is replaced by SEP there. */
Neal Norwitz29fd2ba2003-03-23 13:21:03 +000022static struct st_zip_searchorder zip_searchorder[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},
24 {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE},
25 {"/__init__.py", IS_PACKAGE | IS_SOURCE},
26 {".pyc", IS_BYTECODE},
27 {".pyo", IS_BYTECODE},
28 {".py", IS_SOURCE},
29 {"", 0}
Just van Rossum52e14d62002-12-30 22:08:05 +000030};
31
32/* zipimporter object definition and support */
33
34typedef struct _zipimporter ZipImporter;
35
36struct _zipimporter {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 PyObject_HEAD
38 PyObject *archive; /* pathname of the Zip archive */
Victor Stinner72f767e2010-10-18 11:44:21 +000039 PyObject *prefix; /* file prefix: "a/sub/directory/",
40 encoded to the filesystem encoding */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 PyObject *files; /* dict with file info {path: toc_entry} */
Just van Rossum52e14d62002-12-30 22:08:05 +000042};
43
Just van Rossum52e14d62002-12-30 22:08:05 +000044static PyObject *ZipImportError;
Victor Stinnerc342fca2010-10-18 11:39:05 +000045/* read_directory() cache */
Just van Rossum52e14d62002-12-30 22:08:05 +000046static PyObject *zip_directory_cache = NULL;
47
48/* forward decls */
Victor Stinner2460a432010-08-16 17:54:28 +000049static PyObject *read_directory(PyObject *archive);
Victor Stinner60fe8d92010-08-16 23:48:11 +000050static PyObject *get_data(PyObject *archive, PyObject *toc_entry);
Just van Rossum52e14d62002-12-30 22:08:05 +000051static PyObject *get_module_code(ZipImporter *self, char *fullname,
Victor Stinner08654e12010-10-18 12:09:02 +000052 int *p_ispackage, PyObject **p_modpath);
Just van Rossum52e14d62002-12-30 22:08:05 +000053
54
55#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
56
57
58/* zipimporter.__init__
59 Split the "subdirectory" from the Zip archive path, lookup a matching
60 entry in sys.path_importer_cache, fetch the file directory from there
61 if found, or else read it from the archive. */
62static int
63zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)
64{
Victor Stinner2460a432010-08-16 17:54:28 +000065 PyObject *pathobj, *files;
Victor Stinner2b8dab72010-08-14 14:54:10 +000066 Py_UNICODE *path, *p, *prefix, buf[MAXPATHLEN+2];
67 Py_ssize_t len;
Just van Rossum52e14d62002-12-30 22:08:05 +000068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 if (!_PyArg_NoKeywords("zipimporter()", kwds))
70 return -1;
Georg Brandl02c42872005-08-26 06:42:30 +000071
Victor Stinner2b8dab72010-08-14 14:54:10 +000072 if (!PyArg_ParseTuple(args, "O&:zipimporter",
73 PyUnicode_FSDecoder, &pathobj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return -1;
Just van Rossum52e14d62002-12-30 22:08:05 +000075
Victor Stinner2b8dab72010-08-14 14:54:10 +000076 /* copy path to buf */
77 len = PyUnicode_GET_SIZE(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (len == 0) {
79 PyErr_SetString(ZipImportError, "archive path is empty");
Victor Stinner2b8dab72010-08-14 14:54:10 +000080 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 }
82 if (len >= MAXPATHLEN) {
83 PyErr_SetString(ZipImportError,
84 "archive path too long");
Victor Stinner2b8dab72010-08-14 14:54:10 +000085 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 }
Victor Stinner2b8dab72010-08-14 14:54:10 +000087 Py_UNICODE_strcpy(buf, PyUnicode_AS_UNICODE(pathobj));
Just van Rossum52e14d62002-12-30 22:08:05 +000088
89#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 for (p = buf; *p; p++) {
91 if (*p == ALTSEP)
92 *p = SEP;
93 }
Just van Rossum52e14d62002-12-30 22:08:05 +000094#endif
95
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 path = NULL;
97 prefix = NULL;
98 for (;;) {
99 struct stat statbuf;
100 int rv;
Just van Rossum52e14d62002-12-30 22:08:05 +0000101
Victor Stinner2b8dab72010-08-14 14:54:10 +0000102 if (pathobj == NULL) {
103 pathobj = PyUnicode_FromUnicode(buf, len);
104 if (pathobj == NULL)
105 goto error;
106 }
107 rv = _Py_stat(pathobj, &statbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (rv == 0) {
109 /* it exists */
110 if (S_ISREG(statbuf.st_mode))
111 /* it's a file */
112 path = buf;
113 break;
114 }
Victor Stinner2b8dab72010-08-14 14:54:10 +0000115 else if (PyErr_Occurred())
116 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 /* back up one path element */
Victor Stinner2b8dab72010-08-14 14:54:10 +0000118 p = Py_UNICODE_strrchr(buf, SEP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 if (prefix != NULL)
120 *prefix = SEP;
121 if (p == NULL)
122 break;
123 *p = '\0';
Victor Stinner2b8dab72010-08-14 14:54:10 +0000124 len = p - buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 prefix = p;
Victor Stinner2b8dab72010-08-14 14:54:10 +0000126 Py_CLEAR(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
Victor Stinner2b8dab72010-08-14 14:54:10 +0000128 if (path == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyErr_SetString(ZipImportError, "not a Zip file");
Victor Stinner2b8dab72010-08-14 14:54:10 +0000130 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000132
Victor Stinner2b8dab72010-08-14 14:54:10 +0000133 files = PyDict_GetItem(zip_directory_cache, pathobj);
134 if (files == NULL) {
Victor Stinner2460a432010-08-16 17:54:28 +0000135 files = read_directory(pathobj);
Victor Stinner2b8dab72010-08-14 14:54:10 +0000136 if (files == NULL)
137 goto error;
138 if (PyDict_SetItem(zip_directory_cache, pathobj, files) != 0)
139 goto error;
140 }
141 else
142 Py_INCREF(files);
143 self->files = files;
144
145 self->archive = pathobj;
146 pathobj = NULL;
147
148 if (prefix != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 prefix++;
Victor Stinner2b8dab72010-08-14 14:54:10 +0000150 len = Py_UNICODE_strlen(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (prefix[len-1] != SEP) {
152 /* add trailing SEP */
153 prefix[len] = SEP;
154 prefix[len + 1] = '\0';
Victor Stinner2b8dab72010-08-14 14:54:10 +0000155 len++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 }
157 }
Victor Stinner2b8dab72010-08-14 14:54:10 +0000158 else
159 len = 0;
160 self->prefix = PyUnicode_FromUnicode(prefix, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 if (self->prefix == NULL)
Victor Stinner2b8dab72010-08-14 14:54:10 +0000162 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 return 0;
Victor Stinner2b8dab72010-08-14 14:54:10 +0000165
166error:
167 Py_XDECREF(pathobj);
168 return -1;
Just van Rossum52e14d62002-12-30 22:08:05 +0000169}
170
171/* GC support. */
172static int
173zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)
174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 ZipImporter *self = (ZipImporter *)obj;
176 Py_VISIT(self->files);
177 return 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000178}
179
180static void
181zipimporter_dealloc(ZipImporter *self)
182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 PyObject_GC_UnTrack(self);
184 Py_XDECREF(self->archive);
185 Py_XDECREF(self->prefix);
186 Py_XDECREF(self->files);
187 Py_TYPE(self)->tp_free((PyObject *)self);
Just van Rossum52e14d62002-12-30 22:08:05 +0000188}
189
190static PyObject *
191zipimporter_repr(ZipImporter *self)
192{
Victor Stinner028dd972010-08-17 00:04:48 +0000193 if (self->archive == NULL)
194 return PyUnicode_FromString("<zipimporter object \"???\">");
195 else if (self->prefix != NULL && PyUnicode_GET_SIZE(self->prefix) != 0)
196 return PyUnicode_FromFormat("<zipimporter object \"%.300U%c%.150U\">",
197 self->archive, SEP, self->prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 else
Victor Stinner028dd972010-08-17 00:04:48 +0000199 return PyUnicode_FromFormat("<zipimporter object \"%.300U\">",
200 self->archive);
Just van Rossum52e14d62002-12-30 22:08:05 +0000201}
202
203/* return fullname.split(".")[-1] */
204static char *
205get_subname(char *fullname)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 char *subname = strrchr(fullname, '.');
208 if (subname == NULL)
209 subname = fullname;
210 else
211 subname++;
212 return subname;
Just van Rossum52e14d62002-12-30 22:08:05 +0000213}
214
215/* Given a (sub)modulename, write the potential file path in the
216 archive (without extension) to the path buffer. Return the
217 length of the resulting string. */
218static int
Victor Stinner72f767e2010-10-18 11:44:21 +0000219make_filename(PyObject *prefix_obj, char *name, char *path)
Just van Rossum52e14d62002-12-30 22:08:05 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 size_t len;
222 char *p;
Victor Stinner72f767e2010-10-18 11:44:21 +0000223 PyObject *prefix;
Just van Rossum52e14d62002-12-30 22:08:05 +0000224
Victor Stinner72f767e2010-10-18 11:44:21 +0000225 prefix = PyUnicode_EncodeFSDefault(prefix_obj);
226 if (prefix == NULL)
227 return -1;
228 len = PyBytes_GET_SIZE(prefix);
Just van Rossum52e14d62002-12-30 22:08:05 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */
231 if (len + strlen(name) + 13 >= MAXPATHLEN) {
232 PyErr_SetString(ZipImportError, "path too long");
Victor Stinner72f767e2010-10-18 11:44:21 +0000233 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 return -1;
235 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000236
Victor Stinner72f767e2010-10-18 11:44:21 +0000237 strcpy(path, PyBytes_AS_STRING(prefix));
238 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 strcpy(path + len, name);
240 for (p = path + len; *p; p++) {
241 if (*p == '.')
242 *p = SEP;
243 }
244 len += strlen(name);
245 assert(len < INT_MAX);
246 return (int)len;
Just van Rossum52e14d62002-12-30 22:08:05 +0000247}
248
Raymond Hettinger2c45c9a2004-11-10 13:08:35 +0000249enum zi_module_info {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 MI_ERROR,
251 MI_NOT_FOUND,
252 MI_MODULE,
253 MI_PACKAGE
Just van Rossum52e14d62002-12-30 22:08:05 +0000254};
255
256/* Return some information about a module. */
Raymond Hettinger2c45c9a2004-11-10 13:08:35 +0000257static enum zi_module_info
Just van Rossum52e14d62002-12-30 22:08:05 +0000258get_module_info(ZipImporter *self, char *fullname)
259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 char *subname, path[MAXPATHLEN + 1];
261 int len;
262 struct st_zip_searchorder *zso;
Just van Rossum52e14d62002-12-30 22:08:05 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 subname = get_subname(fullname);
Just van Rossum52e14d62002-12-30 22:08:05 +0000265
Victor Stinner72f767e2010-10-18 11:44:21 +0000266 len = make_filename(self->prefix, subname, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (len < 0)
268 return MI_ERROR;
Just van Rossum52e14d62002-12-30 22:08:05 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 for (zso = zip_searchorder; *zso->suffix; zso++) {
271 strcpy(path + len, zso->suffix);
272 if (PyDict_GetItemString(self->files, path) != NULL) {
273 if (zso->type & IS_PACKAGE)
274 return MI_PACKAGE;
275 else
276 return MI_MODULE;
277 }
278 }
279 return MI_NOT_FOUND;
Just van Rossum52e14d62002-12-30 22:08:05 +0000280}
281
282/* Check whether we can satisfy the import of the module named by
283 'fullname'. Return self if we can, None if we can't. */
284static PyObject *
285zipimporter_find_module(PyObject *obj, PyObject *args)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 ZipImporter *self = (ZipImporter *)obj;
288 PyObject *path = NULL;
289 char *fullname;
290 enum zi_module_info mi;
Just van Rossum52e14d62002-12-30 22:08:05 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module",
293 &fullname, &path))
294 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 mi = get_module_info(self, fullname);
297 if (mi == MI_ERROR)
298 return NULL;
299 if (mi == MI_NOT_FOUND) {
300 Py_INCREF(Py_None);
301 return Py_None;
302 }
303 Py_INCREF(self);
304 return (PyObject *)self;
Just van Rossum52e14d62002-12-30 22:08:05 +0000305}
306
307/* Load and return the module named by 'fullname'. */
308static PyObject *
309zipimporter_load_module(PyObject *obj, PyObject *args)
310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 ZipImporter *self = (ZipImporter *)obj;
Victor Stinner26fabe12010-10-18 12:03:25 +0000312 PyObject *code = NULL, *mod, *dict;
Victor Stinner08654e12010-10-18 12:09:02 +0000313 char *fullname;
314 PyObject *modpath = NULL, *modpath_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 int ispackage;
Just van Rossum52e14d62002-12-30 22:08:05 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (!PyArg_ParseTuple(args, "s:zipimporter.load_module",
318 &fullname))
319 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 code = get_module_code(self, fullname, &ispackage, &modpath);
322 if (code == NULL)
Victor Stinner26fabe12010-10-18 12:03:25 +0000323 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 mod = PyImport_AddModule(fullname);
Victor Stinner26fabe12010-10-18 12:03:25 +0000326 if (mod == NULL)
327 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 dict = PyModule_GetDict(mod);
Just van Rossum52e14d62002-12-30 22:08:05 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 /* mod.__loader__ = self */
331 if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
332 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (ispackage) {
335 /* add __path__ to the module *before* the code gets
336 executed */
337 PyObject *pkgpath, *fullpath;
338 char *subname = get_subname(fullname);
339 int err;
Just van Rossum52e14d62002-12-30 22:08:05 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 fullpath = PyUnicode_FromFormat("%U%c%U%s",
342 self->archive, SEP,
343 self->prefix, subname);
344 if (fullpath == NULL)
345 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 pkgpath = Py_BuildValue("[O]", fullpath);
348 Py_DECREF(fullpath);
349 if (pkgpath == NULL)
350 goto error;
351 err = PyDict_SetItemString(dict, "__path__", pkgpath);
352 Py_DECREF(pkgpath);
353 if (err != 0)
354 goto error;
355 }
Victor Stinner08654e12010-10-18 12:09:02 +0000356 modpath_bytes = PyUnicode_EncodeFSDefault(modpath);
357 if (modpath_bytes == NULL)
358 goto error;
359 mod = PyImport_ExecCodeModuleEx(fullname, code,
360 PyBytes_AS_STRING(modpath_bytes));
361 Py_DECREF(modpath_bytes);
Victor Stinner26fabe12010-10-18 12:03:25 +0000362 Py_CLEAR(code);
363 if (mod == NULL)
364 goto error;
365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (Py_VerboseFlag)
Victor Stinner08654e12010-10-18 12:09:02 +0000367 PySys_FormatStderr("import %s # loaded from Zip %U\n",
368 fullname, modpath);
369 Py_DECREF(modpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 return mod;
Just van Rossum52e14d62002-12-30 22:08:05 +0000371error:
Victor Stinner26fabe12010-10-18 12:03:25 +0000372 Py_XDECREF(code);
Victor Stinner08654e12010-10-18 12:09:02 +0000373 Py_XDECREF(modpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000375}
376
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000377/* Return a string matching __file__ for the named module */
378static PyObject *
379zipimporter_get_filename(PyObject *obj, PyObject *args)
380{
381 ZipImporter *self = (ZipImporter *)obj;
382 PyObject *code;
Victor Stinner08654e12010-10-18 12:09:02 +0000383 char *fullname;
384 PyObject *modpath;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000385 int ispackage;
386
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000387 if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename",
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000388 &fullname))
Victor Stinnerc342fca2010-10-18 11:39:05 +0000389 return NULL;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000390
391 /* Deciding the filename requires working out where the code
392 would come from if the module was actually loaded */
393 code = get_module_code(self, fullname, &ispackage, &modpath);
394 if (code == NULL)
Victor Stinnerc342fca2010-10-18 11:39:05 +0000395 return NULL;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000396 Py_DECREF(code); /* Only need the path info */
397
Victor Stinner08654e12010-10-18 12:09:02 +0000398 return modpath;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000399}
400
Just van Rossum52e14d62002-12-30 22:08:05 +0000401/* Return a bool signifying whether the module is a package or not. */
402static PyObject *
403zipimporter_is_package(PyObject *obj, PyObject *args)
404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 ZipImporter *self = (ZipImporter *)obj;
406 char *fullname;
407 enum zi_module_info mi;
Just van Rossum52e14d62002-12-30 22:08:05 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (!PyArg_ParseTuple(args, "s:zipimporter.is_package",
410 &fullname))
411 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 mi = get_module_info(self, fullname);
414 if (mi == MI_ERROR)
415 return NULL;
416 if (mi == MI_NOT_FOUND) {
417 PyErr_Format(ZipImportError, "can't find module '%.200s'",
418 fullname);
419 return NULL;
420 }
421 return PyBool_FromLong(mi == MI_PACKAGE);
Just van Rossum52e14d62002-12-30 22:08:05 +0000422}
423
424static PyObject *
425zipimporter_get_data(PyObject *obj, PyObject *args)
426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 ZipImporter *self = (ZipImporter *)obj;
Victor Stinner60fe8d92010-08-16 23:48:11 +0000428 PyObject *pathobj, *key;
429 const Py_UNICODE *path;
Just van Rossum52e14d62002-12-30 22:08:05 +0000430#ifdef ALTSEP
Victor Stinner60fe8d92010-08-16 23:48:11 +0000431 Py_UNICODE *p, buf[MAXPATHLEN + 1];
Just van Rossum52e14d62002-12-30 22:08:05 +0000432#endif
Victor Stinner60fe8d92010-08-16 23:48:11 +0000433 Py_UNICODE *archive;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyObject *toc_entry;
Victor Stinner60fe8d92010-08-16 23:48:11 +0000435 Py_ssize_t path_len, len;
Just van Rossum52e14d62002-12-30 22:08:05 +0000436
Victor Stinner60fe8d92010-08-16 23:48:11 +0000437 if (!PyArg_ParseTuple(args, "U:zipimporter.get_data", &pathobj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000439
Victor Stinner60fe8d92010-08-16 23:48:11 +0000440 path_len = PyUnicode_GET_SIZE(pathobj);
441 path = PyUnicode_AS_UNICODE(pathobj);
Just van Rossum52e14d62002-12-30 22:08:05 +0000442#ifdef ALTSEP
Victor Stinner60fe8d92010-08-16 23:48:11 +0000443 if (path_len >= MAXPATHLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyErr_SetString(ZipImportError, "path too long");
445 return NULL;
446 }
Victor Stinner60fe8d92010-08-16 23:48:11 +0000447 Py_UNICODE_strcpy(buf, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 for (p = buf; *p; p++) {
449 if (*p == ALTSEP)
450 *p = SEP;
451 }
452 path = buf;
Just van Rossum52e14d62002-12-30 22:08:05 +0000453#endif
Victor Stinner60fe8d92010-08-16 23:48:11 +0000454 archive = PyUnicode_AS_UNICODE(self->archive);
455 len = PyUnicode_GET_SIZE(self->archive);
456 if ((size_t)len < Py_UNICODE_strlen(path) &&
457 Py_UNICODE_strncmp(path, archive, len) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 path[len] == SEP) {
Victor Stinner60fe8d92010-08-16 23:48:11 +0000459 path += len + 1;
460 path_len -= len + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000462
Victor Stinner60fe8d92010-08-16 23:48:11 +0000463 key = PyUnicode_FromUnicode(path, path_len);
464 if (key == NULL)
465 return NULL;
466 toc_entry = PyDict_GetItem(self->files, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (toc_entry == NULL) {
Victor Stinner60fe8d92010-08-16 23:48:11 +0000468 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, key);
469 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 return NULL;
471 }
Victor Stinner60fe8d92010-08-16 23:48:11 +0000472 Py_DECREF(key);
473 return get_data(self->archive, toc_entry);
Just van Rossum52e14d62002-12-30 22:08:05 +0000474}
475
476static PyObject *
477zipimporter_get_code(PyObject *obj, PyObject *args)
478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 ZipImporter *self = (ZipImporter *)obj;
480 char *fullname;
Just van Rossum52e14d62002-12-30 22:08:05 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname))
483 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return get_module_code(self, fullname, NULL, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +0000486}
487
488static PyObject *
489zipimporter_get_source(PyObject *obj, PyObject *args)
490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 ZipImporter *self = (ZipImporter *)obj;
492 PyObject *toc_entry;
493 char *fullname, *subname, path[MAXPATHLEN+1];
494 int len;
495 enum zi_module_info mi;
Just van Rossum52e14d62002-12-30 22:08:05 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname))
498 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 mi = get_module_info(self, fullname);
501 if (mi == MI_ERROR)
502 return NULL;
503 if (mi == MI_NOT_FOUND) {
504 PyErr_Format(ZipImportError, "can't find module '%.200s'",
505 fullname);
506 return NULL;
507 }
508 subname = get_subname(fullname);
Just van Rossum52e14d62002-12-30 22:08:05 +0000509
Victor Stinner72f767e2010-10-18 11:44:21 +0000510 len = make_filename(self->prefix, subname, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (len < 0)
512 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (mi == MI_PACKAGE) {
515 path[len] = SEP;
516 strcpy(path + len + 1, "__init__.py");
517 }
518 else
519 strcpy(path + len, ".py");
Just van Rossum52e14d62002-12-30 22:08:05 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 toc_entry = PyDict_GetItemString(self->files, path);
522 if (toc_entry != NULL) {
Victor Stinner60fe8d92010-08-16 23:48:11 +0000523 PyObject *res, *bytes;
524 bytes = get_data(self->archive, toc_entry);
525 if (bytes == NULL)
526 return NULL;
527 res = PyUnicode_FromStringAndSize(PyBytes_AS_STRING(bytes),
528 PyBytes_GET_SIZE(bytes));
529 Py_DECREF(bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return res;
531 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* we have the module, but no source */
534 Py_INCREF(Py_None);
535 return Py_None;
Just van Rossum52e14d62002-12-30 22:08:05 +0000536}
537
538PyDoc_STRVAR(doc_find_module,
539"find_module(fullname, path=None) -> self or None.\n\
540\n\
541Search for a module specified by 'fullname'. 'fullname' must be the\n\
542fully qualified (dotted) module name. It returns the zipimporter\n\
543instance itself if the module was found, or None if it wasn't.\n\
544The optional 'path' argument is ignored -- it's there for compatibility\n\
545with the importer protocol.");
546
547PyDoc_STRVAR(doc_load_module,
548"load_module(fullname) -> module.\n\
549\n\
550Load the module specified by 'fullname'. 'fullname' must be the\n\
551fully qualified (dotted) module name. It returns the imported\n\
552module, or raises ZipImportError if it wasn't found.");
553
554PyDoc_STRVAR(doc_get_data,
555"get_data(pathname) -> string with file data.\n\
556\n\
557Return the data associated with 'pathname'. Raise IOError if\n\
558the file wasn't found.");
559
560PyDoc_STRVAR(doc_is_package,
561"is_package(fullname) -> bool.\n\
562\n\
563Return True if the module specified by fullname is a package.\n\
Brian Curtin32839732010-07-21 01:44:19 +0000564Raise ZipImportError if the module couldn't be found.");
Just van Rossum52e14d62002-12-30 22:08:05 +0000565
566PyDoc_STRVAR(doc_get_code,
567"get_code(fullname) -> code object.\n\
568\n\
569Return the code object for the specified module. Raise ZipImportError\n\
Brian Curtin32839732010-07-21 01:44:19 +0000570if the module couldn't be found.");
Just van Rossum52e14d62002-12-30 22:08:05 +0000571
572PyDoc_STRVAR(doc_get_source,
573"get_source(fullname) -> source string.\n\
574\n\
575Return the source code for the specified module. Raise ZipImportError\n\
Brian Curtin32839732010-07-21 01:44:19 +0000576if the module couldn't be found, return None if the archive does\n\
Just van Rossum52e14d62002-12-30 22:08:05 +0000577contain the module, but has no source for it.");
578
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000579
580PyDoc_STRVAR(doc_get_filename,
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000581"get_filename(fullname) -> filename string.\n\
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000582\n\
583Return the filename for the specified module.");
584
Just van Rossum52e14d62002-12-30 22:08:05 +0000585static PyMethodDef zipimporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 {"find_module", zipimporter_find_module, METH_VARARGS,
587 doc_find_module},
588 {"load_module", zipimporter_load_module, METH_VARARGS,
589 doc_load_module},
590 {"get_data", zipimporter_get_data, METH_VARARGS,
591 doc_get_data},
592 {"get_code", zipimporter_get_code, METH_VARARGS,
593 doc_get_code},
594 {"get_source", zipimporter_get_source, METH_VARARGS,
595 doc_get_source},
596 {"get_filename", zipimporter_get_filename, METH_VARARGS,
597 doc_get_filename},
598 {"is_package", zipimporter_is_package, METH_VARARGS,
599 doc_is_package},
600 {NULL, NULL} /* sentinel */
Just van Rossum52e14d62002-12-30 22:08:05 +0000601};
602
603static PyMemberDef zipimporter_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
605 {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
606 {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
607 {NULL}
Just van Rossum52e14d62002-12-30 22:08:05 +0000608};
609
610PyDoc_STRVAR(zipimporter_doc,
611"zipimporter(archivepath) -> zipimporter object\n\
612\n\
613Create a new zipimporter instance. 'archivepath' must be a path to\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000614a zipfile, or to a specific path inside a zipfile. For example, it can be\n\
615'/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a\n\
616valid directory inside the archive.\n\
617\n\
618'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip\n\
619archive.\n\
620\n\
621The 'archive' attribute of zipimporter objects contains the name of the\n\
622zipfile targeted.");
Just van Rossum52e14d62002-12-30 22:08:05 +0000623
624#define DEFERRED_ADDRESS(ADDR) 0
625
626static PyTypeObject ZipImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
628 "zipimport.zipimporter",
629 sizeof(ZipImporter),
630 0, /* tp_itemsize */
631 (destructor)zipimporter_dealloc, /* tp_dealloc */
632 0, /* tp_print */
633 0, /* tp_getattr */
634 0, /* tp_setattr */
635 0, /* tp_reserved */
636 (reprfunc)zipimporter_repr, /* tp_repr */
637 0, /* tp_as_number */
638 0, /* tp_as_sequence */
639 0, /* tp_as_mapping */
640 0, /* tp_hash */
641 0, /* tp_call */
642 0, /* tp_str */
643 PyObject_GenericGetAttr, /* tp_getattro */
644 0, /* tp_setattro */
645 0, /* tp_as_buffer */
646 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
647 Py_TPFLAGS_HAVE_GC, /* tp_flags */
648 zipimporter_doc, /* tp_doc */
649 zipimporter_traverse, /* tp_traverse */
650 0, /* tp_clear */
651 0, /* tp_richcompare */
652 0, /* tp_weaklistoffset */
653 0, /* tp_iter */
654 0, /* tp_iternext */
655 zipimporter_methods, /* tp_methods */
656 zipimporter_members, /* tp_members */
657 0, /* tp_getset */
658 0, /* tp_base */
659 0, /* tp_dict */
660 0, /* tp_descr_get */
661 0, /* tp_descr_set */
662 0, /* tp_dictoffset */
663 (initproc)zipimporter_init, /* tp_init */
664 PyType_GenericAlloc, /* tp_alloc */
665 PyType_GenericNew, /* tp_new */
666 PyObject_GC_Del, /* tp_free */
Just van Rossum52e14d62002-12-30 22:08:05 +0000667};
668
669
670/* implementation */
671
Just van Rossum52e14d62002-12-30 22:08:05 +0000672/* Given a buffer, return the long that is represented by the first
673 4 bytes, encoded as little endian. This partially reimplements
674 marshal.c:r_long() */
675static long
676get_long(unsigned char *buf) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 long x;
678 x = buf[0];
679 x |= (long)buf[1] << 8;
680 x |= (long)buf[2] << 16;
681 x |= (long)buf[3] << 24;
Just van Rossum52e14d62002-12-30 22:08:05 +0000682#if SIZEOF_LONG > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* Sign extension for 64-bit machines */
684 x |= -(x & 0x80000000L);
Just van Rossum52e14d62002-12-30 22:08:05 +0000685#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return x;
Just van Rossum52e14d62002-12-30 22:08:05 +0000687}
688
689/*
690 read_directory(archive) -> files dict (new reference)
691
692 Given a path to a Zip archive, build a dict, mapping file names
693 (local to the archive, using SEP as a separator) to toc entries.
694
695 A toc_entry is a tuple:
696
Victor Stinner08654e12010-10-18 12:09:02 +0000697 (__file__, # value to use for __file__, available for all files,
698 # encoded to the filesystem encoding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 compress, # compression kind; 0 for uncompressed
700 data_size, # size of compressed data on disk
701 file_size, # size of decompressed data
702 file_offset, # offset of file header from start of archive
703 time, # mod time of file (in dos format)
704 date, # mod data of file (in dos format)
705 crc, # crc checksum of the data
Victor Stinnerc342fca2010-10-18 11:39:05 +0000706 )
Just van Rossum52e14d62002-12-30 22:08:05 +0000707
708 Directories can be recognized by the trailing SEP in the name,
709 data_size and file_offset are 0.
710*/
711static PyObject *
Victor Stinner2460a432010-08-16 17:54:28 +0000712read_directory(PyObject *archive_obj)
Just van Rossum52e14d62002-12-30 22:08:05 +0000713{
Victor Stinner2460a432010-08-16 17:54:28 +0000714 /* FIXME: work on Py_UNICODE* instead of char* */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyObject *files = NULL;
716 FILE *fp;
717 long compress, crc, data_size, file_size, file_offset, date, time;
718 long header_offset, name_size, header_size, header_position;
719 long i, l, count;
720 size_t length;
Victor Stinner2460a432010-08-16 17:54:28 +0000721 Py_UNICODE path[MAXPATHLEN + 5];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 char name[MAXPATHLEN + 5];
Victor Stinner2460a432010-08-16 17:54:28 +0000723 PyObject *nameobj = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 char *p, endof_central_dir[22];
725 long arc_offset; /* offset from beginning of file to start of zip-archive */
Victor Stinner2460a432010-08-16 17:54:28 +0000726 PyObject *pathobj;
Just van Rossum52e14d62002-12-30 22:08:05 +0000727
Victor Stinner2460a432010-08-16 17:54:28 +0000728 if (PyUnicode_GET_SIZE(archive_obj) > MAXPATHLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyErr_SetString(PyExc_OverflowError,
730 "Zip path name is too long");
731 return NULL;
732 }
Victor Stinner2460a432010-08-16 17:54:28 +0000733 Py_UNICODE_strcpy(path, PyUnicode_AS_UNICODE(archive_obj));
Just van Rossum52e14d62002-12-30 22:08:05 +0000734
Victor Stinner2460a432010-08-16 17:54:28 +0000735 fp = _Py_fopen(archive_obj, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (fp == NULL) {
737 PyErr_Format(ZipImportError, "can't open Zip file: "
Victor Stinner2460a432010-08-16 17:54:28 +0000738 "'%.200U'", archive_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return NULL;
740 }
741 fseek(fp, -22, SEEK_END);
742 header_position = ftell(fp);
743 if (fread(endof_central_dir, 1, 22, fp) != 22) {
744 fclose(fp);
745 PyErr_Format(ZipImportError, "can't read Zip file: "
Victor Stinner2460a432010-08-16 17:54:28 +0000746 "'%.200U'", archive_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return NULL;
748 }
749 if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
750 /* Bad: End of Central Dir signature */
751 fclose(fp);
752 PyErr_Format(ZipImportError, "not a Zip file: "
Victor Stinner2460a432010-08-16 17:54:28 +0000753 "'%.200U'", archive_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return NULL;
755 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 header_size = get_long((unsigned char *)endof_central_dir + 12);
758 header_offset = get_long((unsigned char *)endof_central_dir + 16);
759 arc_offset = header_position - header_offset - header_size;
760 header_offset += arc_offset;
Just van Rossum52e14d62002-12-30 22:08:05 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 files = PyDict_New();
763 if (files == NULL)
764 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000765
Victor Stinner2460a432010-08-16 17:54:28 +0000766 length = Py_UNICODE_strlen(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 path[length] = SEP;
Just van Rossum52e14d62002-12-30 22:08:05 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 /* Start of Central Directory */
770 count = 0;
771 for (;;) {
772 PyObject *t;
773 int err;
Just van Rossum52e14d62002-12-30 22:08:05 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 fseek(fp, header_offset, 0); /* Start of file header */
776 l = PyMarshal_ReadLongFromFile(fp);
777 if (l != 0x02014B50)
778 break; /* Bad: Central Dir File Header */
779 fseek(fp, header_offset + 10, 0);
780 compress = PyMarshal_ReadShortFromFile(fp);
781 time = PyMarshal_ReadShortFromFile(fp);
782 date = PyMarshal_ReadShortFromFile(fp);
783 crc = PyMarshal_ReadLongFromFile(fp);
784 data_size = PyMarshal_ReadLongFromFile(fp);
785 file_size = PyMarshal_ReadLongFromFile(fp);
786 name_size = PyMarshal_ReadShortFromFile(fp);
787 header_size = 46 + name_size +
788 PyMarshal_ReadShortFromFile(fp) +
789 PyMarshal_ReadShortFromFile(fp);
790 fseek(fp, header_offset + 42, 0);
791 file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
792 if (name_size > MAXPATHLEN)
793 name_size = MAXPATHLEN;
Just van Rossum52e14d62002-12-30 22:08:05 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 p = name;
796 for (i = 0; i < name_size; i++) {
797 *p = (char)getc(fp);
798 if (*p == '/')
799 *p = SEP;
800 p++;
801 }
802 *p = 0; /* Add terminating null byte */
803 header_offset += header_size;
Just van Rossum52e14d62002-12-30 22:08:05 +0000804
Victor Stinner2460a432010-08-16 17:54:28 +0000805 nameobj = PyUnicode_DecodeFSDefaultAndSize(name, name_size);
806 if (nameobj == NULL)
807 goto error;
808 Py_UNICODE_strncpy(path + length + 1, PyUnicode_AS_UNICODE(nameobj), MAXPATHLEN - length - 1);
Just van Rossum52e14d62002-12-30 22:08:05 +0000809
Victor Stinner2460a432010-08-16 17:54:28 +0000810 pathobj = PyUnicode_FromUnicode(path, Py_UNICODE_strlen(path));
811 if (pathobj == NULL)
812 goto error;
813 t = Py_BuildValue("Niiiiiii", pathobj, compress, data_size,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 file_size, file_offset, time, date, crc);
815 if (t == NULL)
816 goto error;
Victor Stinner2460a432010-08-16 17:54:28 +0000817 err = PyDict_SetItem(files, nameobj, t);
818 Py_CLEAR(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_DECREF(t);
820 if (err != 0)
821 goto error;
822 count++;
823 }
824 fclose(fp);
825 if (Py_VerboseFlag)
Victor Stinner2460a432010-08-16 17:54:28 +0000826 PySys_FormatStderr("# zipimport: found %ld names in %U\n",
827 count, archive_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return files;
Just van Rossum52e14d62002-12-30 22:08:05 +0000829error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 fclose(fp);
831 Py_XDECREF(files);
Victor Stinner2460a432010-08-16 17:54:28 +0000832 Py_XDECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000834}
835
836/* Return the zlib.decompress function object, or NULL if zlib couldn't
837 be imported. The function is cached when found, so subsequent calls
838 don't import zlib again. Returns a *borrowed* reference.
839 XXX This makes zlib.decompress immortal. */
840static PyObject *
841get_decompress_func(void)
842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 static PyObject *decompress = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (decompress == NULL) {
846 PyObject *zlib;
847 static int importing_zlib = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (importing_zlib != 0)
850 /* Someone has a zlib.py[co] in their Zip file;
851 let's avoid a stack overflow. */
852 return NULL;
853 importing_zlib = 1;
854 zlib = PyImport_ImportModuleNoBlock("zlib");
855 importing_zlib = 0;
856 if (zlib != NULL) {
857 decompress = PyObject_GetAttrString(zlib,
858 "decompress");
859 Py_DECREF(zlib);
860 }
861 else
862 PyErr_Clear();
863 if (Py_VerboseFlag)
864 PySys_WriteStderr("# zipimport: zlib %s\n",
865 zlib != NULL ? "available": "UNAVAILABLE");
866 }
867 return decompress;
Just van Rossum52e14d62002-12-30 22:08:05 +0000868}
869
870/* Given a path to a Zip file and a toc_entry, return the (uncompressed)
871 data as a new reference. */
872static PyObject *
Victor Stinner60fe8d92010-08-16 23:48:11 +0000873get_data(PyObject *archive, PyObject *toc_entry)
Just van Rossum52e14d62002-12-30 22:08:05 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 PyObject *raw_data, *data = NULL, *decompress;
876 char *buf;
877 FILE *fp;
878 int err;
879 Py_ssize_t bytes_read = 0;
880 long l;
Victor Stinner60fe8d92010-08-16 23:48:11 +0000881 PyObject *datapath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 long compress, data_size, file_size, file_offset, bytes_size;
883 long time, date, crc;
Just van Rossum52e14d62002-12-30 22:08:05 +0000884
Victor Stinner60fe8d92010-08-16 23:48:11 +0000885 if (!PyArg_ParseTuple(toc_entry, "Olllllll", &datapath, &compress,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 &data_size, &file_size, &file_offset, &time,
887 &date, &crc)) {
888 return NULL;
889 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000890
Victor Stinner60fe8d92010-08-16 23:48:11 +0000891 fp = _Py_fopen(archive, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (!fp) {
893 PyErr_Format(PyExc_IOError,
Victor Stinner60fe8d92010-08-16 23:48:11 +0000894 "zipimport: can not open file %U", archive);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 return NULL;
896 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* Check to make sure the local file header is correct */
899 fseek(fp, file_offset, 0);
900 l = PyMarshal_ReadLongFromFile(fp);
901 if (l != 0x04034B50) {
902 /* Bad: Local File Header */
903 PyErr_Format(ZipImportError,
Victor Stinner60fe8d92010-08-16 23:48:11 +0000904 "bad local file header in %U",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 archive);
906 fclose(fp);
907 return NULL;
908 }
909 fseek(fp, file_offset + 26, 0);
910 l = 30 + PyMarshal_ReadShortFromFile(fp) +
911 PyMarshal_ReadShortFromFile(fp); /* local header size */
912 file_offset += l; /* Start of file data */
Just van Rossum52e14d62002-12-30 22:08:05 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 bytes_size = compress == 0 ? data_size : data_size + 1;
915 if (bytes_size == 0)
916 bytes_size++;
917 raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size);
Just van Rossum52e14d62002-12-30 22:08:05 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (raw_data == NULL) {
920 fclose(fp);
921 return NULL;
922 }
923 buf = PyBytes_AsString(raw_data);
Just van Rossum52e14d62002-12-30 22:08:05 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 err = fseek(fp, file_offset, 0);
926 if (err == 0)
927 bytes_read = fread(buf, 1, data_size, fp);
928 fclose(fp);
929 if (err || bytes_read != data_size) {
930 PyErr_SetString(PyExc_IOError,
931 "zipimport: can't read data");
932 Py_DECREF(raw_data);
933 return NULL;
934 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (compress != 0) {
937 buf[data_size] = 'Z'; /* saw this in zipfile.py */
938 data_size++;
939 }
940 buf[data_size] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (compress == 0) { /* data is not compressed */
943 data = PyBytes_FromStringAndSize(buf, data_size);
944 Py_DECREF(raw_data);
945 return data;
946 }
947
948 /* Decompress with zlib */
949 decompress = get_decompress_func();
950 if (decompress == NULL) {
951 PyErr_SetString(ZipImportError,
952 "can't decompress data; "
953 "zlib not available");
954 goto error;
955 }
956 data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
Just van Rossum52e14d62002-12-30 22:08:05 +0000957error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 Py_DECREF(raw_data);
959 return data;
Just van Rossum52e14d62002-12-30 22:08:05 +0000960}
961
962/* Lenient date/time comparison function. The precision of the mtime
963 in the archive is lower than the mtime stored in a .pyc: we
964 must allow a difference of at most one second. */
965static int
966eq_mtime(time_t t1, time_t t2)
967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 time_t d = t1 - t2;
969 if (d < 0)
970 d = -d;
971 /* dostime only stores even seconds, so be lenient */
972 return d <= 1;
Just van Rossum52e14d62002-12-30 22:08:05 +0000973}
974
975/* Given the contents of a .py[co] file in a buffer, unmarshal the data
976 and return the code object. Return None if it the magic word doesn't
977 match (we do this instead of raising an exception as we fall back
978 to .py if available and we don't want to mask other errors).
979 Returns a new reference. */
980static PyObject *
981unmarshal_code(char *pathname, PyObject *data, time_t mtime)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *code;
984 char *buf = PyBytes_AsString(data);
985 Py_ssize_t size = PyBytes_Size(data);
Just van Rossum52e14d62002-12-30 22:08:05 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (size <= 9) {
988 PyErr_SetString(ZipImportError,
989 "bad pyc data");
990 return NULL;
991 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
994 if (Py_VerboseFlag)
995 PySys_WriteStderr("# %s has bad magic\n",
996 pathname);
997 Py_INCREF(Py_None);
998 return Py_None; /* signal caller to try alternative */
999 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
1002 mtime)) {
1003 if (Py_VerboseFlag)
1004 PySys_WriteStderr("# %s has bad mtime\n",
1005 pathname);
1006 Py_INCREF(Py_None);
1007 return Py_None; /* signal caller to try alternative */
1008 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
1011 if (code == NULL)
1012 return NULL;
1013 if (!PyCode_Check(code)) {
1014 Py_DECREF(code);
1015 PyErr_Format(PyExc_TypeError,
1016 "compiled module %.200s is not a code object",
1017 pathname);
1018 return NULL;
1019 }
1020 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001021}
1022
1023/* Replace any occurances of "\r\n?" in the input string with "\n".
1024 This converts DOS and Mac line endings to Unix line endings.
1025 Also append a trailing "\n" to be compatible with
1026 PyParser_SimpleParseFile(). Returns a new reference. */
1027static PyObject *
1028normalize_line_endings(PyObject *source)
1029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 char *buf, *q, *p = PyBytes_AsString(source);
1031 PyObject *fixed_source;
1032 int len = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (!p) {
1035 return PyBytes_FromStringAndSize("\n\0", 2);
1036 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* one char extra for trailing \n and one for terminating \0 */
1039 buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2);
1040 if (buf == NULL) {
1041 PyErr_SetString(PyExc_MemoryError,
1042 "zipimport: no memory to allocate "
1043 "source buffer");
1044 return NULL;
1045 }
1046 /* replace "\r\n?" by "\n" */
1047 for (q = buf; *p != '\0'; p++) {
1048 if (*p == '\r') {
1049 *q++ = '\n';
1050 if (*(p + 1) == '\n')
1051 p++;
1052 }
1053 else
1054 *q++ = *p;
1055 len++;
1056 }
1057 *q++ = '\n'; /* add trailing \n */
1058 *q = '\0';
1059 fixed_source = PyBytes_FromStringAndSize(buf, len + 2);
1060 PyMem_Free(buf);
1061 return fixed_source;
Just van Rossum52e14d62002-12-30 22:08:05 +00001062}
1063
1064/* Given a string buffer containing Python source code, compile it
1065 return and return a code object as a new reference. */
1066static PyObject *
1067compile_source(char *pathname, PyObject *source)
1068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *code, *fixed_source;
Just van Rossum52e14d62002-12-30 22:08:05 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 fixed_source = normalize_line_endings(source);
1072 if (fixed_source == NULL)
1073 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 code = Py_CompileString(PyBytes_AsString(fixed_source), pathname,
1076 Py_file_input);
1077 Py_DECREF(fixed_source);
1078 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001079}
1080
1081/* Convert the date/time values found in the Zip archive to a value
1082 that's compatible with the time stamp stored in .pyc files. */
Neal Norwitz29fd2ba2003-03-23 13:21:03 +00001083static time_t
1084parse_dostime(int dostime, int dosdate)
Just van Rossum52e14d62002-12-30 22:08:05 +00001085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 struct tm stm;
Just van Rossum52e14d62002-12-30 22:08:05 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 memset((void *) &stm, '\0', sizeof(stm));
Christian Heimes679db4a2008-01-18 09:56:22 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 stm.tm_sec = (dostime & 0x1f) * 2;
1091 stm.tm_min = (dostime >> 5) & 0x3f;
1092 stm.tm_hour = (dostime >> 11) & 0x1f;
1093 stm.tm_mday = dosdate & 0x1f;
1094 stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;
1095 stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;
1096 stm.tm_isdst = -1; /* wday/yday is ignored */
Just van Rossum52e14d62002-12-30 22:08:05 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 return mktime(&stm);
Just van Rossum52e14d62002-12-30 22:08:05 +00001099}
1100
1101/* Given a path to a .pyc or .pyo file in the archive, return the
1102 modifictaion time of the matching .py file, or 0 if no source
1103 is available. */
1104static time_t
1105get_mtime_of_source(ZipImporter *self, char *path)
1106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 PyObject *toc_entry;
1108 time_t mtime = 0;
1109 Py_ssize_t lastchar = strlen(path) - 1;
1110 char savechar = path[lastchar];
1111 path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */
1112 toc_entry = PyDict_GetItemString(self->files, path);
1113 if (toc_entry != NULL && PyTuple_Check(toc_entry) &&
1114 PyTuple_Size(toc_entry) == 8) {
1115 /* fetch the time stamp of the .py file for comparison
1116 with an embedded pyc time stamp */
1117 int time, date;
1118 time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5));
1119 date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6));
1120 mtime = parse_dostime(time, date);
1121 }
1122 path[lastchar] = savechar;
1123 return mtime;
Just van Rossum52e14d62002-12-30 22:08:05 +00001124}
1125
1126/* Return the code object for the module named by 'fullname' from the
1127 Zip archive as a new reference. */
1128static PyObject *
1129get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 time_t mtime, PyObject *toc_entry)
Just van Rossum52e14d62002-12-30 22:08:05 +00001131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 PyObject *data, *code;
1133 char *modpath;
Just van Rossum52e14d62002-12-30 22:08:05 +00001134
Victor Stinner60fe8d92010-08-16 23:48:11 +00001135 data = get_data(self->archive, toc_entry);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (data == NULL)
1137 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0));
Victor Stinner5a7913e2010-10-16 11:29:07 +00001140 if (modpath == NULL) {
1141 Py_DECREF(data);
1142 return NULL;
1143 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (isbytecode) {
1146 code = unmarshal_code(modpath, data, mtime);
1147 }
1148 else {
1149 code = compile_source(modpath, data);
1150 }
1151 Py_DECREF(data);
1152 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001153}
1154
1155/* Get the code object assoiciated with the module specified by
1156 'fullname'. */
1157static PyObject *
1158get_module_code(ZipImporter *self, char *fullname,
Victor Stinner08654e12010-10-18 12:09:02 +00001159 int *p_ispackage, PyObject **p_modpath)
Just van Rossum52e14d62002-12-30 22:08:05 +00001160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *toc_entry;
1162 char *subname, path[MAXPATHLEN + 1];
1163 int len;
1164 struct st_zip_searchorder *zso;
Just van Rossum52e14d62002-12-30 22:08:05 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 subname = get_subname(fullname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001167
Victor Stinner72f767e2010-10-18 11:44:21 +00001168 len = make_filename(self->prefix, subname, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (len < 0)
1170 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 for (zso = zip_searchorder; *zso->suffix; zso++) {
1173 PyObject *code = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 strcpy(path + len, zso->suffix);
1176 if (Py_VerboseFlag > 1)
Victor Stinner353349c2010-10-18 11:40:40 +00001177 PySys_FormatStderr("# trying %U%c%s\n",
Victor Stinner72f767e2010-10-18 11:44:21 +00001178 self->archive, (int)SEP, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 toc_entry = PyDict_GetItemString(self->files, path);
1180 if (toc_entry != NULL) {
1181 time_t mtime = 0;
1182 int ispackage = zso->type & IS_PACKAGE;
1183 int isbytecode = zso->type & IS_BYTECODE;
Just van Rossum52e14d62002-12-30 22:08:05 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (isbytecode)
1186 mtime = get_mtime_of_source(self, path);
1187 if (p_ispackage != NULL)
1188 *p_ispackage = ispackage;
1189 code = get_code_from_data(self, ispackage,
1190 isbytecode, mtime,
1191 toc_entry);
1192 if (code == Py_None) {
1193 /* bad magic number or non-matching mtime
1194 in byte code, try next */
1195 Py_DECREF(code);
1196 continue;
1197 }
Victor Stinner08654e12010-10-18 12:09:02 +00001198 if (code != NULL && p_modpath != NULL) {
1199 *p_modpath = PyTuple_GetItem(toc_entry, 0);
1200 Py_INCREF(*p_modpath);
1201 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return code;
1203 }
1204 }
1205 PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);
1206 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001207}
1208
1209
1210/* Module init */
1211
1212PyDoc_STRVAR(zipimport_doc,
1213"zipimport provides support for importing Python modules from Zip archives.\n\
1214\n\
1215This module exports three objects:\n\
1216- zipimporter: a class; its constructor takes a path to a Zip archive.\n\
Fredrik Lundhb84b35f2006-01-15 15:00:40 +00001217- ZipImportError: exception raised by zipimporter objects. It's a\n\
Just van Rossum52e14d62002-12-30 22:08:05 +00001218 subclass of ImportError, so it can be caught as ImportError, too.\n\
1219- _zip_directory_cache: a dict, mapping archive paths to zip directory\n\
1220 info dicts, as used in zipimporter._files.\n\
1221\n\
1222It is usually not needed to use the zipimport module explicitly; it is\n\
1223used by the builtin import mechanism for sys.path items that are paths\n\
1224to Zip archives.");
1225
Martin v. Löwis1a214512008-06-11 05:26:20 +00001226static struct PyModuleDef zipimportmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 PyModuleDef_HEAD_INIT,
1228 "zipimport",
1229 zipimport_doc,
1230 -1,
1231 NULL,
1232 NULL,
1233 NULL,
1234 NULL,
1235 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001236};
1237
Just van Rossum52e14d62002-12-30 22:08:05 +00001238PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001239PyInit_zipimport(void)
Just van Rossum52e14d62002-12-30 22:08:05 +00001240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyObject *mod;
Just van Rossum52e14d62002-12-30 22:08:05 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (PyType_Ready(&ZipImporter_Type) < 0)
1244 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 /* Correct directory separator */
1247 zip_searchorder[0].suffix[0] = SEP;
1248 zip_searchorder[1].suffix[0] = SEP;
1249 zip_searchorder[2].suffix[0] = SEP;
1250 if (Py_OptimizeFlag) {
1251 /* Reverse *.pyc and *.pyo */
1252 struct st_zip_searchorder tmp;
1253 tmp = zip_searchorder[0];
1254 zip_searchorder[0] = zip_searchorder[1];
1255 zip_searchorder[1] = tmp;
1256 tmp = zip_searchorder[3];
1257 zip_searchorder[3] = zip_searchorder[4];
1258 zip_searchorder[4] = tmp;
1259 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 mod = PyModule_Create(&zipimportmodule);
1262 if (mod == NULL)
1263 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 ZipImportError = PyErr_NewException("zipimport.ZipImportError",
1266 PyExc_ImportError, NULL);
1267 if (ZipImportError == NULL)
1268 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 Py_INCREF(ZipImportError);
1271 if (PyModule_AddObject(mod, "ZipImportError",
1272 ZipImportError) < 0)
1273 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 Py_INCREF(&ZipImporter_Type);
1276 if (PyModule_AddObject(mod, "zipimporter",
1277 (PyObject *)&ZipImporter_Type) < 0)
1278 return NULL;
Just van Rossumf8b6de12002-12-31 09:51:59 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 zip_directory_cache = PyDict_New();
1281 if (zip_directory_cache == NULL)
1282 return NULL;
1283 Py_INCREF(zip_directory_cache);
1284 if (PyModule_AddObject(mod, "_zip_directory_cache",
1285 zip_directory_cache) < 0)
1286 return NULL;
1287 return mod;
Just van Rossum52e14d62002-12-30 22:08:05 +00001288}