blob: 2feb2a827c8b67dfd947d93153e289c869211bcc [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
Victor Stinner9e40fad2010-10-18 22:34:46 +000038 PyObject *archive; /* pathname of the Zip archive,
39 decoded from the filesystem encoding */
Victor Stinner72f767e2010-10-18 11:44:21 +000040 PyObject *prefix; /* file prefix: "a/sub/directory/",
41 encoded to the filesystem encoding */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *files; /* dict with file info {path: toc_entry} */
Just van Rossum52e14d62002-12-30 22:08:05 +000043};
44
Just van Rossum52e14d62002-12-30 22:08:05 +000045static PyObject *ZipImportError;
Victor Stinnerc342fca2010-10-18 11:39:05 +000046/* read_directory() cache */
Just van Rossum52e14d62002-12-30 22:08:05 +000047static PyObject *zip_directory_cache = NULL;
48
49/* forward decls */
Victor Stinner2460a432010-08-16 17:54:28 +000050static PyObject *read_directory(PyObject *archive);
Victor Stinner60fe8d92010-08-16 23:48:11 +000051static PyObject *get_data(PyObject *archive, PyObject *toc_entry);
Victor Stinnerf6b563a2011-03-14 20:46:50 -040052static PyObject *get_module_code(ZipImporter *self, PyObject *fullname,
Victor Stinner08654e12010-10-18 12:09:02 +000053 int *p_ispackage, PyObject **p_modpath);
Just van Rossum52e14d62002-12-30 22:08:05 +000054
55
56#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
57
58
59/* zipimporter.__init__
60 Split the "subdirectory" from the Zip archive path, lookup a matching
61 entry in sys.path_importer_cache, fetch the file directory from there
62 if found, or else read it from the archive. */
63static int
64zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)
65{
Martin v. Löwisa72e78b2011-10-31 08:33:37 +010066 PyObject *path, *files, *tmp;
67 PyObject *filename = NULL;
68 Py_ssize_t len, flen;
69#ifdef ALTSEP
70 _Py_IDENTIFIER(replace);
71#endif
Just van Rossum52e14d62002-12-30 22:08:05 +000072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 if (!_PyArg_NoKeywords("zipimporter()", kwds))
74 return -1;
Georg Brandl02c42872005-08-26 06:42:30 +000075
Victor Stinner2b8dab72010-08-14 14:54:10 +000076 if (!PyArg_ParseTuple(args, "O&:zipimporter",
Martin v. Löwisa72e78b2011-10-31 08:33:37 +010077 PyUnicode_FSDecoder, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 return -1;
Just van Rossum52e14d62002-12-30 22:08:05 +000079
Martin v. Löwisa72e78b2011-10-31 08:33:37 +010080 if (PyUnicode_READY(path) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020081 return -1;
82
Martin v. Löwisa72e78b2011-10-31 08:33:37 +010083 len = PyUnicode_GET_LENGTH(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 if (len == 0) {
85 PyErr_SetString(ZipImportError, "archive path is empty");
Victor Stinner2b8dab72010-08-14 14:54:10 +000086 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 }
Just van Rossum52e14d62002-12-30 22:08:05 +000088
89#ifdef ALTSEP
Martin v. Löwiscfa61292011-10-31 09:01:22 +010090 tmp = _PyObject_CallMethodId(path, &PyId_replace, "CC", ALTSEP, SEP);
Martin v. Löwisa72e78b2011-10-31 08:33:37 +010091 if (!tmp)
92 goto error;
93 Py_DECREF(path);
94 path = tmp;
Just van Rossum52e14d62002-12-30 22:08:05 +000095#endif
96
Martin v. Löwisa72e78b2011-10-31 08:33:37 +010097 filename = path;
98 Py_INCREF(filename);
99 flen = len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 for (;;) {
101 struct stat statbuf;
102 int rv;
Just van Rossum52e14d62002-12-30 22:08:05 +0000103
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100104 rv = _Py_stat(filename, &statbuf);
Victor Stinnerbd0850b2011-12-18 20:47:30 +0100105 if (rv == -2)
106 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 if (rv == 0) {
108 /* it exists */
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100109 if (!S_ISREG(statbuf.st_mode))
110 /* it's a not file */
111 Py_CLEAR(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 break;
113 }
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100114 Py_CLEAR(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* back up one path element */
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100116 flen = PyUnicode_FindChar(path, SEP, 0, flen, -1);
117 if (flen == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 break;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100119 filename = PyUnicode_Substring(path, 0, flen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100121 if (filename == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyErr_SetString(ZipImportError, "not a Zip file");
Victor Stinner2b8dab72010-08-14 14:54:10 +0000123 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000125
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100126 if (PyUnicode_READY(filename) < 0)
127 goto error;
128
129 files = PyDict_GetItem(zip_directory_cache, filename);
Victor Stinner2b8dab72010-08-14 14:54:10 +0000130 if (files == NULL) {
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100131 files = read_directory(filename);
Victor Stinner2b8dab72010-08-14 14:54:10 +0000132 if (files == NULL)
133 goto error;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100134 if (PyDict_SetItem(zip_directory_cache, filename, files) != 0)
Victor Stinner2b8dab72010-08-14 14:54:10 +0000135 goto error;
136 }
137 else
138 Py_INCREF(files);
139 self->files = files;
140
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100141 /* Transfer reference */
142 self->archive = filename;
143 filename = NULL;
Victor Stinner2b8dab72010-08-14 14:54:10 +0000144
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100145 /* Check if there is a prefix directory following the filename. */
146 if (flen != len) {
147 tmp = PyUnicode_Substring(path, flen+1,
148 PyUnicode_GET_LENGTH(path));
149 if (tmp == NULL)
150 goto error;
151 self->prefix = tmp;
152 if (PyUnicode_READ_CHAR(path, len-1) != SEP) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 /* add trailing SEP */
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100154 tmp = PyUnicode_FromFormat("%U%c", self->prefix, SEP);
155 if (tmp == NULL)
156 goto error;
157 Py_DECREF(self->prefix);
158 self->prefix = tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 }
160 }
Victor Stinner2b8dab72010-08-14 14:54:10 +0000161 else
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100162 self->prefix = PyUnicode_New(0, 0);
163 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 return 0;
Victor Stinner2b8dab72010-08-14 14:54:10 +0000165
166error:
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100167 Py_DECREF(path);
168 Py_XDECREF(filename);
Victor Stinner2b8dab72010-08-14 14:54:10 +0000169 return -1;
Just van Rossum52e14d62002-12-30 22:08:05 +0000170}
171
172/* GC support. */
173static int
174zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)
175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 ZipImporter *self = (ZipImporter *)obj;
177 Py_VISIT(self->files);
178 return 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000179}
180
181static void
182zipimporter_dealloc(ZipImporter *self)
183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyObject_GC_UnTrack(self);
185 Py_XDECREF(self->archive);
186 Py_XDECREF(self->prefix);
187 Py_XDECREF(self->files);
188 Py_TYPE(self)->tp_free((PyObject *)self);
Just van Rossum52e14d62002-12-30 22:08:05 +0000189}
190
191static PyObject *
192zipimporter_repr(ZipImporter *self)
193{
Victor Stinner028dd972010-08-17 00:04:48 +0000194 if (self->archive == NULL)
195 return PyUnicode_FromString("<zipimporter object \"???\">");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200196 else if (self->prefix != NULL && PyUnicode_GET_LENGTH(self->prefix) != 0)
Victor Stinner07298a12010-10-18 22:45:54 +0000197 return PyUnicode_FromFormat("<zipimporter object \"%U%c%U\">",
Victor Stinner028dd972010-08-17 00:04:48 +0000198 self->archive, SEP, self->prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 else
Victor Stinner07298a12010-10-18 22:45:54 +0000200 return PyUnicode_FromFormat("<zipimporter object \"%U\">",
Victor Stinner028dd972010-08-17 00:04:48 +0000201 self->archive);
Just van Rossum52e14d62002-12-30 22:08:05 +0000202}
203
204/* return fullname.split(".")[-1] */
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400205static PyObject *
206get_subname(PyObject *fullname)
Just van Rossum52e14d62002-12-30 22:08:05 +0000207{
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100208 Py_ssize_t len, dot;
209 if (PyUnicode_READY(fullname) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200210 return NULL;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100211 len = PyUnicode_GET_LENGTH(fullname);
212 dot = PyUnicode_FindChar(fullname, '.', 0, len, -1);
213 if (dot == -1) {
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400214 Py_INCREF(fullname);
215 return fullname;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100216 } else
217 return PyUnicode_Substring(fullname, dot+1, len);
Just van Rossum52e14d62002-12-30 22:08:05 +0000218}
219
220/* Given a (sub)modulename, write the potential file path in the
221 archive (without extension) to the path buffer. Return the
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400222 length of the resulting string.
223
224 return self.prefix + name.replace('.', os.sep) */
225static PyObject*
226make_filename(PyObject *prefix, PyObject *name)
Just van Rossum52e14d62002-12-30 22:08:05 +0000227{
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400228 PyObject *pathobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 Py_UCS4 *p, *buf;
230 Py_ssize_t len;
Just van Rossum52e14d62002-12-30 22:08:05 +0000231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 len = PyUnicode_GET_LENGTH(prefix) + PyUnicode_GET_LENGTH(name) + 1;
233 p = buf = PyMem_Malloc(sizeof(Py_UCS4) * len);
234 if (buf == NULL) {
235 PyErr_NoMemory();
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400236 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200237 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000238
Christian Heimes1b5c76a2012-09-10 02:00:34 +0200239 if (!PyUnicode_AsUCS4(prefix, p, len, 0)) {
240 PyMem_Free(buf);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 return NULL;
Christian Heimes1b5c76a2012-09-10 02:00:34 +0200242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200243 p += PyUnicode_GET_LENGTH(prefix);
244 len -= PyUnicode_GET_LENGTH(prefix);
Christian Heimes1b5c76a2012-09-10 02:00:34 +0200245 if (!PyUnicode_AsUCS4(name, p, len, 1)) {
246 PyMem_Free(buf);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200247 return NULL;
Christian Heimes1b5c76a2012-09-10 02:00:34 +0200248 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400249 for (; *p; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (*p == '.')
251 *p = SEP;
252 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200253 pathobj = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
254 buf, p-buf);
255 PyMem_Free(buf);
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400256 return pathobj;
Just van Rossum52e14d62002-12-30 22:08:05 +0000257}
258
Raymond Hettinger2c45c9a2004-11-10 13:08:35 +0000259enum zi_module_info {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 MI_ERROR,
261 MI_NOT_FOUND,
262 MI_MODULE,
263 MI_PACKAGE
Just van Rossum52e14d62002-12-30 22:08:05 +0000264};
265
Eric V. Smith984b11f2012-05-24 20:21:04 -0400266/* Does this path represent a directory?
267 on error, return < 0
268 if not a dir, return 0
269 if a dir, return 1
270*/
271static int
272check_is_directory(ZipImporter *self, PyObject* prefix, PyObject *path)
273{
274 PyObject *dirpath;
Benjamin Peterson18eac4a2012-05-25 00:24:42 -0700275 int res;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400276
277 /* See if this is a "directory". If so, it's eligible to be part
278 of a namespace package. We test by seeing if the name, with an
279 appended path separator, exists. */
280 dirpath = PyUnicode_FromFormat("%U%U%c", prefix, path, SEP);
281 if (dirpath == NULL)
282 return -1;
283 /* If dirpath is present in self->files, we have a directory. */
Benjamin Peterson18eac4a2012-05-25 00:24:42 -0700284 res = PyDict_Contains(self->files, dirpath);
Eric V. Smith984b11f2012-05-24 20:21:04 -0400285 Py_DECREF(dirpath);
Benjamin Peterson18eac4a2012-05-25 00:24:42 -0700286 return res;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400287}
288
Just van Rossum52e14d62002-12-30 22:08:05 +0000289/* Return some information about a module. */
Raymond Hettinger2c45c9a2004-11-10 13:08:35 +0000290static enum zi_module_info
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400291get_module_info(ZipImporter *self, PyObject *fullname)
Just van Rossum52e14d62002-12-30 22:08:05 +0000292{
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400293 PyObject *subname;
294 PyObject *path, *fullpath, *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 struct st_zip_searchorder *zso;
Just van Rossum52e14d62002-12-30 22:08:05 +0000296
Victor Stinner965a8a12010-10-18 21:44:33 +0000297 subname = get_subname(fullname);
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400298 if (subname == NULL)
299 return MI_ERROR;
Just van Rossum52e14d62002-12-30 22:08:05 +0000300
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400301 path = make_filename(self->prefix, subname);
302 Py_DECREF(subname);
303 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return MI_ERROR;
Just van Rossum52e14d62002-12-30 22:08:05 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 for (zso = zip_searchorder; *zso->suffix; zso++) {
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400307 fullpath = PyUnicode_FromFormat("%U%s", path, zso->suffix);
308 if (fullpath == NULL) {
309 Py_DECREF(path);
310 return MI_ERROR;
311 }
312 item = PyDict_GetItem(self->files, fullpath);
313 Py_DECREF(fullpath);
314 if (item != NULL) {
315 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (zso->type & IS_PACKAGE)
317 return MI_PACKAGE;
318 else
319 return MI_MODULE;
320 }
321 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400322 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return MI_NOT_FOUND;
Just van Rossum52e14d62002-12-30 22:08:05 +0000324}
325
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700326typedef enum {
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700327 FL_ERROR,
328 FL_NOT_FOUND,
329 FL_MODULE_FOUND,
330 FL_NS_FOUND
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700331} find_loader_result;
332
Eric V. Smith984b11f2012-05-24 20:21:04 -0400333/* The guts of "find_loader" and "find_module". Return values:
334 -1: error
335 0: no loader or namespace portions found
336 1: module/package found
337 2: namespace portion found: *namespace_portion will point to the name
338*/
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700339static find_loader_result
Eric V. Smith984b11f2012-05-24 20:21:04 -0400340find_loader(ZipImporter *self, PyObject *fullname, PyObject **namespace_portion)
341{
342 enum zi_module_info mi;
343
344 *namespace_portion = NULL;
345
346 mi = get_module_info(self, fullname);
347 if (mi == MI_ERROR)
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700348 return FL_ERROR;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400349 if (mi == MI_NOT_FOUND) {
350 /* Not a module or regular package. See if this is a directory, and
351 therefore possibly a portion of a namespace package. */
352 int is_dir = check_is_directory(self, self->prefix, fullname);
353 if (is_dir < 0)
354 return -1;
355 if (is_dir) {
356 /* This is possibly a portion of a namespace
357 package. Return the string representing its path,
358 without a trailing separator. */
359 *namespace_portion = PyUnicode_FromFormat("%U%c%U%U",
360 self->archive, SEP,
361 self->prefix, fullname);
362 if (*namespace_portion == NULL)
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700363 return FL_ERROR;
364 return FL_NS_FOUND;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400365 }
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700366 return FL_NOT_FOUND;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400367 }
368 /* This is a module or package. */
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700369 return FL_MODULE_FOUND;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400370}
371
372
Just van Rossum52e14d62002-12-30 22:08:05 +0000373/* Check whether we can satisfy the import of the module named by
374 'fullname'. Return self if we can, None if we can't. */
375static PyObject *
376zipimporter_find_module(PyObject *obj, PyObject *args)
377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 ZipImporter *self = (ZipImporter *)obj;
379 PyObject *path = NULL;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400380 PyObject *fullname;
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700381 PyObject *namespace_portion = NULL;
382 PyObject *result = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000383
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700384 if (!PyArg_ParseTuple(args, "U|O:zipimporter.find_module", &fullname, &path))
385 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000386
Eric V. Smith984b11f2012-05-24 20:21:04 -0400387 switch (find_loader(self, fullname, &namespace_portion)) {
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700388 case FL_ERROR:
Benjamin Petersona6a7a1a2012-05-25 00:22:04 -0700389 return NULL;
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700390 case FL_NS_FOUND:
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700391 /* A namespace portion is not allowed via find_module, so return None. */
Eric V. Smith984b11f2012-05-24 20:21:04 -0400392 Py_DECREF(namespace_portion);
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700393 /* FALL THROUGH */
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700394 case FL_NOT_FOUND:
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700395 result = Py_None;
396 break;
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700397 case FL_MODULE_FOUND:
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700398 result = (PyObject *)self;
399 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 }
Benjamin Petersona6a7a1a2012-05-25 00:22:04 -0700401 Py_INCREF(result);
Benjamin Peterson2d12e142012-05-25 00:19:40 -0700402 return result;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400403}
404
405
406/* Check whether we can satisfy the import of the module named by
407 'fullname', or whether it could be a portion of a namespace
408 package. Return self if we can load it, a string containing the
409 full path if it's a possible namespace portion, None if we
410 can't load it. */
411static PyObject *
412zipimporter_find_loader(PyObject *obj, PyObject *args)
413{
414 ZipImporter *self = (ZipImporter *)obj;
415 PyObject *path = NULL;
416 PyObject *fullname;
417 PyObject *result = NULL;
418 PyObject *namespace_portion = NULL;
419
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700420 if (!PyArg_ParseTuple(args, "U|O:zipimporter.find_module", &fullname, &path))
421 return NULL;
Eric V. Smith984b11f2012-05-24 20:21:04 -0400422
423 switch (find_loader(self, fullname, &namespace_portion)) {
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700424 case FL_ERROR:
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700425 return NULL;
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700426 case FL_NOT_FOUND: /* Not found, return (None, []) */
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700427 result = Py_BuildValue("O[]", Py_None);
428 break;
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700429 case FL_MODULE_FOUND: /* Return (self, []) */
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700430 result = Py_BuildValue("O[]", self);
431 break;
Benjamin Peterson46c214d2012-05-25 10:22:29 -0700432 case FL_NS_FOUND: /* Return (None, [namespace_portion]) */
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700433 result = Py_BuildValue("O[O]", Py_None, namespace_portion);
Benjamin Peterson209e04c2012-05-24 22:35:39 -0700434 Py_DECREF(namespace_portion);
Eric V. Smith984b11f2012-05-24 20:21:04 -0400435 return result;
436 }
Benjamin Peterson5ed7bd72012-05-24 22:54:15 -0700437 return result;
Just van Rossum52e14d62002-12-30 22:08:05 +0000438}
439
440/* Load and return the module named by 'fullname'. */
441static PyObject *
442zipimporter_load_module(PyObject *obj, PyObject *args)
443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 ZipImporter *self = (ZipImporter *)obj;
Victor Stinner26fabe12010-10-18 12:03:25 +0000445 PyObject *code = NULL, *mod, *dict;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400446 PyObject *fullname;
447 PyObject *modpath = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 int ispackage;
Just van Rossum52e14d62002-12-30 22:08:05 +0000449
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400450 if (!PyArg_ParseTuple(args, "U:zipimporter.load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 &fullname))
452 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200453 if (PyUnicode_READY(fullname) == -1)
454 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 code = get_module_code(self, fullname, &ispackage, &modpath);
457 if (code == NULL)
Victor Stinner26fabe12010-10-18 12:03:25 +0000458 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000459
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400460 mod = PyImport_AddModuleObject(fullname);
Victor Stinner26fabe12010-10-18 12:03:25 +0000461 if (mod == NULL)
462 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 dict = PyModule_GetDict(mod);
Just van Rossum52e14d62002-12-30 22:08:05 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* mod.__loader__ = self */
466 if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
467 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (ispackage) {
470 /* add __path__ to the module *before* the code gets
471 executed */
472 PyObject *pkgpath, *fullpath;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400473 PyObject *subname = get_subname(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 int err;
Just van Rossum52e14d62002-12-30 22:08:05 +0000475
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400476 fullpath = PyUnicode_FromFormat("%U%c%U%U",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 self->archive, SEP,
478 self->prefix, subname);
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400479 Py_DECREF(subname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (fullpath == NULL)
481 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000482
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400483 pkgpath = Py_BuildValue("[N]", fullpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (pkgpath == NULL)
485 goto error;
486 err = PyDict_SetItemString(dict, "__path__", pkgpath);
487 Py_DECREF(pkgpath);
488 if (err != 0)
489 goto error;
490 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400491 mod = PyImport_ExecCodeModuleObject(fullname, code, modpath, NULL);
Victor Stinner26fabe12010-10-18 12:03:25 +0000492 Py_CLEAR(code);
493 if (mod == NULL)
494 goto error;
495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (Py_VerboseFlag)
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400497 PySys_FormatStderr("import %U # loaded from Zip %U\n",
Victor Stinner08654e12010-10-18 12:09:02 +0000498 fullname, modpath);
499 Py_DECREF(modpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return mod;
Just van Rossum52e14d62002-12-30 22:08:05 +0000501error:
Victor Stinner26fabe12010-10-18 12:03:25 +0000502 Py_XDECREF(code);
Victor Stinner08654e12010-10-18 12:09:02 +0000503 Py_XDECREF(modpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000505}
506
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000507/* Return a string matching __file__ for the named module */
508static PyObject *
509zipimporter_get_filename(PyObject *obj, PyObject *args)
510{
511 ZipImporter *self = (ZipImporter *)obj;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400512 PyObject *fullname, *code, *modpath;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000513 int ispackage;
514
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400515 if (!PyArg_ParseTuple(args, "U:zipimporter.get_filename",
Victor Stinner9e40fad2010-10-18 22:34:46 +0000516 &fullname))
Victor Stinnerc342fca2010-10-18 11:39:05 +0000517 return NULL;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000518
519 /* Deciding the filename requires working out where the code
520 would come from if the module was actually loaded */
521 code = get_module_code(self, fullname, &ispackage, &modpath);
522 if (code == NULL)
Victor Stinnerc342fca2010-10-18 11:39:05 +0000523 return NULL;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000524 Py_DECREF(code); /* Only need the path info */
525
Victor Stinner08654e12010-10-18 12:09:02 +0000526 return modpath;
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000527}
528
Just van Rossum52e14d62002-12-30 22:08:05 +0000529/* Return a bool signifying whether the module is a package or not. */
530static PyObject *
531zipimporter_is_package(PyObject *obj, PyObject *args)
532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 ZipImporter *self = (ZipImporter *)obj;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400534 PyObject *fullname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 enum zi_module_info mi;
Just van Rossum52e14d62002-12-30 22:08:05 +0000536
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400537 if (!PyArg_ParseTuple(args, "U:zipimporter.is_package",
Victor Stinner965a8a12010-10-18 21:44:33 +0000538 &fullname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 mi = get_module_info(self, fullname);
542 if (mi == MI_ERROR)
Victor Stinner965a8a12010-10-18 21:44:33 +0000543 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (mi == MI_NOT_FOUND) {
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400545 PyErr_Format(ZipImportError, "can't find module %R", fullname);
Victor Stinner965a8a12010-10-18 21:44:33 +0000546 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 }
548 return PyBool_FromLong(mi == MI_PACKAGE);
Just van Rossum52e14d62002-12-30 22:08:05 +0000549}
550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200551
Just van Rossum52e14d62002-12-30 22:08:05 +0000552static PyObject *
553zipimporter_get_data(PyObject *obj, PyObject *args)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 ZipImporter *self = (ZipImporter *)obj;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100556 PyObject *path, *key;
Just van Rossum52e14d62002-12-30 22:08:05 +0000557#ifdef ALTSEP
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100558 _Py_IDENTIFIER(replace);
Just van Rossum52e14d62002-12-30 22:08:05 +0000559#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 PyObject *toc_entry;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100561 Py_ssize_t path_start, path_len, len;
Just van Rossum52e14d62002-12-30 22:08:05 +0000562
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100563 if (!PyArg_ParseTuple(args, "U:zipimporter.get_data", &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200566#ifdef ALTSEP
Martin v. Löwiscfa61292011-10-31 09:01:22 +0100567 path = _PyObject_CallMethodId(path, &PyId_replace, "CC", ALTSEP, SEP);
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100568 if (!path)
569 return NULL;
570#else
571 Py_INCREF(path);
Just van Rossum52e14d62002-12-30 22:08:05 +0000572#endif
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100573 if (PyUnicode_READY(path) == -1)
574 goto error;
575
576 path_len = PyUnicode_GET_LENGTH(path);
577
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200578 len = PyUnicode_GET_LENGTH(self->archive);
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100579 path_start = 0;
580 if (PyUnicode_Tailmatch(path, self->archive, 0, len, -1)
581 && PyUnicode_READ_CHAR(path, len) == SEP) {
582 path_start = len + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000584
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100585 key = PyUnicode_Substring(path, path_start, path_len);
Victor Stinner60fe8d92010-08-16 23:48:11 +0000586 if (key == NULL)
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100587 goto error;
Victor Stinner60fe8d92010-08-16 23:48:11 +0000588 toc_entry = PyDict_GetItem(self->files, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (toc_entry == NULL) {
Victor Stinner60fe8d92010-08-16 23:48:11 +0000590 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, key);
591 Py_DECREF(key);
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100592 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 }
Victor Stinner60fe8d92010-08-16 23:48:11 +0000594 Py_DECREF(key);
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100595 Py_DECREF(path);
Victor Stinner60fe8d92010-08-16 23:48:11 +0000596 return get_data(self->archive, toc_entry);
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100597 error:
598 Py_DECREF(path);
599 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000600}
601
602static PyObject *
603zipimporter_get_code(PyObject *obj, PyObject *args)
604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 ZipImporter *self = (ZipImporter *)obj;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400606 PyObject *fullname;
Just van Rossum52e14d62002-12-30 22:08:05 +0000607
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400608 if (!PyArg_ParseTuple(args, "U:zipimporter.get_code", &fullname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return get_module_code(self, fullname, NULL, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +0000612}
613
614static PyObject *
615zipimporter_get_source(PyObject *obj, PyObject *args)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 ZipImporter *self = (ZipImporter *)obj;
618 PyObject *toc_entry;
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400619 PyObject *fullname, *subname, *path, *fullpath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 enum zi_module_info mi;
Just van Rossum52e14d62002-12-30 22:08:05 +0000621
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400622 if (!PyArg_ParseTuple(args, "U:zipimporter.get_source", &fullname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 mi = get_module_info(self, fullname);
Victor Stinner965a8a12010-10-18 21:44:33 +0000626 if (mi == MI_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return NULL;
Victor Stinner04106562010-10-18 20:44:08 +0000628 if (mi == MI_NOT_FOUND) {
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400629 PyErr_Format(ZipImportError, "can't find module %R", fullname);
Victor Stinner04106562010-10-18 20:44:08 +0000630 return NULL;
631 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400632
Victor Stinner965a8a12010-10-18 21:44:33 +0000633 subname = get_subname(fullname);
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400634 if (subname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000636
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400637 path = make_filename(self->prefix, subname);
638 Py_DECREF(subname);
639 if (path == NULL)
640 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000641
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400642 if (mi == MI_PACKAGE)
643 fullpath = PyUnicode_FromFormat("%U%c__init__.py", path, SEP);
644 else
645 fullpath = PyUnicode_FromFormat("%U.py", path);
646 Py_DECREF(path);
647 if (fullpath == NULL)
648 return NULL;
649
650 toc_entry = PyDict_GetItem(self->files, fullpath);
651 Py_DECREF(fullpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (toc_entry != NULL) {
Victor Stinner60fe8d92010-08-16 23:48:11 +0000653 PyObject *res, *bytes;
654 bytes = get_data(self->archive, toc_entry);
655 if (bytes == NULL)
656 return NULL;
657 res = PyUnicode_FromStringAndSize(PyBytes_AS_STRING(bytes),
658 PyBytes_GET_SIZE(bytes));
659 Py_DECREF(bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return res;
661 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 /* we have the module, but no source */
664 Py_INCREF(Py_None);
665 return Py_None;
Just van Rossum52e14d62002-12-30 22:08:05 +0000666}
667
668PyDoc_STRVAR(doc_find_module,
669"find_module(fullname, path=None) -> self or None.\n\
670\n\
671Search for a module specified by 'fullname'. 'fullname' must be the\n\
672fully qualified (dotted) module name. It returns the zipimporter\n\
673instance itself if the module was found, or None if it wasn't.\n\
674The optional 'path' argument is ignored -- it's there for compatibility\n\
675with the importer protocol.");
676
Eric V. Smith984b11f2012-05-24 20:21:04 -0400677PyDoc_STRVAR(doc_find_loader,
678"find_loader(fullname, path=None) -> self, str or None.\n\
679\n\
680Search for a module specified by 'fullname'. 'fullname' must be the\n\
681fully qualified (dotted) module name. It returns the zipimporter\n\
682instance itself if the module was found, a string containing the\n\
683full path name if it's possibly a portion of a namespace package,\n\
684or None otherwise. The optional 'path' argument is ignored -- it's\n\
685 there for compatibility with the importer protocol.");
686
Just van Rossum52e14d62002-12-30 22:08:05 +0000687PyDoc_STRVAR(doc_load_module,
688"load_module(fullname) -> module.\n\
689\n\
690Load the module specified by 'fullname'. 'fullname' must be the\n\
691fully qualified (dotted) module name. It returns the imported\n\
692module, or raises ZipImportError if it wasn't found.");
693
694PyDoc_STRVAR(doc_get_data,
695"get_data(pathname) -> string with file data.\n\
696\n\
697Return the data associated with 'pathname'. Raise IOError if\n\
698the file wasn't found.");
699
700PyDoc_STRVAR(doc_is_package,
701"is_package(fullname) -> bool.\n\
702\n\
703Return True if the module specified by fullname is a package.\n\
Brian Curtin32839732010-07-21 01:44:19 +0000704Raise ZipImportError if the module couldn't be found.");
Just van Rossum52e14d62002-12-30 22:08:05 +0000705
706PyDoc_STRVAR(doc_get_code,
707"get_code(fullname) -> code object.\n\
708\n\
709Return the code object for the specified module. Raise ZipImportError\n\
Brian Curtin32839732010-07-21 01:44:19 +0000710if the module couldn't be found.");
Just van Rossum52e14d62002-12-30 22:08:05 +0000711
712PyDoc_STRVAR(doc_get_source,
713"get_source(fullname) -> source string.\n\
714\n\
715Return the source code for the specified module. Raise ZipImportError\n\
Brian Curtin32839732010-07-21 01:44:19 +0000716if the module couldn't be found, return None if the archive does\n\
Just van Rossum52e14d62002-12-30 22:08:05 +0000717contain the module, but has no source for it.");
718
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000719
720PyDoc_STRVAR(doc_get_filename,
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000721"get_filename(fullname) -> filename string.\n\
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000722\n\
723Return the filename for the specified module.");
724
Just van Rossum52e14d62002-12-30 22:08:05 +0000725static PyMethodDef zipimporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 {"find_module", zipimporter_find_module, METH_VARARGS,
727 doc_find_module},
Eric V. Smith984b11f2012-05-24 20:21:04 -0400728 {"find_loader", zipimporter_find_loader, METH_VARARGS,
729 doc_find_loader},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 {"load_module", zipimporter_load_module, METH_VARARGS,
731 doc_load_module},
732 {"get_data", zipimporter_get_data, METH_VARARGS,
733 doc_get_data},
734 {"get_code", zipimporter_get_code, METH_VARARGS,
735 doc_get_code},
736 {"get_source", zipimporter_get_source, METH_VARARGS,
737 doc_get_source},
738 {"get_filename", zipimporter_get_filename, METH_VARARGS,
739 doc_get_filename},
740 {"is_package", zipimporter_is_package, METH_VARARGS,
741 doc_is_package},
742 {NULL, NULL} /* sentinel */
Just van Rossum52e14d62002-12-30 22:08:05 +0000743};
744
745static PyMemberDef zipimporter_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
747 {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
748 {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
749 {NULL}
Just van Rossum52e14d62002-12-30 22:08:05 +0000750};
751
752PyDoc_STRVAR(zipimporter_doc,
753"zipimporter(archivepath) -> zipimporter object\n\
754\n\
755Create a new zipimporter instance. 'archivepath' must be a path to\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000756a zipfile, or to a specific path inside a zipfile. For example, it can be\n\
757'/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a\n\
758valid directory inside the archive.\n\
759\n\
760'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip\n\
761archive.\n\
762\n\
763The 'archive' attribute of zipimporter objects contains the name of the\n\
764zipfile targeted.");
Just van Rossum52e14d62002-12-30 22:08:05 +0000765
766#define DEFERRED_ADDRESS(ADDR) 0
767
768static PyTypeObject ZipImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
770 "zipimport.zipimporter",
771 sizeof(ZipImporter),
772 0, /* tp_itemsize */
773 (destructor)zipimporter_dealloc, /* tp_dealloc */
774 0, /* tp_print */
775 0, /* tp_getattr */
776 0, /* tp_setattr */
777 0, /* tp_reserved */
778 (reprfunc)zipimporter_repr, /* tp_repr */
779 0, /* tp_as_number */
780 0, /* tp_as_sequence */
781 0, /* tp_as_mapping */
782 0, /* tp_hash */
783 0, /* tp_call */
784 0, /* tp_str */
785 PyObject_GenericGetAttr, /* tp_getattro */
786 0, /* tp_setattro */
787 0, /* tp_as_buffer */
788 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
789 Py_TPFLAGS_HAVE_GC, /* tp_flags */
790 zipimporter_doc, /* tp_doc */
791 zipimporter_traverse, /* tp_traverse */
792 0, /* tp_clear */
793 0, /* tp_richcompare */
794 0, /* tp_weaklistoffset */
795 0, /* tp_iter */
796 0, /* tp_iternext */
797 zipimporter_methods, /* tp_methods */
798 zipimporter_members, /* tp_members */
799 0, /* tp_getset */
800 0, /* tp_base */
801 0, /* tp_dict */
802 0, /* tp_descr_get */
803 0, /* tp_descr_set */
804 0, /* tp_dictoffset */
805 (initproc)zipimporter_init, /* tp_init */
806 PyType_GenericAlloc, /* tp_alloc */
807 PyType_GenericNew, /* tp_new */
808 PyObject_GC_Del, /* tp_free */
Just van Rossum52e14d62002-12-30 22:08:05 +0000809};
810
811
812/* implementation */
813
Just van Rossum52e14d62002-12-30 22:08:05 +0000814/* Given a buffer, return the long that is represented by the first
815 4 bytes, encoded as little endian. This partially reimplements
816 marshal.c:r_long() */
817static long
818get_long(unsigned char *buf) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 long x;
820 x = buf[0];
821 x |= (long)buf[1] << 8;
822 x |= (long)buf[2] << 16;
823 x |= (long)buf[3] << 24;
Just van Rossum52e14d62002-12-30 22:08:05 +0000824#if SIZEOF_LONG > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 /* Sign extension for 64-bit machines */
826 x |= -(x & 0x80000000L);
Just van Rossum52e14d62002-12-30 22:08:05 +0000827#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return x;
Just van Rossum52e14d62002-12-30 22:08:05 +0000829}
830
831/*
832 read_directory(archive) -> files dict (new reference)
833
834 Given a path to a Zip archive, build a dict, mapping file names
835 (local to the archive, using SEP as a separator) to toc entries.
836
837 A toc_entry is a tuple:
838
Victor Stinner08654e12010-10-18 12:09:02 +0000839 (__file__, # value to use for __file__, available for all files,
840 # encoded to the filesystem encoding
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 compress, # compression kind; 0 for uncompressed
842 data_size, # size of compressed data on disk
843 file_size, # size of decompressed data
844 file_offset, # offset of file header from start of archive
845 time, # mod time of file (in dos format)
846 date, # mod data of file (in dos format)
847 crc, # crc checksum of the data
Victor Stinnerc342fca2010-10-18 11:39:05 +0000848 )
Just van Rossum52e14d62002-12-30 22:08:05 +0000849
850 Directories can be recognized by the trailing SEP in the name,
851 data_size and file_offset are 0.
852*/
853static PyObject *
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400854read_directory(PyObject *archive)
Just van Rossum52e14d62002-12-30 22:08:05 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *files = NULL;
857 FILE *fp;
Victor Stinnerd36c8212010-10-18 12:13:46 +0000858 unsigned short flags;
Gregory P. Smithab320662012-01-30 15:17:33 -0800859 short compress, time, date, name_size;
860 long crc, data_size, file_size, header_size;
861 Py_ssize_t file_offset, header_position, header_offset;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200862 long l, count;
863 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 char name[MAXPATHLEN + 5];
Victor Stinner2460a432010-08-16 17:54:28 +0000865 PyObject *nameobj = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 char *p, endof_central_dir[22];
Gregory P. Smithab320662012-01-30 15:17:33 -0800867 Py_ssize_t arc_offset; /* Absolute offset to start of the zip-archive. */
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100868 PyObject *path;
Victor Stinnerd36c8212010-10-18 12:13:46 +0000869 const char *charset;
Victor Stinner4ee65a92011-01-22 10:30:29 +0000870 int bootstrap;
Just van Rossum52e14d62002-12-30 22:08:05 +0000871
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400872 fp = _Py_fopen(archive, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (fp == NULL) {
Victor Stinnerbd206e22011-12-18 21:04:17 +0100874 if (!PyErr_Occurred())
Victor Stinner35734762011-12-18 21:05:22 +0100875 PyErr_Format(ZipImportError, "can't open Zip file: %R", archive);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 return NULL;
877 }
Jesus Cea09bf7a72012-10-03 02:13:05 +0200878
879 if (fseek(fp, -22, SEEK_END) == -1) {
880 fclose(fp);
881 PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
882 return NULL;
883 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 header_position = ftell(fp);
885 if (fread(endof_central_dir, 1, 22, fp) != 22) {
886 fclose(fp);
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400887 PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 return NULL;
889 }
890 if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
891 /* Bad: End of Central Dir signature */
892 fclose(fp);
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400893 PyErr_Format(ZipImportError, "not a Zip file: %R", archive);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return NULL;
895 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 header_size = get_long((unsigned char *)endof_central_dir + 12);
898 header_offset = get_long((unsigned char *)endof_central_dir + 16);
899 arc_offset = header_position - header_offset - header_size;
900 header_offset += arc_offset;
Just van Rossum52e14d62002-12-30 22:08:05 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 files = PyDict_New();
903 if (files == NULL)
904 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Start of Central Directory */
907 count = 0;
908 for (;;) {
909 PyObject *t;
910 int err;
Just van Rossum52e14d62002-12-30 22:08:05 +0000911
Jesus Cea09bf7a72012-10-03 02:13:05 +0200912 if (fseek(fp, header_offset, 0) == -1) /* Start of file header */
913 goto fseek_error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 l = PyMarshal_ReadLongFromFile(fp);
915 if (l != 0x02014B50)
916 break; /* Bad: Central Dir File Header */
Jesus Cea09bf7a72012-10-03 02:13:05 +0200917 if (fseek(fp, header_offset + 8, 0) == -1)
918 goto fseek_error;
Victor Stinnerd36c8212010-10-18 12:13:46 +0000919 flags = (unsigned short)PyMarshal_ReadShortFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 compress = PyMarshal_ReadShortFromFile(fp);
921 time = PyMarshal_ReadShortFromFile(fp);
922 date = PyMarshal_ReadShortFromFile(fp);
923 crc = PyMarshal_ReadLongFromFile(fp);
924 data_size = PyMarshal_ReadLongFromFile(fp);
925 file_size = PyMarshal_ReadLongFromFile(fp);
926 name_size = PyMarshal_ReadShortFromFile(fp);
927 header_size = 46 + name_size +
928 PyMarshal_ReadShortFromFile(fp) +
929 PyMarshal_ReadShortFromFile(fp);
Jesus Cea09bf7a72012-10-03 02:13:05 +0200930 if (fseek(fp, header_offset + 42, 0) == -1)
931 goto fseek_error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
933 if (name_size > MAXPATHLEN)
934 name_size = MAXPATHLEN;
Just van Rossum52e14d62002-12-30 22:08:05 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 p = name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200937 for (i = 0; i < (Py_ssize_t)name_size; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 *p = (char)getc(fp);
939 if (*p == '/')
940 *p = SEP;
941 p++;
942 }
943 *p = 0; /* Add terminating null byte */
944 header_offset += header_size;
Just van Rossum52e14d62002-12-30 22:08:05 +0000945
Victor Stinner4ee65a92011-01-22 10:30:29 +0000946 bootstrap = 0;
Victor Stinnerd36c8212010-10-18 12:13:46 +0000947 if (flags & 0x0800)
948 charset = "utf-8";
Victor Stinner4ee65a92011-01-22 10:30:29 +0000949 else if (!PyThreadState_GET()->interp->codecs_initialized) {
950 /* During bootstrap, we may need to load the encodings
951 package from a ZIP file. But the cp437 encoding is implemented
952 in Python in the encodings package.
953
954 Break out of this dependency by assuming that the path to
955 the encodings module is ASCII-only. */
956 charset = "ascii";
957 bootstrap = 1;
958 }
Victor Stinnerd36c8212010-10-18 12:13:46 +0000959 else
960 charset = "cp437";
961 nameobj = PyUnicode_Decode(name, name_size, charset, NULL);
Victor Stinner4ee65a92011-01-22 10:30:29 +0000962 if (nameobj == NULL) {
963 if (bootstrap)
964 PyErr_Format(PyExc_NotImplementedError,
965 "bootstrap issue: python%i%i.zip contains non-ASCII "
966 "filenames without the unicode flag",
967 PY_MAJOR_VERSION, PY_MINOR_VERSION);
Victor Stinner2460a432010-08-16 17:54:28 +0000968 goto error;
Victor Stinner4ee65a92011-01-22 10:30:29 +0000969 }
Stefan Krah000fde92012-08-20 14:14:49 +0200970 if (PyUnicode_READY(nameobj) == -1)
971 goto error;
Martin v. Löwisa72e78b2011-10-31 08:33:37 +0100972 path = PyUnicode_FromFormat("%U%c%U", archive, SEP, nameobj);
973 if (path == NULL)
Victor Stinner2460a432010-08-16 17:54:28 +0000974 goto error;
Gregory P. Smithcc6abd52012-01-30 15:55:29 -0800975 t = Py_BuildValue("Nhllnhhl", path, compress, data_size,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 file_size, file_offset, time, date, crc);
977 if (t == NULL)
978 goto error;
Victor Stinner2460a432010-08-16 17:54:28 +0000979 err = PyDict_SetItem(files, nameobj, t);
980 Py_CLEAR(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 Py_DECREF(t);
982 if (err != 0)
983 goto error;
984 count++;
985 }
986 fclose(fp);
987 if (Py_VerboseFlag)
Victor Stinnerf6b563a2011-03-14 20:46:50 -0400988 PySys_FormatStderr("# zipimport: found %ld names in %R\n",
989 count, archive);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 return files;
Jesus Cea09bf7a72012-10-03 02:13:05 +0200991fseek_error:
992 fclose(fp);
993 Py_XDECREF(files);
994 Py_XDECREF(nameobj);
995 PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
996 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000997error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 fclose(fp);
999 Py_XDECREF(files);
Victor Stinner2460a432010-08-16 17:54:28 +00001000 Py_XDECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001002}
1003
1004/* Return the zlib.decompress function object, or NULL if zlib couldn't
1005 be imported. The function is cached when found, so subsequent calls
Victor Stinner4925cde2011-05-20 00:16:09 +02001006 don't import zlib again. */
Just van Rossum52e14d62002-12-30 22:08:05 +00001007static PyObject *
1008get_decompress_func(void)
1009{
Victor Stinner4925cde2011-05-20 00:16:09 +02001010 static int importing_zlib = 0;
1011 PyObject *zlib;
1012 PyObject *decompress;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001013 _Py_IDENTIFIER(decompress);
Just van Rossum52e14d62002-12-30 22:08:05 +00001014
Victor Stinner4925cde2011-05-20 00:16:09 +02001015 if (importing_zlib != 0)
1016 /* Someone has a zlib.py[co] in their Zip file;
1017 let's avoid a stack overflow. */
1018 return NULL;
1019 importing_zlib = 1;
1020 zlib = PyImport_ImportModuleNoBlock("zlib");
1021 importing_zlib = 0;
1022 if (zlib != NULL) {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001023 decompress = _PyObject_GetAttrId(zlib,
1024 &PyId_decompress);
Victor Stinner4925cde2011-05-20 00:16:09 +02001025 Py_DECREF(zlib);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 }
Victor Stinner4925cde2011-05-20 00:16:09 +02001027 else {
1028 PyErr_Clear();
1029 decompress = NULL;
1030 }
1031 if (Py_VerboseFlag)
1032 PySys_WriteStderr("# zipimport: zlib %s\n",
1033 zlib != NULL ? "available": "UNAVAILABLE");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 return decompress;
Just van Rossum52e14d62002-12-30 22:08:05 +00001035}
1036
1037/* Given a path to a Zip file and a toc_entry, return the (uncompressed)
1038 data as a new reference. */
1039static PyObject *
Victor Stinner60fe8d92010-08-16 23:48:11 +00001040get_data(PyObject *archive, PyObject *toc_entry)
Just van Rossum52e14d62002-12-30 22:08:05 +00001041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *raw_data, *data = NULL, *decompress;
1043 char *buf;
1044 FILE *fp;
1045 int err;
1046 Py_ssize_t bytes_read = 0;
1047 long l;
Victor Stinner60fe8d92010-08-16 23:48:11 +00001048 PyObject *datapath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 long compress, data_size, file_size, file_offset, bytes_size;
1050 long time, date, crc;
Just van Rossum52e14d62002-12-30 22:08:05 +00001051
Victor Stinner60fe8d92010-08-16 23:48:11 +00001052 if (!PyArg_ParseTuple(toc_entry, "Olllllll", &datapath, &compress,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 &data_size, &file_size, &file_offset, &time,
1054 &date, &crc)) {
1055 return NULL;
1056 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001057
Victor Stinner60fe8d92010-08-16 23:48:11 +00001058 fp = _Py_fopen(archive, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (!fp) {
Victor Stinnerbd206e22011-12-18 21:04:17 +01001060 if (!PyErr_Occurred())
1061 PyErr_Format(PyExc_IOError,
1062 "zipimport: can not open file %U", archive);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 return NULL;
1064 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 /* Check to make sure the local file header is correct */
Jesus Cea09bf7a72012-10-03 02:13:05 +02001067 if (fseek(fp, file_offset, 0) == -1) {
1068 fclose(fp);
1069 PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
1070 return NULL;
1071 }
1072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 l = PyMarshal_ReadLongFromFile(fp);
1074 if (l != 0x04034B50) {
1075 /* Bad: Local File Header */
1076 PyErr_Format(ZipImportError,
Victor Stinner60fe8d92010-08-16 23:48:11 +00001077 "bad local file header in %U",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 archive);
1079 fclose(fp);
1080 return NULL;
1081 }
Jesus Cea09bf7a72012-10-03 02:13:05 +02001082 if (fseek(fp, file_offset + 26, 0) == -1) {
1083 fclose(fp);
1084 PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
1085 return NULL;
1086 }
1087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 l = 30 + PyMarshal_ReadShortFromFile(fp) +
1089 PyMarshal_ReadShortFromFile(fp); /* local header size */
1090 file_offset += l; /* Start of file data */
Just van Rossum52e14d62002-12-30 22:08:05 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 bytes_size = compress == 0 ? data_size : data_size + 1;
1093 if (bytes_size == 0)
1094 bytes_size++;
1095 raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size);
Just van Rossum52e14d62002-12-30 22:08:05 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (raw_data == NULL) {
1098 fclose(fp);
1099 return NULL;
1100 }
1101 buf = PyBytes_AsString(raw_data);
Just van Rossum52e14d62002-12-30 22:08:05 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 err = fseek(fp, file_offset, 0);
Jesus Cea09bf7a72012-10-03 02:13:05 +02001104 if (err == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 bytes_read = fread(buf, 1, data_size, fp);
Jesus Cea09bf7a72012-10-03 02:13:05 +02001106 } else {
1107 fclose(fp);
1108 PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
1109 return NULL;
1110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 fclose(fp);
1112 if (err || bytes_read != data_size) {
1113 PyErr_SetString(PyExc_IOError,
1114 "zipimport: can't read data");
1115 Py_DECREF(raw_data);
1116 return NULL;
1117 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (compress != 0) {
1120 buf[data_size] = 'Z'; /* saw this in zipfile.py */
1121 data_size++;
1122 }
1123 buf[data_size] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (compress == 0) { /* data is not compressed */
1126 data = PyBytes_FromStringAndSize(buf, data_size);
1127 Py_DECREF(raw_data);
1128 return data;
1129 }
1130
1131 /* Decompress with zlib */
1132 decompress = get_decompress_func();
1133 if (decompress == NULL) {
1134 PyErr_SetString(ZipImportError,
1135 "can't decompress data; "
1136 "zlib not available");
1137 goto error;
1138 }
1139 data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
Victor Stinner4925cde2011-05-20 00:16:09 +02001140 Py_DECREF(decompress);
Just van Rossum52e14d62002-12-30 22:08:05 +00001141error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 Py_DECREF(raw_data);
1143 return data;
Just van Rossum52e14d62002-12-30 22:08:05 +00001144}
1145
1146/* Lenient date/time comparison function. The precision of the mtime
1147 in the archive is lower than the mtime stored in a .pyc: we
1148 must allow a difference of at most one second. */
1149static int
1150eq_mtime(time_t t1, time_t t2)
1151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 time_t d = t1 - t2;
1153 if (d < 0)
1154 d = -d;
1155 /* dostime only stores even seconds, so be lenient */
1156 return d <= 1;
Just van Rossum52e14d62002-12-30 22:08:05 +00001157}
1158
1159/* Given the contents of a .py[co] file in a buffer, unmarshal the data
1160 and return the code object. Return None if it the magic word doesn't
1161 match (we do this instead of raising an exception as we fall back
1162 to .py if available and we don't want to mask other errors).
1163 Returns a new reference. */
1164static PyObject *
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001165unmarshal_code(PyObject *pathname, PyObject *data, time_t mtime)
Just van Rossum52e14d62002-12-30 22:08:05 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyObject *code;
1168 char *buf = PyBytes_AsString(data);
1169 Py_ssize_t size = PyBytes_Size(data);
Just van Rossum52e14d62002-12-30 22:08:05 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (size <= 9) {
1172 PyErr_SetString(ZipImportError,
1173 "bad pyc data");
1174 return NULL;
1175 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
1178 if (Py_VerboseFlag)
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001179 PySys_FormatStderr("# %R has bad magic\n",
1180 pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_INCREF(Py_None);
1182 return Py_None; /* signal caller to try alternative */
1183 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
1186 mtime)) {
1187 if (Py_VerboseFlag)
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001188 PySys_FormatStderr("# %R has bad mtime\n",
1189 pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 Py_INCREF(Py_None);
1191 return Py_None; /* signal caller to try alternative */
1192 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001193
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001194 /* XXX the pyc's size field is ignored; timestamp collisions are probably
1195 unimportant with zip files. */
1196 code = PyMarshal_ReadObjectFromString(buf + 12, size - 12);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (code == NULL)
1198 return NULL;
1199 if (!PyCode_Check(code)) {
1200 Py_DECREF(code);
1201 PyErr_Format(PyExc_TypeError,
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001202 "compiled module %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 pathname);
1204 return NULL;
1205 }
1206 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001207}
1208
1209/* Replace any occurances of "\r\n?" in the input string with "\n".
1210 This converts DOS and Mac line endings to Unix line endings.
1211 Also append a trailing "\n" to be compatible with
1212 PyParser_SimpleParseFile(). Returns a new reference. */
1213static PyObject *
1214normalize_line_endings(PyObject *source)
1215{
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001216 char *buf, *q, *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyObject *fixed_source;
1218 int len = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +00001219
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001220 p = PyBytes_AsString(source);
1221 if (p == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 return PyBytes_FromStringAndSize("\n\0", 2);
1223 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* one char extra for trailing \n and one for terminating \0 */
1226 buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2);
1227 if (buf == NULL) {
1228 PyErr_SetString(PyExc_MemoryError,
1229 "zipimport: no memory to allocate "
1230 "source buffer");
1231 return NULL;
1232 }
1233 /* replace "\r\n?" by "\n" */
1234 for (q = buf; *p != '\0'; p++) {
1235 if (*p == '\r') {
1236 *q++ = '\n';
1237 if (*(p + 1) == '\n')
1238 p++;
1239 }
1240 else
1241 *q++ = *p;
1242 len++;
1243 }
1244 *q++ = '\n'; /* add trailing \n */
1245 *q = '\0';
1246 fixed_source = PyBytes_FromStringAndSize(buf, len + 2);
1247 PyMem_Free(buf);
1248 return fixed_source;
Just van Rossum52e14d62002-12-30 22:08:05 +00001249}
1250
1251/* Given a string buffer containing Python source code, compile it
1252 return and return a code object as a new reference. */
1253static PyObject *
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001254compile_source(PyObject *pathname, PyObject *source)
Just van Rossum52e14d62002-12-30 22:08:05 +00001255{
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001256 PyObject *code, *fixed_source, *pathbytes;
Just van Rossum52e14d62002-12-30 22:08:05 +00001257
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001258 pathbytes = PyUnicode_EncodeFSDefault(pathname);
1259 if (pathbytes == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001261
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001262 fixed_source = normalize_line_endings(source);
1263 if (fixed_source == NULL) {
1264 Py_DECREF(pathbytes);
1265 return NULL;
1266 }
1267
1268 code = Py_CompileString(PyBytes_AsString(fixed_source),
1269 PyBytes_AsString(pathbytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 Py_file_input);
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001271 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 Py_DECREF(fixed_source);
1273 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001274}
1275
1276/* Convert the date/time values found in the Zip archive to a value
1277 that's compatible with the time stamp stored in .pyc files. */
Neal Norwitz29fd2ba2003-03-23 13:21:03 +00001278static time_t
1279parse_dostime(int dostime, int dosdate)
Just van Rossum52e14d62002-12-30 22:08:05 +00001280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 struct tm stm;
Just van Rossum52e14d62002-12-30 22:08:05 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 memset((void *) &stm, '\0', sizeof(stm));
Christian Heimes679db4a2008-01-18 09:56:22 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 stm.tm_sec = (dostime & 0x1f) * 2;
1286 stm.tm_min = (dostime >> 5) & 0x3f;
1287 stm.tm_hour = (dostime >> 11) & 0x1f;
1288 stm.tm_mday = dosdate & 0x1f;
1289 stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;
1290 stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;
1291 stm.tm_isdst = -1; /* wday/yday is ignored */
Just van Rossum52e14d62002-12-30 22:08:05 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return mktime(&stm);
Just van Rossum52e14d62002-12-30 22:08:05 +00001294}
1295
1296/* Given a path to a .pyc or .pyo file in the archive, return the
Ezio Melotti13925002011-03-16 11:05:33 +02001297 modification time of the matching .py file, or 0 if no source
Just van Rossum52e14d62002-12-30 22:08:05 +00001298 is available. */
1299static time_t
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001300get_mtime_of_source(ZipImporter *self, PyObject *path)
Just van Rossum52e14d62002-12-30 22:08:05 +00001301{
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001302 PyObject *toc_entry, *stripped;
1303 time_t mtime;
1304
1305 /* strip 'c' or 'o' from *.py[co] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306 if (PyUnicode_READY(path) == -1)
1307 return (time_t)-1;
1308 stripped = PyUnicode_FromKindAndData(PyUnicode_KIND(path),
1309 PyUnicode_DATA(path),
1310 PyUnicode_GET_LENGTH(path) - 1);
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001311 if (stripped == NULL)
1312 return (time_t)-1;
1313
1314 toc_entry = PyDict_GetItem(self->files, stripped);
1315 Py_DECREF(stripped);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (toc_entry != NULL && PyTuple_Check(toc_entry) &&
1317 PyTuple_Size(toc_entry) == 8) {
1318 /* fetch the time stamp of the .py file for comparison
1319 with an embedded pyc time stamp */
1320 int time, date;
1321 time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5));
1322 date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6));
1323 mtime = parse_dostime(time, date);
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001324 } else
1325 mtime = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 return mtime;
Just van Rossum52e14d62002-12-30 22:08:05 +00001327}
1328
1329/* Return the code object for the module named by 'fullname' from the
1330 Zip archive as a new reference. */
1331static PyObject *
1332get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 time_t mtime, PyObject *toc_entry)
Just van Rossum52e14d62002-12-30 22:08:05 +00001334{
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001335 PyObject *data, *modpath, *code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001336
Victor Stinner60fe8d92010-08-16 23:48:11 +00001337 data = get_data(self->archive, toc_entry);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (data == NULL)
1339 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001340
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001341 modpath = PyTuple_GetItem(toc_entry, 0);
Victor Stinner2a94f4c2010-10-18 12:15:34 +00001342 if (isbytecode)
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001343 code = unmarshal_code(modpath, data, mtime);
Victor Stinner2a94f4c2010-10-18 12:15:34 +00001344 else
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001345 code = compile_source(modpath, data);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_DECREF(data);
1347 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001348}
1349
Ezio Melotti42da6632011-03-15 05:18:48 +02001350/* Get the code object associated with the module specified by
Just van Rossum52e14d62002-12-30 22:08:05 +00001351 'fullname'. */
1352static PyObject *
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001353get_module_code(ZipImporter *self, PyObject *fullname,
Victor Stinner08654e12010-10-18 12:09:02 +00001354 int *p_ispackage, PyObject **p_modpath)
Just van Rossum52e14d62002-12-30 22:08:05 +00001355{
Gregory P. Smith95c7c462011-05-21 05:19:42 -07001356 PyObject *code = NULL, *toc_entry, *subname;
Victor Stinner9a2261a2011-05-26 13:59:41 +02001357 PyObject *path, *fullpath = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 struct st_zip_searchorder *zso;
Just van Rossum52e14d62002-12-30 22:08:05 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 subname = get_subname(fullname);
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001361 if (subname == NULL)
1362 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001363
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001364 path = make_filename(self->prefix, subname);
1365 Py_DECREF(subname);
1366 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 for (zso = zip_searchorder; *zso->suffix; zso++) {
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001370 code = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001371
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001372 fullpath = PyUnicode_FromFormat("%U%s", path, zso->suffix);
1373 if (fullpath == NULL)
1374 goto exit;
1375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (Py_VerboseFlag > 1)
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001377 PySys_FormatStderr("# trying %U%c%U\n",
1378 self->archive, (int)SEP, fullpath);
1379 toc_entry = PyDict_GetItem(self->files, fullpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (toc_entry != NULL) {
1381 time_t mtime = 0;
1382 int ispackage = zso->type & IS_PACKAGE;
1383 int isbytecode = zso->type & IS_BYTECODE;
Just van Rossum52e14d62002-12-30 22:08:05 +00001384
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001385 if (isbytecode) {
1386 mtime = get_mtime_of_source(self, fullpath);
1387 if (mtime == (time_t)-1 && PyErr_Occurred()) {
1388 goto exit;
1389 }
1390 }
1391 Py_CLEAR(fullpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (p_ispackage != NULL)
1393 *p_ispackage = ispackage;
1394 code = get_code_from_data(self, ispackage,
1395 isbytecode, mtime,
1396 toc_entry);
1397 if (code == Py_None) {
1398 /* bad magic number or non-matching mtime
1399 in byte code, try next */
1400 Py_DECREF(code);
1401 continue;
1402 }
Victor Stinner08654e12010-10-18 12:09:02 +00001403 if (code != NULL && p_modpath != NULL) {
1404 *p_modpath = PyTuple_GetItem(toc_entry, 0);
1405 Py_INCREF(*p_modpath);
1406 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001407 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001409 else
1410 Py_CLEAR(fullpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 }
Victor Stinnerf6b563a2011-03-14 20:46:50 -04001412 PyErr_Format(ZipImportError, "can't find module %R", fullname);
1413exit:
1414 Py_DECREF(path);
1415 Py_XDECREF(fullpath);
1416 return code;
Just van Rossum52e14d62002-12-30 22:08:05 +00001417}
1418
1419
1420/* Module init */
1421
1422PyDoc_STRVAR(zipimport_doc,
1423"zipimport provides support for importing Python modules from Zip archives.\n\
1424\n\
1425This module exports three objects:\n\
1426- zipimporter: a class; its constructor takes a path to a Zip archive.\n\
Fredrik Lundhb84b35f2006-01-15 15:00:40 +00001427- ZipImportError: exception raised by zipimporter objects. It's a\n\
Just van Rossum52e14d62002-12-30 22:08:05 +00001428 subclass of ImportError, so it can be caught as ImportError, too.\n\
1429- _zip_directory_cache: a dict, mapping archive paths to zip directory\n\
1430 info dicts, as used in zipimporter._files.\n\
1431\n\
1432It is usually not needed to use the zipimport module explicitly; it is\n\
1433used by the builtin import mechanism for sys.path items that are paths\n\
1434to Zip archives.");
1435
Martin v. Löwis1a214512008-06-11 05:26:20 +00001436static struct PyModuleDef zipimportmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyModuleDef_HEAD_INIT,
1438 "zipimport",
1439 zipimport_doc,
1440 -1,
1441 NULL,
1442 NULL,
1443 NULL,
1444 NULL,
1445 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001446};
1447
Just van Rossum52e14d62002-12-30 22:08:05 +00001448PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001449PyInit_zipimport(void)
Just van Rossum52e14d62002-12-30 22:08:05 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *mod;
Just van Rossum52e14d62002-12-30 22:08:05 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (PyType_Ready(&ZipImporter_Type) < 0)
1454 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* Correct directory separator */
1457 zip_searchorder[0].suffix[0] = SEP;
1458 zip_searchorder[1].suffix[0] = SEP;
1459 zip_searchorder[2].suffix[0] = SEP;
1460 if (Py_OptimizeFlag) {
1461 /* Reverse *.pyc and *.pyo */
1462 struct st_zip_searchorder tmp;
1463 tmp = zip_searchorder[0];
1464 zip_searchorder[0] = zip_searchorder[1];
1465 zip_searchorder[1] = tmp;
1466 tmp = zip_searchorder[3];
1467 zip_searchorder[3] = zip_searchorder[4];
1468 zip_searchorder[4] = tmp;
1469 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 mod = PyModule_Create(&zipimportmodule);
1472 if (mod == NULL)
1473 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 ZipImportError = PyErr_NewException("zipimport.ZipImportError",
1476 PyExc_ImportError, NULL);
1477 if (ZipImportError == NULL)
1478 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_INCREF(ZipImportError);
1481 if (PyModule_AddObject(mod, "ZipImportError",
1482 ZipImportError) < 0)
1483 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_INCREF(&ZipImporter_Type);
1486 if (PyModule_AddObject(mod, "zipimporter",
1487 (PyObject *)&ZipImporter_Type) < 0)
1488 return NULL;
Just van Rossumf8b6de12002-12-31 09:51:59 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 zip_directory_cache = PyDict_New();
1491 if (zip_directory_cache == NULL)
1492 return NULL;
1493 Py_INCREF(zip_directory_cache);
1494 if (PyModule_AddObject(mod, "_zip_directory_cache",
1495 zip_directory_cache) < 0)
1496 return NULL;
1497 return mod;
Just van Rossum52e14d62002-12-30 22:08:05 +00001498}