+++ /dev/null
-#include "Python.h"\r
-#include "structmember.h"\r
-#include "osdefs.h"\r
-#include "marshal.h"\r
-#include <time.h>\r
-\r
-\r
-#define IS_SOURCE 0x0\r
-#define IS_BYTECODE 0x1\r
-#define IS_PACKAGE 0x2\r
-\r
-struct st_zip_searchorder {\r
- char suffix[14];\r
- int type;\r
-};\r
-\r
-/* zip_searchorder defines how we search for a module in the Zip\r
- archive: we first search for a package __init__, then for\r
- non-package .pyc, .pyo and .py entries. The .pyc and .pyo entries\r
- are swapped by initzipimport() if we run in optimized mode. Also,\r
- '/' is replaced by SEP there. */\r
-static struct st_zip_searchorder zip_searchorder[] = {\r
- {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},\r
- {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE},\r
- {"/__init__.py", IS_PACKAGE | IS_SOURCE},\r
- {".pyc", IS_BYTECODE},\r
- {".pyo", IS_BYTECODE},\r
- {".py", IS_SOURCE},\r
- {"", 0}\r
-};\r
-\r
-/* zipimporter object definition and support */\r
-\r
-typedef struct _zipimporter ZipImporter;\r
-\r
-struct _zipimporter {\r
- PyObject_HEAD\r
- PyObject *archive; /* pathname of the Zip archive */\r
- PyObject *prefix; /* file prefix: "a/sub/directory/" */\r
- PyObject *files; /* dict with file info {path: toc_entry} */\r
-};\r
-\r
-static PyObject *ZipImportError;\r
-static PyObject *zip_directory_cache = NULL;\r
-\r
-/* forward decls */\r
-static PyObject *read_directory(char *archive);\r
-static PyObject *get_data(char *archive, PyObject *toc_entry);\r
-static PyObject *get_module_code(ZipImporter *self, char *fullname,\r
- int *p_ispackage, char **p_modpath);\r
-\r
-\r
-#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)\r
-\r
-\r
-/* zipimporter.__init__\r
- Split the "subdirectory" from the Zip archive path, lookup a matching\r
- entry in sys.path_importer_cache, fetch the file directory from there\r
- if found, or else read it from the archive. */\r
-static int\r
-zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)\r
-{\r
- char *path, *p, *prefix, buf[MAXPATHLEN+2];\r
- size_t len;\r
-\r
- if (!_PyArg_NoKeywords("zipimporter()", kwds))\r
- return -1;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter",\r
- &path))\r
- return -1;\r
-\r
- len = strlen(path);\r
- if (len == 0) {\r
- PyErr_SetString(ZipImportError, "archive path is empty");\r
- return -1;\r
- }\r
- if (len >= MAXPATHLEN) {\r
- PyErr_SetString(ZipImportError,\r
- "archive path too long");\r
- return -1;\r
- }\r
- strcpy(buf, path);\r
-\r
-#ifdef ALTSEP\r
- for (p = buf; *p; p++) {\r
- if (*p == ALTSEP)\r
- *p = SEP;\r
- }\r
-#endif\r
-\r
- path = NULL;\r
- prefix = NULL;\r
- for (;;) {\r
-#ifndef RISCOS\r
- struct stat statbuf;\r
- int rv;\r
-\r
- rv = stat(buf, &statbuf);\r
- if (rv == 0) {\r
- /* it exists */\r
- if (S_ISREG(statbuf.st_mode))\r
- /* it's a file */\r
- path = buf;\r
- break;\r
- }\r
-#else\r
- if (object_exists(buf)) {\r
- /* it exists */\r
- if (isfile(buf))\r
- /* it's a file */\r
- path = buf;\r
- break;\r
- }\r
-#endif\r
- /* back up one path element */\r
- p = strrchr(buf, SEP);\r
- if (prefix != NULL)\r
- *prefix = SEP;\r
- if (p == NULL)\r
- break;\r
- *p = '\0';\r
- prefix = p;\r
- }\r
- if (path != NULL) {\r
- PyObject *files;\r
- files = PyDict_GetItemString(zip_directory_cache, path);\r
- if (files == NULL) {\r
- files = read_directory(buf);\r
- if (files == NULL)\r
- return -1;\r
- if (PyDict_SetItemString(zip_directory_cache, path,\r
- files) != 0)\r
- return -1;\r
- }\r
- else\r
- Py_INCREF(files);\r
- self->files = files;\r
- }\r
- else {\r
- PyErr_SetString(ZipImportError, "not a Zip file");\r
- return -1;\r
- }\r
-\r
- if (prefix == NULL)\r
- prefix = "";\r
- else {\r
- prefix++;\r
- len = strlen(prefix);\r
- if (prefix[len-1] != SEP) {\r
- /* add trailing SEP */\r
- prefix[len] = SEP;\r
- prefix[len + 1] = '\0';\r
- }\r
- }\r
-\r
- self->archive = PyString_FromString(buf);\r
- if (self->archive == NULL)\r
- return -1;\r
-\r
- self->prefix = PyString_FromString(prefix);\r
- if (self->prefix == NULL)\r
- return -1;\r
-\r
- return 0;\r
-}\r
-\r
-/* GC support. */\r
-static int\r
-zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- Py_VISIT(self->files);\r
- return 0;\r
-}\r
-\r
-static void\r
-zipimporter_dealloc(ZipImporter *self)\r
-{\r
- PyObject_GC_UnTrack(self);\r
- Py_XDECREF(self->archive);\r
- Py_XDECREF(self->prefix);\r
- Py_XDECREF(self->files);\r
- Py_TYPE(self)->tp_free((PyObject *)self);\r
-}\r
-\r
-static PyObject *\r
-zipimporter_repr(ZipImporter *self)\r
-{\r
- char buf[500];\r
- char *archive = "???";\r
- char *prefix = "";\r
-\r
- if (self->archive != NULL && PyString_Check(self->archive))\r
- archive = PyString_AsString(self->archive);\r
- if (self->prefix != NULL && PyString_Check(self->prefix))\r
- prefix = PyString_AsString(self->prefix);\r
- if (prefix != NULL && *prefix)\r
- PyOS_snprintf(buf, sizeof(buf),\r
- "<zipimporter object \"%.300s%c%.150s\">",\r
- archive, SEP, prefix);\r
- else\r
- PyOS_snprintf(buf, sizeof(buf),\r
- "<zipimporter object \"%.300s\">",\r
- archive);\r
- return PyString_FromString(buf);\r
-}\r
-\r
-/* return fullname.split(".")[-1] */\r
-static char *\r
-get_subname(char *fullname)\r
-{\r
- char *subname = strrchr(fullname, '.');\r
- if (subname == NULL)\r
- subname = fullname;\r
- else\r
- subname++;\r
- return subname;\r
-}\r
-\r
-/* Given a (sub)modulename, write the potential file path in the\r
- archive (without extension) to the path buffer. Return the\r
- length of the resulting string. */\r
-static int\r
-make_filename(char *prefix, char *name, char *path)\r
-{\r
- size_t len;\r
- char *p;\r
-\r
- len = strlen(prefix);\r
-\r
- /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */\r
- if (len + strlen(name) + 13 >= MAXPATHLEN) {\r
- PyErr_SetString(ZipImportError, "path too long");\r
- return -1;\r
- }\r
-\r
- strcpy(path, prefix);\r
- strcpy(path + len, name);\r
- for (p = path + len; *p; p++) {\r
- if (*p == '.')\r
- *p = SEP;\r
- }\r
- len += strlen(name);\r
- assert(len < INT_MAX);\r
- return (int)len;\r
-}\r
-\r
-enum zi_module_info {\r
- MI_ERROR,\r
- MI_NOT_FOUND,\r
- MI_MODULE,\r
- MI_PACKAGE\r
-};\r
-\r
-/* Return some information about a module. */\r
-static enum zi_module_info\r
-get_module_info(ZipImporter *self, char *fullname)\r
-{\r
- char *subname, path[MAXPATHLEN + 1];\r
- int len;\r
- struct st_zip_searchorder *zso;\r
-\r
- subname = get_subname(fullname);\r
-\r
- len = make_filename(PyString_AsString(self->prefix), subname, path);\r
- if (len < 0)\r
- return MI_ERROR;\r
-\r
- for (zso = zip_searchorder; *zso->suffix; zso++) {\r
- strcpy(path + len, zso->suffix);\r
- if (PyDict_GetItemString(self->files, path) != NULL) {\r
- if (zso->type & IS_PACKAGE)\r
- return MI_PACKAGE;\r
- else\r
- return MI_MODULE;\r
- }\r
- }\r
- return MI_NOT_FOUND;\r
-}\r
-\r
-/* Check whether we can satisfy the import of the module named by\r
- 'fullname'. Return self if we can, None if we can't. */\r
-static PyObject *\r
-zipimporter_find_module(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- PyObject *path = NULL;\r
- char *fullname;\r
- enum zi_module_info mi;\r
-\r
- if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module",\r
- &fullname, &path))\r
- return NULL;\r
-\r
- mi = get_module_info(self, fullname);\r
- if (mi == MI_ERROR)\r
- return NULL;\r
- if (mi == MI_NOT_FOUND) {\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
- }\r
- Py_INCREF(self);\r
- return (PyObject *)self;\r
-}\r
-\r
-/* Load and return the module named by 'fullname'. */\r
-static PyObject *\r
-zipimporter_load_module(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- PyObject *code, *mod, *dict;\r
- char *fullname, *modpath;\r
- int ispackage;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter.load_module",\r
- &fullname))\r
- return NULL;\r
-\r
- code = get_module_code(self, fullname, &ispackage, &modpath);\r
- if (code == NULL)\r
- return NULL;\r
-\r
- mod = PyImport_AddModule(fullname);\r
- if (mod == NULL) {\r
- Py_DECREF(code);\r
- return NULL;\r
- }\r
- dict = PyModule_GetDict(mod);\r
-\r
- /* mod.__loader__ = self */\r
- if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)\r
- goto error;\r
-\r
- if (ispackage) {\r
- /* add __path__ to the module *before* the code gets\r
- executed */\r
- PyObject *pkgpath, *fullpath;\r
- char *prefix = PyString_AsString(self->prefix);\r
- char *subname = get_subname(fullname);\r
- int err;\r
-\r
- fullpath = PyString_FromFormat("%s%c%s%s",\r
- PyString_AsString(self->archive),\r
- SEP,\r
- *prefix ? prefix : "",\r
- subname);\r
- if (fullpath == NULL)\r
- goto error;\r
-\r
- pkgpath = Py_BuildValue("[O]", fullpath);\r
- Py_DECREF(fullpath);\r
- if (pkgpath == NULL)\r
- goto error;\r
- err = PyDict_SetItemString(dict, "__path__", pkgpath);\r
- Py_DECREF(pkgpath);\r
- if (err != 0)\r
- goto error;\r
- }\r
- mod = PyImport_ExecCodeModuleEx(fullname, code, modpath);\r
- Py_DECREF(code);\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # loaded from Zip %s\n",\r
- fullname, modpath);\r
- return mod;\r
-error:\r
- Py_DECREF(code);\r
- Py_DECREF(mod);\r
- return NULL;\r
-}\r
-\r
-/* Return a string matching __file__ for the named module */\r
-static PyObject *\r
-zipimporter_get_filename(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- PyObject *code;\r
- char *fullname, *modpath;\r
- int ispackage;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename",\r
- &fullname))\r
- return NULL;\r
-\r
- /* Deciding the filename requires working out where the code\r
- would come from if the module was actually loaded */\r
- code = get_module_code(self, fullname, &ispackage, &modpath);\r
- if (code == NULL)\r
- return NULL;\r
- Py_DECREF(code); /* Only need the path info */\r
-\r
- return PyString_FromString(modpath);\r
-}\r
-\r
-/* Return a bool signifying whether the module is a package or not. */\r
-static PyObject *\r
-zipimporter_is_package(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- char *fullname;\r
- enum zi_module_info mi;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter.is_package",\r
- &fullname))\r
- return NULL;\r
-\r
- mi = get_module_info(self, fullname);\r
- if (mi == MI_ERROR)\r
- return NULL;\r
- if (mi == MI_NOT_FOUND) {\r
- PyErr_Format(ZipImportError, "can't find module '%.200s'",\r
- fullname);\r
- return NULL;\r
- }\r
- return PyBool_FromLong(mi == MI_PACKAGE);\r
-}\r
-\r
-static PyObject *\r
-zipimporter_get_data(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- char *path;\r
-#ifdef ALTSEP\r
- char *p, buf[MAXPATHLEN + 1];\r
-#endif\r
- PyObject *toc_entry;\r
- Py_ssize_t len;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path))\r
- return NULL;\r
-\r
-#ifdef ALTSEP\r
- if (strlen(path) >= MAXPATHLEN) {\r
- PyErr_SetString(ZipImportError, "path too long");\r
- return NULL;\r
- }\r
- strcpy(buf, path);\r
- for (p = buf; *p; p++) {\r
- if (*p == ALTSEP)\r
- *p = SEP;\r
- }\r
- path = buf;\r
-#endif\r
- len = PyString_Size(self->archive);\r
- if ((size_t)len < strlen(path) &&\r
- strncmp(path, PyString_AsString(self->archive), len) == 0 &&\r
- path[len] == SEP) {\r
- path = path + len + 1;\r
- }\r
-\r
- toc_entry = PyDict_GetItemString(self->files, path);\r
- if (toc_entry == NULL) {\r
- PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);\r
- return NULL;\r
- }\r
- return get_data(PyString_AsString(self->archive), toc_entry);\r
-}\r
-\r
-static PyObject *\r
-zipimporter_get_code(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- char *fullname;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname))\r
- return NULL;\r
-\r
- return get_module_code(self, fullname, NULL, NULL);\r
-}\r
-\r
-static PyObject *\r
-zipimporter_get_source(PyObject *obj, PyObject *args)\r
-{\r
- ZipImporter *self = (ZipImporter *)obj;\r
- PyObject *toc_entry;\r
- char *fullname, *subname, path[MAXPATHLEN+1];\r
- int len;\r
- enum zi_module_info mi;\r
-\r
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname))\r
- return NULL;\r
-\r
- mi = get_module_info(self, fullname);\r
- if (mi == MI_ERROR)\r
- return NULL;\r
- if (mi == MI_NOT_FOUND) {\r
- PyErr_Format(ZipImportError, "can't find module '%.200s'",\r
- fullname);\r
- return NULL;\r
- }\r
- subname = get_subname(fullname);\r
-\r
- len = make_filename(PyString_AsString(self->prefix), subname, path);\r
- if (len < 0)\r
- return NULL;\r
-\r
- if (mi == MI_PACKAGE) {\r
- path[len] = SEP;\r
- strcpy(path + len + 1, "__init__.py");\r
- }\r
- else\r
- strcpy(path + len, ".py");\r
-\r
- toc_entry = PyDict_GetItemString(self->files, path);\r
- if (toc_entry != NULL)\r
- return get_data(PyString_AsString(self->archive), toc_entry);\r
-\r
- /* we have the module, but no source */\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(doc_find_module,\r
-"find_module(fullname, path=None) -> self or None.\n\\r
-\n\\r
-Search for a module specified by 'fullname'. 'fullname' must be the\n\\r
-fully qualified (dotted) module name. It returns the zipimporter\n\\r
-instance itself if the module was found, or None if it wasn't.\n\\r
-The optional 'path' argument is ignored -- it's there for compatibility\n\\r
-with the importer protocol.");\r
-\r
-PyDoc_STRVAR(doc_load_module,\r
-"load_module(fullname) -> module.\n\\r
-\n\\r
-Load the module specified by 'fullname'. 'fullname' must be the\n\\r
-fully qualified (dotted) module name. It returns the imported\n\\r
-module, or raises ZipImportError if it wasn't found.");\r
-\r
-PyDoc_STRVAR(doc_get_data,\r
-"get_data(pathname) -> string with file data.\n\\r
-\n\\r
-Return the data associated with 'pathname'. Raise IOError if\n\\r
-the file wasn't found.");\r
-\r
-PyDoc_STRVAR(doc_is_package,\r
-"is_package(fullname) -> bool.\n\\r
-\n\\r
-Return True if the module specified by fullname is a package.\n\\r
-Raise ZipImportError if the module couldn't be found.");\r
-\r
-PyDoc_STRVAR(doc_get_code,\r
-"get_code(fullname) -> code object.\n\\r
-\n\\r
-Return the code object for the specified module. Raise ZipImportError\n\\r
-if the module couldn't be found.");\r
-\r
-PyDoc_STRVAR(doc_get_source,\r
-"get_source(fullname) -> source string.\n\\r
-\n\\r
-Return the source code for the specified module. Raise ZipImportError\n\\r
-if the module couldn't be found, return None if the archive does\n\\r
-contain the module, but has no source for it.");\r
-\r
-\r
-PyDoc_STRVAR(doc_get_filename,\r
-"get_filename(fullname) -> filename string.\n\\r
-\n\\r
-Return the filename for the specified module.");\r
-\r
-static PyMethodDef zipimporter_methods[] = {\r
- {"find_module", zipimporter_find_module, METH_VARARGS,\r
- doc_find_module},\r
- {"load_module", zipimporter_load_module, METH_VARARGS,\r
- doc_load_module},\r
- {"get_data", zipimporter_get_data, METH_VARARGS,\r
- doc_get_data},\r
- {"get_code", zipimporter_get_code, METH_VARARGS,\r
- doc_get_code},\r
- {"get_source", zipimporter_get_source, METH_VARARGS,\r
- doc_get_source},\r
- {"get_filename", zipimporter_get_filename, METH_VARARGS,\r
- doc_get_filename},\r
- {"is_package", zipimporter_is_package, METH_VARARGS,\r
- doc_is_package},\r
- {NULL, NULL} /* sentinel */\r
-};\r
-\r
-static PyMemberDef zipimporter_members[] = {\r
- {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},\r
- {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},\r
- {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},\r
- {NULL}\r
-};\r
-\r
-PyDoc_STRVAR(zipimporter_doc,\r
-"zipimporter(archivepath) -> zipimporter object\n\\r
-\n\\r
-Create a new zipimporter instance. 'archivepath' must be a path to\n\\r
-a zipfile, or to a specific path inside a zipfile. For example, it can be\n\\r
-'/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a\n\\r
-valid directory inside the archive.\n\\r
-\n\\r
-'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip\n\\r
-archive.\n\\r
-\n\\r
-The 'archive' attribute of zipimporter objects contains the name of the\n\\r
-zipfile targeted.");\r
-\r
-#define DEFERRED_ADDRESS(ADDR) 0\r
-\r
-static PyTypeObject ZipImporter_Type = {\r
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)\r
- "zipimport.zipimporter",\r
- sizeof(ZipImporter),\r
- 0, /* tp_itemsize */\r
- (destructor)zipimporter_dealloc, /* tp_dealloc */\r
- 0, /* tp_print */\r
- 0, /* tp_getattr */\r
- 0, /* tp_setattr */\r
- 0, /* tp_compare */\r
- (reprfunc)zipimporter_repr, /* tp_repr */\r
- 0, /* tp_as_number */\r
- 0, /* tp_as_sequence */\r
- 0, /* tp_as_mapping */\r
- 0, /* tp_hash */\r
- 0, /* tp_call */\r
- 0, /* tp_str */\r
- PyObject_GenericGetAttr, /* tp_getattro */\r
- 0, /* tp_setattro */\r
- 0, /* tp_as_buffer */\r
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |\r
- Py_TPFLAGS_HAVE_GC, /* tp_flags */\r
- zipimporter_doc, /* tp_doc */\r
- zipimporter_traverse, /* tp_traverse */\r
- 0, /* tp_clear */\r
- 0, /* tp_richcompare */\r
- 0, /* tp_weaklistoffset */\r
- 0, /* tp_iter */\r
- 0, /* tp_iternext */\r
- zipimporter_methods, /* tp_methods */\r
- zipimporter_members, /* tp_members */\r
- 0, /* tp_getset */\r
- 0, /* tp_base */\r
- 0, /* tp_dict */\r
- 0, /* tp_descr_get */\r
- 0, /* tp_descr_set */\r
- 0, /* tp_dictoffset */\r
- (initproc)zipimporter_init, /* tp_init */\r
- PyType_GenericAlloc, /* tp_alloc */\r
- PyType_GenericNew, /* tp_new */\r
- PyObject_GC_Del, /* tp_free */\r
-};\r
-\r
-\r
-/* implementation */\r
-\r
-/* Given a buffer, return the long that is represented by the first\r
- 4 bytes, encoded as little endian. This partially reimplements\r
- marshal.c:r_long() */\r
-static long\r
-get_long(unsigned char *buf) {\r
- long x;\r
- x = buf[0];\r
- x |= (long)buf[1] << 8;\r
- x |= (long)buf[2] << 16;\r
- x |= (long)buf[3] << 24;\r
-#if SIZEOF_LONG > 4\r
- /* Sign extension for 64-bit machines */\r
- x |= -(x & 0x80000000L);\r
-#endif\r
- return x;\r
-}\r
-\r
-/*\r
- read_directory(archive) -> files dict (new reference)\r
-\r
- Given a path to a Zip archive, build a dict, mapping file names\r
- (local to the archive, using SEP as a separator) to toc entries.\r
-\r
- A toc_entry is a tuple:\r
-\r
- (__file__, # value to use for __file__, available for all files\r
- compress, # compression kind; 0 for uncompressed\r
- data_size, # size of compressed data on disk\r
- file_size, # size of decompressed data\r
- file_offset, # offset of file header from start of archive\r
- time, # mod time of file (in dos format)\r
- date, # mod data of file (in dos format)\r
- crc, # crc checksum of the data\r
- )\r
-\r
- Directories can be recognized by the trailing SEP in the name,\r
- data_size and file_offset are 0.\r
-*/\r
-static PyObject *\r
-read_directory(char *archive)\r
-{\r
- PyObject *files = NULL;\r
- FILE *fp;\r
- long compress, crc, data_size, file_size, file_offset, date, time;\r
- long header_offset, name_size, header_size, header_position;\r
- long i, l, count;\r
- size_t length;\r
- char path[MAXPATHLEN + 5];\r
- char name[MAXPATHLEN + 5];\r
- char *p, endof_central_dir[22];\r
- long arc_offset; /* offset from beginning of file to start of zip-archive */\r
-\r
- if (strlen(archive) > MAXPATHLEN) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "Zip path name is too long");\r
- return NULL;\r
- }\r
- strcpy(path, archive);\r
-\r
- fp = fopen(archive, "rb");\r
- if (fp == NULL) {\r
- PyErr_Format(ZipImportError, "can't open Zip file: "\r
- "'%.200s'", archive);\r
- return NULL;\r
- }\r
-\r
- if (fseek(fp, -22, SEEK_END) == -1) {\r
- fclose(fp);\r
- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);\r
- return NULL;\r
- }\r
- header_position = ftell(fp);\r
- if (fread(endof_central_dir, 1, 22, fp) != 22) {\r
- fclose(fp);\r
- PyErr_Format(ZipImportError, "can't read Zip file: "\r
- "'%.200s'", archive);\r
- return NULL;\r
- }\r
- if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {\r
- /* Bad: End of Central Dir signature */\r
- fclose(fp);\r
- PyErr_Format(ZipImportError, "not a Zip file: "\r
- "'%.200s'", archive);\r
- return NULL;\r
- }\r
-\r
- header_size = get_long((unsigned char *)endof_central_dir + 12);\r
- header_offset = get_long((unsigned char *)endof_central_dir + 16);\r
- arc_offset = header_position - header_offset - header_size;\r
- header_offset += arc_offset;\r
-\r
- files = PyDict_New();\r
- if (files == NULL)\r
- goto error;\r
-\r
- length = (long)strlen(path);\r
- path[length] = SEP;\r
-\r
- /* Start of Central Directory */\r
- count = 0;\r
- for (;;) {\r
- PyObject *t;\r
- int err;\r
-\r
- if (fseek(fp, header_offset, 0) == -1) /* Start of file header */\r
- goto fseek_error;\r
- l = PyMarshal_ReadLongFromFile(fp);\r
- if (l != 0x02014B50)\r
- break; /* Bad: Central Dir File Header */\r
- if (fseek(fp, header_offset + 10, 0) == -1)\r
- goto fseek_error;\r
- compress = PyMarshal_ReadShortFromFile(fp);\r
- time = PyMarshal_ReadShortFromFile(fp);\r
- date = PyMarshal_ReadShortFromFile(fp);\r
- crc = PyMarshal_ReadLongFromFile(fp);\r
- data_size = PyMarshal_ReadLongFromFile(fp);\r
- file_size = PyMarshal_ReadLongFromFile(fp);\r
- name_size = PyMarshal_ReadShortFromFile(fp);\r
- header_size = 46 + name_size +\r
- PyMarshal_ReadShortFromFile(fp) +\r
- PyMarshal_ReadShortFromFile(fp);\r
- if (fseek(fp, header_offset + 42, 0) == -1)\r
- goto fseek_error;\r
- file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;\r
- if (name_size > MAXPATHLEN)\r
- name_size = MAXPATHLEN;\r
-\r
- p = name;\r
- for (i = 0; i < name_size; i++) {\r
- *p = (char)getc(fp);\r
- if (*p == '/')\r
- *p = SEP;\r
- p++;\r
- }\r
- *p = 0; /* Add terminating null byte */\r
- header_offset += header_size;\r
-\r
- strncpy(path + length + 1, name, MAXPATHLEN - length - 1);\r
-\r
- t = Py_BuildValue("siiiiiii", path, compress, data_size,\r
- file_size, file_offset, time, date, crc);\r
- if (t == NULL)\r
- goto error;\r
- err = PyDict_SetItemString(files, name, t);\r
- Py_DECREF(t);\r
- if (err != 0)\r
- goto error;\r
- count++;\r
- }\r
- fclose(fp);\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# zipimport: found %ld names in %s\n",\r
- count, archive);\r
- return files;\r
-fseek_error:\r
- fclose(fp);\r
- Py_XDECREF(files);\r
- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);\r
- return NULL;\r
-error:\r
- fclose(fp);\r
- Py_XDECREF(files);\r
- return NULL;\r
-}\r
-\r
-/* Return the zlib.decompress function object, or NULL if zlib couldn't\r
- be imported. The function is cached when found, so subsequent calls\r
- don't import zlib again. */\r
-static PyObject *\r
-get_decompress_func(void)\r
-{\r
- static int importing_zlib = 0;\r
- PyObject *zlib;\r
- PyObject *decompress;\r
-\r
- if (importing_zlib != 0)\r
- /* Someone has a zlib.py[co] in their Zip file;\r
- let's avoid a stack overflow. */\r
- return NULL;\r
- importing_zlib = 1;\r
- zlib = PyImport_ImportModuleNoBlock("zlib");\r
- importing_zlib = 0;\r
- if (zlib != NULL) {\r
- decompress = PyObject_GetAttrString(zlib,\r
- "decompress");\r
- Py_DECREF(zlib);\r
- }\r
- else {\r
- PyErr_Clear();\r
- decompress = NULL;\r
- }\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# zipimport: zlib %s\n",\r
- zlib != NULL ? "available": "UNAVAILABLE");\r
- return decompress;\r
-}\r
-\r
-/* Given a path to a Zip file and a toc_entry, return the (uncompressed)\r
- data as a new reference. */\r
-static PyObject *\r
-get_data(char *archive, PyObject *toc_entry)\r
-{\r
- PyObject *raw_data, *data = NULL, *decompress;\r
- char *buf;\r
- FILE *fp;\r
- int err;\r
- Py_ssize_t bytes_read = 0;\r
- long l;\r
- char *datapath;\r
- long compress, data_size, file_size, file_offset;\r
- long time, date, crc;\r
-\r
- if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,\r
- &data_size, &file_size, &file_offset, &time,\r
- &date, &crc)) {\r
- return NULL;\r
- }\r
-\r
- fp = fopen(archive, "rb");\r
- if (!fp) {\r
- PyErr_Format(PyExc_IOError,\r
- "zipimport: can not open file %s", archive);\r
- return NULL;\r
- }\r
-\r
- /* Check to make sure the local file header is correct */\r
- if (fseek(fp, file_offset, 0) == -1) {\r
- fclose(fp);\r
- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);\r
- return NULL;\r
- }\r
-\r
- l = PyMarshal_ReadLongFromFile(fp);\r
- if (l != 0x04034B50) {\r
- /* Bad: Local File Header */\r
- PyErr_Format(ZipImportError,\r
- "bad local file header in %s",\r
- archive);\r
- fclose(fp);\r
- return NULL;\r
- }\r
- if (fseek(fp, file_offset + 26, 0) == -1) {\r
- fclose(fp);\r
- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);\r
- return NULL;\r
- }\r
-\r
- l = 30 + PyMarshal_ReadShortFromFile(fp) +\r
- PyMarshal_ReadShortFromFile(fp); /* local header size */\r
- file_offset += l; /* Start of file data */\r
-\r
- raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?\r
- data_size : data_size + 1);\r
- if (raw_data == NULL) {\r
- fclose(fp);\r
- return NULL;\r
- }\r
- buf = PyString_AsString(raw_data);\r
-\r
- err = fseek(fp, file_offset, 0);\r
- if (err == 0) {\r
- bytes_read = fread(buf, 1, data_size, fp);\r
- } else {\r
- fclose(fp);\r
- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);\r
- return NULL;\r
- }\r
- fclose(fp);\r
- if (err || bytes_read != data_size) {\r
- PyErr_SetString(PyExc_IOError,\r
- "zipimport: can't read data");\r
- Py_DECREF(raw_data);\r
- return NULL;\r
- }\r
-\r
- if (compress != 0) {\r
- buf[data_size] = 'Z'; /* saw this in zipfile.py */\r
- data_size++;\r
- }\r
- buf[data_size] = '\0';\r
-\r
- if (compress == 0) /* data is not compressed */\r
- return raw_data;\r
-\r
- /* Decompress with zlib */\r
- decompress = get_decompress_func();\r
- if (decompress == NULL) {\r
- PyErr_SetString(ZipImportError,\r
- "can't decompress data; "\r
- "zlib not available");\r
- goto error;\r
- }\r
- data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);\r
- Py_DECREF(decompress);\r
-error:\r
- Py_DECREF(raw_data);\r
- return data;\r
-}\r
-\r
-/* Lenient date/time comparison function. The precision of the mtime\r
- in the archive is lower than the mtime stored in a .pyc: we\r
- must allow a difference of at most one second. */\r
-static int\r
-eq_mtime(time_t t1, time_t t2)\r
-{\r
- time_t d = t1 - t2;\r
- if (d < 0)\r
- d = -d;\r
- /* dostime only stores even seconds, so be lenient */\r
- return d <= 1;\r
-}\r
-\r
-/* Given the contents of a .py[co] file in a buffer, unmarshal the data\r
- and return the code object. Return None if it the magic word doesn't\r
- match (we do this instead of raising an exception as we fall back\r
- to .py if available and we don't want to mask other errors).\r
- Returns a new reference. */\r
-static PyObject *\r
-unmarshal_code(char *pathname, PyObject *data, time_t mtime)\r
-{\r
- PyObject *code;\r
- char *buf = PyString_AsString(data);\r
- Py_ssize_t size = PyString_Size(data);\r
-\r
- if (size <= 9) {\r
- PyErr_SetString(ZipImportError,\r
- "bad pyc data");\r
- return NULL;\r
- }\r
-\r
- if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# %s has bad magic\n",\r
- pathname);\r
- Py_INCREF(Py_None);\r
- return Py_None; /* signal caller to try alternative */\r
- }\r
-\r
- if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),\r
- mtime)) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# %s has bad mtime\n",\r
- pathname);\r
- Py_INCREF(Py_None);\r
- return Py_None; /* signal caller to try alternative */\r
- }\r
-\r
- code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);\r
- if (code == NULL)\r
- return NULL;\r
- if (!PyCode_Check(code)) {\r
- Py_DECREF(code);\r
- PyErr_Format(PyExc_TypeError,\r
- "compiled module %.200s is not a code object",\r
- pathname);\r
- return NULL;\r
- }\r
- return code;\r
-}\r
-\r
-/* Replace any occurances of "\r\n?" in the input string with "\n".\r
- This converts DOS and Mac line endings to Unix line endings.\r
- Also append a trailing "\n" to be compatible with\r
- PyParser_SimpleParseFile(). Returns a new reference. */\r
-static PyObject *\r
-normalize_line_endings(PyObject *source)\r
-{\r
- char *buf, *q, *p = PyString_AsString(source);\r
- PyObject *fixed_source;\r
-\r
- if (!p)\r
- return NULL;\r
-\r
- /* one char extra for trailing \n and one for terminating \0 */\r
- buf = (char *)PyMem_Malloc(PyString_Size(source) + 2);\r
- if (buf == NULL) {\r
- PyErr_SetString(PyExc_MemoryError,\r
- "zipimport: no memory to allocate "\r
- "source buffer");\r
- return NULL;\r
- }\r
- /* replace "\r\n?" by "\n" */\r
- for (q = buf; *p != '\0'; p++) {\r
- if (*p == '\r') {\r
- *q++ = '\n';\r
- if (*(p + 1) == '\n')\r
- p++;\r
- }\r
- else\r
- *q++ = *p;\r
- }\r
- *q++ = '\n'; /* add trailing \n */\r
- *q = '\0';\r
- fixed_source = PyString_FromString(buf);\r
- PyMem_Free(buf);\r
- return fixed_source;\r
-}\r
-\r
-/* Given a string buffer containing Python source code, compile it\r
- return and return a code object as a new reference. */\r
-static PyObject *\r
-compile_source(char *pathname, PyObject *source)\r
-{\r
- PyObject *code, *fixed_source;\r
-\r
- fixed_source = normalize_line_endings(source);\r
- if (fixed_source == NULL)\r
- return NULL;\r
-\r
- code = Py_CompileString(PyString_AsString(fixed_source), pathname,\r
- Py_file_input);\r
- Py_DECREF(fixed_source);\r
- return code;\r
-}\r
-\r
-/* Convert the date/time values found in the Zip archive to a value\r
- that's compatible with the time stamp stored in .pyc files. */\r
-static time_t\r
-parse_dostime(int dostime, int dosdate)\r
-{\r
- struct tm stm;\r
-\r
- memset((void *) &stm, '\0', sizeof(stm));\r
-\r
- stm.tm_sec = (dostime & 0x1f) * 2;\r
- stm.tm_min = (dostime >> 5) & 0x3f;\r
- stm.tm_hour = (dostime >> 11) & 0x1f;\r
- stm.tm_mday = dosdate & 0x1f;\r
- stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;\r
- stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;\r
- stm.tm_isdst = -1; /* wday/yday is ignored */\r
-\r
- return mktime(&stm);\r
-}\r
-\r
-/* Given a path to a .pyc or .pyo file in the archive, return the\r
- modification time of the matching .py file, or 0 if no source\r
- is available. */\r
-static time_t\r
-get_mtime_of_source(ZipImporter *self, char *path)\r
-{\r
- PyObject *toc_entry;\r
- time_t mtime = 0;\r
- Py_ssize_t lastchar = strlen(path) - 1;\r
- char savechar = path[lastchar];\r
- path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */\r
- toc_entry = PyDict_GetItemString(self->files, path);\r
- if (toc_entry != NULL && PyTuple_Check(toc_entry) &&\r
- PyTuple_Size(toc_entry) == 8) {\r
- /* fetch the time stamp of the .py file for comparison\r
- with an embedded pyc time stamp */\r
- int time, date;\r
- time = PyInt_AsLong(PyTuple_GetItem(toc_entry, 5));\r
- date = PyInt_AsLong(PyTuple_GetItem(toc_entry, 6));\r
- mtime = parse_dostime(time, date);\r
- }\r
- path[lastchar] = savechar;\r
- return mtime;\r
-}\r
-\r
-/* Return the code object for the module named by 'fullname' from the\r
- Zip archive as a new reference. */\r
-static PyObject *\r
-get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,\r
- time_t mtime, PyObject *toc_entry)\r
-{\r
- PyObject *data, *code;\r
- char *modpath;\r
- char *archive = PyString_AsString(self->archive);\r
-\r
- if (archive == NULL)\r
- return NULL;\r
-\r
- data = get_data(archive, toc_entry);\r
- if (data == NULL)\r
- return NULL;\r
-\r
- modpath = PyString_AsString(PyTuple_GetItem(toc_entry, 0));\r
-\r
- if (isbytecode) {\r
- code = unmarshal_code(modpath, data, mtime);\r
- }\r
- else {\r
- code = compile_source(modpath, data);\r
- }\r
- Py_DECREF(data);\r
- return code;\r
-}\r
-\r
-/* Get the code object associated with the module specified by\r
- 'fullname'. */\r
-static PyObject *\r
-get_module_code(ZipImporter *self, char *fullname,\r
- int *p_ispackage, char **p_modpath)\r
-{\r
- PyObject *toc_entry;\r
- char *subname, path[MAXPATHLEN + 1];\r
- int len;\r
- struct st_zip_searchorder *zso;\r
-\r
- subname = get_subname(fullname);\r
-\r
- len = make_filename(PyString_AsString(self->prefix), subname, path);\r
- if (len < 0)\r
- return NULL;\r
-\r
- for (zso = zip_searchorder; *zso->suffix; zso++) {\r
- PyObject *code = NULL;\r
-\r
- strcpy(path + len, zso->suffix);\r
- if (Py_VerboseFlag > 1)\r
- PySys_WriteStderr("# trying %s%c%s\n",\r
- PyString_AsString(self->archive),\r
- SEP, path);\r
- toc_entry = PyDict_GetItemString(self->files, path);\r
- if (toc_entry != NULL) {\r
- time_t mtime = 0;\r
- int ispackage = zso->type & IS_PACKAGE;\r
- int isbytecode = zso->type & IS_BYTECODE;\r
-\r
- if (isbytecode)\r
- mtime = get_mtime_of_source(self, path);\r
- if (p_ispackage != NULL)\r
- *p_ispackage = ispackage;\r
- code = get_code_from_data(self, ispackage,\r
- isbytecode, mtime,\r
- toc_entry);\r
- if (code == Py_None) {\r
- /* bad magic number or non-matching mtime\r
- in byte code, try next */\r
- Py_DECREF(code);\r
- continue;\r
- }\r
- if (code != NULL && p_modpath != NULL)\r
- *p_modpath = PyString_AsString(\r
- PyTuple_GetItem(toc_entry, 0));\r
- return code;\r
- }\r
- }\r
- PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);\r
- return NULL;\r
-}\r
-\r
-\r
-/* Module init */\r
-\r
-PyDoc_STRVAR(zipimport_doc,\r
-"zipimport provides support for importing Python modules from Zip archives.\n\\r
-\n\\r
-This module exports three objects:\n\\r
-- zipimporter: a class; its constructor takes a path to a Zip archive.\n\\r
-- ZipImportError: exception raised by zipimporter objects. It's a\n\\r
- subclass of ImportError, so it can be caught as ImportError, too.\n\\r
-- _zip_directory_cache: a dict, mapping archive paths to zip directory\n\\r
- info dicts, as used in zipimporter._files.\n\\r
-\n\\r
-It is usually not needed to use the zipimport module explicitly; it is\n\\r
-used by the builtin import mechanism for sys.path items that are paths\n\\r
-to Zip archives.");\r
-\r
-PyMODINIT_FUNC\r
-initzipimport(void)\r
-{\r
- PyObject *mod;\r
-\r
- if (PyType_Ready(&ZipImporter_Type) < 0)\r
- return;\r
-\r
- /* Correct directory separator */\r
- zip_searchorder[0].suffix[0] = SEP;\r
- zip_searchorder[1].suffix[0] = SEP;\r
- zip_searchorder[2].suffix[0] = SEP;\r
- if (Py_OptimizeFlag) {\r
- /* Reverse *.pyc and *.pyo */\r
- struct st_zip_searchorder tmp;\r
- tmp = zip_searchorder[0];\r
- zip_searchorder[0] = zip_searchorder[1];\r
- zip_searchorder[1] = tmp;\r
- tmp = zip_searchorder[3];\r
- zip_searchorder[3] = zip_searchorder[4];\r
- zip_searchorder[4] = tmp;\r
- }\r
-\r
- mod = Py_InitModule4("zipimport", NULL, zipimport_doc,\r
- NULL, PYTHON_API_VERSION);\r
- if (mod == NULL)\r
- return;\r
-\r
- ZipImportError = PyErr_NewException("zipimport.ZipImportError",\r
- PyExc_ImportError, NULL);\r
- if (ZipImportError == NULL)\r
- return;\r
-\r
- Py_INCREF(ZipImportError);\r
- if (PyModule_AddObject(mod, "ZipImportError",\r
- ZipImportError) < 0)\r
- return;\r
-\r
- Py_INCREF(&ZipImporter_Type);\r
- if (PyModule_AddObject(mod, "zipimporter",\r
- (PyObject *)&ZipImporter_Type) < 0)\r
- return;\r
-\r
- zip_directory_cache = PyDict_New();\r
- if (zip_directory_cache == NULL)\r
- return;\r
- Py_INCREF(zip_directory_cache);\r
- if (PyModule_AddObject(mod, "_zip_directory_cache",\r
- zip_directory_cache) < 0)\r
- return;\r
-}\r