1/*
2  +----------------------------------------------------------------------+
3  | phar php single-file executable PHP extension                        |
4  +----------------------------------------------------------------------+
5  | Copyright (c) 2005-2014 The PHP Group                                |
6  +----------------------------------------------------------------------+
7  | This source file is subject to version 3.01 of the PHP license,      |
8  | that is bundled with this package in the file LICENSE, and is        |
9  | available through the world-wide-web at the following url:           |
10  | http://www.php.net/license/3_01.txt.                                 |
11  | If you did not receive a copy of the PHP license and are unable to   |
12  | obtain it through the world-wide-web, please send a note to          |
13  | license@php.net so we can mail you a copy immediately.               |
14  +----------------------------------------------------------------------+
15  | Authors: Gregory Beaver <cellog@php.net>                             |
16  |          Marcus Boerger <helly@php.net>                              |
17  +----------------------------------------------------------------------+
18*/
19
20/* $Id$ */
21
22#include "phar_internal.h"
23#include "func_interceptors.h"
24
25static zend_class_entry *phar_ce_archive;
26static zend_class_entry *phar_ce_data;
27static zend_class_entry *phar_ce_PharException;
28
29#if HAVE_SPL
30static zend_class_entry *phar_ce_entry;
31#endif
32
33#if PHP_MAJOR_VERSION > 5 || ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION >= 3))
34# define PHAR_ARG_INFO
35#else
36# define PHAR_ARG_INFO static
37#endif
38
39static int phar_file_type(HashTable *mimes, char *file, char **mime_type TSRMLS_DC) /* {{{ */
40{
41    char *ext;
42    phar_mime_type *mime;
43    ext = strrchr(file, '.');
44    if (!ext) {
45        *mime_type = "text/plain";
46        /* no file extension = assume text/plain */
47        return PHAR_MIME_OTHER;
48    }
49    ++ext;
50    if (SUCCESS != zend_hash_find(mimes, ext, strlen(ext), (void **) &mime)) {
51        *mime_type = "application/octet-stream";
52        return PHAR_MIME_OTHER;
53    }
54    *mime_type = mime->mime;
55    return mime->type;
56}
57/* }}} */
58
59static void phar_mung_server_vars(char *fname, char *entry, int entry_len, char *basename, int request_uri_len TSRMLS_DC) /* {{{ */
60{
61    HashTable *_SERVER;
62    zval **stuff;
63    char *path_info;
64    int basename_len = strlen(basename);
65    int code;
66    zval *temp;
67
68    /* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */
69    if (!PG(http_globals)[TRACK_VARS_SERVER]) {
70        return;
71    }
72
73    _SERVER = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
74
75    /* PATH_INFO and PATH_TRANSLATED should always be munged */
76    if (SUCCESS == zend_hash_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO"), (void **) &stuff)) {
77        path_info = Z_STRVAL_PP(stuff);
78        code = Z_STRLEN_PP(stuff);
79
80        if (Z_STRLEN_PP(stuff) > entry_len && !memcmp(Z_STRVAL_PP(stuff), entry, entry_len)) {
81            ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + entry_len, request_uri_len, 1);
82
83            MAKE_STD_ZVAL(temp);
84            ZVAL_STRINGL(temp, path_info, code, 0);
85
86            zend_hash_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO"), &temp, sizeof(zval **), NULL);
87        }
88    }
89
90    if (SUCCESS == zend_hash_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED"), (void **) &stuff)) {
91        path_info = Z_STRVAL_PP(stuff);
92        code = Z_STRLEN_PP(stuff);
93        Z_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, "phar://%s%s", fname, entry);
94
95        MAKE_STD_ZVAL(temp);
96        ZVAL_STRINGL(temp, path_info, code, 0);
97
98        zend_hash_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED"), (void *) &temp, sizeof(zval **), NULL);
99    }
100
101    if (!PHAR_GLOBALS->phar_SERVER_mung_list) {
102        return;
103    }
104
105    if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_REQUEST_URI) {
106        if (SUCCESS == zend_hash_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &stuff)) {
107            path_info = Z_STRVAL_PP(stuff);
108            code = Z_STRLEN_PP(stuff);
109
110            if (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) {
111                ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1);
112
113                MAKE_STD_ZVAL(temp);
114                ZVAL_STRINGL(temp, path_info, code, 0);
115
116                zend_hash_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI"), (void *) &temp, sizeof(zval **), NULL);
117            }
118        }
119    }
120
121    if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_PHP_SELF) {
122        if (SUCCESS == zend_hash_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF"), (void **) &stuff)) {
123            path_info = Z_STRVAL_PP(stuff);
124            code = Z_STRLEN_PP(stuff);
125
126            if (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) {
127                ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1);
128
129                MAKE_STD_ZVAL(temp);
130                ZVAL_STRINGL(temp, path_info, code, 0);
131
132                zend_hash_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF"), (void *) &temp, sizeof(zval **), NULL);
133            }
134        }
135    }
136
137    if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_NAME) {
138        if (SUCCESS == zend_hash_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void **) &stuff)) {
139            path_info = Z_STRVAL_PP(stuff);
140            code = Z_STRLEN_PP(stuff);
141            ZVAL_STRINGL(*stuff, entry, entry_len, 1);
142
143            MAKE_STD_ZVAL(temp);
144            ZVAL_STRINGL(temp, path_info, code, 0);
145
146            zend_hash_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME"), (void *) &temp, sizeof(zval **), NULL);
147        }
148    }
149
150    if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_FILENAME) {
151        if (SUCCESS == zend_hash_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME"), (void **) &stuff)) {
152            path_info = Z_STRVAL_PP(stuff);
153            code = Z_STRLEN_PP(stuff);
154            Z_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, "phar://%s%s", fname, entry);
155
156            MAKE_STD_ZVAL(temp);
157            ZVAL_STRINGL(temp, path_info, code, 0);
158
159            zend_hash_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME"), (void *) &temp, sizeof(zval **), NULL);
160        }
161    }
162}
163/* }}} */
164
165static int phar_file_action(phar_archive_data *phar, phar_entry_info *info, char *mime_type, int code, char *entry, int entry_len, char *arch, char *basename, char *ru, int ru_len TSRMLS_DC) /* {{{ */
166{
167    char *name = NULL, buf[8192];
168    const char *cwd;
169    zend_syntax_highlighter_ini syntax_highlighter_ini;
170    sapi_header_line ctr = {0};
171    size_t got;
172    int dummy = 1, name_len;
173    zend_file_handle file_handle;
174    zend_op_array *new_op_array;
175    zval *result = NULL;
176    php_stream *fp;
177    off_t position;
178
179    switch (code) {
180        case PHAR_MIME_PHPS:
181            efree(basename);
182            /* highlight source */
183            if (entry[0] == '/') {
184                name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry);
185            } else {
186                name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry);
187            }
188            php_get_highlight_struct(&syntax_highlighter_ini);
189
190            highlight_file(name, &syntax_highlighter_ini TSRMLS_CC);
191
192            efree(name);
193#ifdef PHP_WIN32
194            efree(arch);
195#endif
196            zend_bailout();
197        case PHAR_MIME_OTHER:
198            /* send headers, output file contents */
199            efree(basename);
200            ctr.line_len = spprintf(&(ctr.line), 0, "Content-type: %s", mime_type);
201            sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
202            efree(ctr.line);
203            ctr.line_len = spprintf(&(ctr.line), 0, "Content-length: %u", info->uncompressed_filesize);
204            sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
205            efree(ctr.line);
206
207            if (FAILURE == sapi_send_headers(TSRMLS_C)) {
208                zend_bailout();
209            }
210
211            /* prepare to output  */
212            fp = phar_get_efp(info, 1 TSRMLS_CC);
213
214            if (!fp) {
215                char *error;
216                if (!phar_open_jit(phar, info, &error TSRMLS_CC)) {
217                    if (error) {
218                        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
219                        efree(error);
220                    }
221                    return -1;
222                }
223                fp = phar_get_efp(info, 1 TSRMLS_CC);
224            }
225            position = 0;
226            phar_seek_efp(info, 0, SEEK_SET, 0, 1 TSRMLS_CC);
227
228            do {
229                got = php_stream_read(fp, buf, MIN(8192, info->uncompressed_filesize - position));
230                if (got > 0) {
231                    PHPWRITE(buf, got);
232                    position += got;
233                    if (position == (off_t) info->uncompressed_filesize) {
234                        break;
235                    }
236                }
237            } while (1);
238
239            zend_bailout();
240        case PHAR_MIME_PHP:
241            if (basename) {
242                phar_mung_server_vars(arch, entry, entry_len, basename, ru_len TSRMLS_CC);
243                efree(basename);
244            }
245
246            if (entry[0] == '/') {
247                name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry);
248            } else {
249                name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry);
250            }
251
252            file_handle.type = ZEND_HANDLE_FILENAME;
253            file_handle.handle.fd = 0;
254            file_handle.filename = name;
255            file_handle.opened_path = NULL;
256            file_handle.free_filename = 0;
257
258            PHAR_G(cwd) = NULL;
259            PHAR_G(cwd_len) = 0;
260
261            if (zend_hash_add(&EG(included_files), name, name_len+1, (void *)&dummy, sizeof(int), NULL) == SUCCESS) {
262                if ((cwd = zend_memrchr(entry, '/', entry_len))) {
263                    PHAR_G(cwd_init) = 1;
264                    if (entry == cwd) {
265                        /* root directory */
266                        PHAR_G(cwd_len) = 0;
267                        PHAR_G(cwd) = NULL;
268                    } else if (entry[0] == '/') {
269                        PHAR_G(cwd_len) = cwd - (entry + 1);
270                        PHAR_G(cwd) = estrndup(entry + 1, PHAR_G(cwd_len));
271                    } else {
272                        PHAR_G(cwd_len) = cwd - entry;
273                        PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len));
274                    }
275                }
276
277                new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE TSRMLS_CC);
278
279                if (!new_op_array) {
280                    zend_hash_del(&EG(included_files), name, name_len+1);
281                }
282
283                zend_destroy_file_handle(&file_handle TSRMLS_CC);
284
285            } else {
286                efree(name);
287                new_op_array = NULL;
288            }
289#ifdef PHP_WIN32
290            efree(arch);
291#endif
292            if (new_op_array) {
293                EG(return_value_ptr_ptr) = &result;
294                EG(active_op_array) = new_op_array;
295
296                zend_try {
297                    zend_execute(new_op_array TSRMLS_CC);
298                    if (PHAR_G(cwd)) {
299                        efree(PHAR_G(cwd));
300                        PHAR_G(cwd) = NULL;
301                        PHAR_G(cwd_len) = 0;
302                    }
303
304                    PHAR_G(cwd_init) = 0;
305                    efree(name);
306                    destroy_op_array(new_op_array TSRMLS_CC);
307                    efree(new_op_array);
308
309
310                    if (EG(return_value_ptr_ptr) && *EG(return_value_ptr_ptr)) {
311                        zval_ptr_dtor(EG(return_value_ptr_ptr));
312                    }
313                } zend_catch {
314                    if (PHAR_G(cwd)) {
315                        efree(PHAR_G(cwd));
316                        PHAR_G(cwd) = NULL;
317                        PHAR_G(cwd_len) = 0;
318                    }
319
320                    PHAR_G(cwd_init) = 0;
321                    efree(name);
322                } zend_end_try();
323
324                zend_bailout();
325            }
326
327            return PHAR_MIME_PHP;
328    }
329    return -1;
330}
331/* }}} */
332
333static void phar_do_403(char *entry, int entry_len TSRMLS_DC) /* {{{ */
334{
335    sapi_header_line ctr = {0};
336
337    ctr.response_code = 403;
338    ctr.line_len = sizeof("HTTP/1.0 403 Access Denied")-1;
339    ctr.line = "HTTP/1.0 403 Access Denied";
340    sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
341    sapi_send_headers(TSRMLS_C);
342    PHPWRITE("<html>\n <head>\n  <title>Access Denied</title>\n </head>\n <body>\n  <h1>403 - File ", sizeof("<html>\n <head>\n  <title>Access Denied</title>\n </head>\n <body>\n  <h1>403 - File ") - 1);
343    PHPWRITE(entry, entry_len);
344    PHPWRITE(" Access Denied</h1>\n </body>\n</html>", sizeof(" Access Denied</h1>\n </body>\n</html>") - 1);
345}
346/* }}} */
347
348static void phar_do_404(phar_archive_data *phar, char *fname, int fname_len, char *f404, int f404_len, char *entry, int entry_len TSRMLS_DC) /* {{{ */
349{
350    sapi_header_line ctr = {0};
351    phar_entry_info *info;
352
353    if (phar && f404_len) {
354        info = phar_get_entry_info(phar, f404, f404_len, NULL, 1 TSRMLS_CC);
355
356        if (info) {
357            phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0 TSRMLS_CC);
358            return;
359        }
360    }
361
362    ctr.response_code = 404;
363    ctr.line_len = sizeof("HTTP/1.0 404 Not Found")-1;
364    ctr.line = "HTTP/1.0 404 Not Found";
365    sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
366    sapi_send_headers(TSRMLS_C);
367    PHPWRITE("<html>\n <head>\n  <title>File Not Found</title>\n </head>\n <body>\n  <h1>404 - File ", sizeof("<html>\n <head>\n  <title>File Not Found</title>\n </head>\n <body>\n  <h1>404 - File ") - 1);
368    PHPWRITE(entry, entry_len);
369    PHPWRITE(" Not Found</h1>\n </body>\n</html>",  sizeof(" Not Found</h1>\n </body>\n</html>") - 1);
370}
371/* }}} */
372
373/* post-process REQUEST_URI and retrieve the actual request URI.  This is for
374   cases like http://localhost/blah.phar/path/to/file.php/extra/stuff
375   which calls "blah.phar" file "path/to/file.php" with PATH_INFO "/extra/stuff" */
376static void phar_postprocess_ru_web(char *fname, int fname_len, char **entry, int *entry_len, char **ru, int *ru_len TSRMLS_DC) /* {{{ */
377{
378    char *e = *entry + 1, *u = NULL, *u1 = NULL, *saveu = NULL;
379    int e_len = *entry_len - 1, u_len = 0;
380    phar_archive_data **pphar = NULL;
381
382    /* we already know we can retrieve the phar if we reach here */
383    zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, (void **) &pphar);
384
385    if (!pphar && PHAR_G(manifest_cached)) {
386        zend_hash_find(&cached_phars, fname, fname_len, (void **) &pphar);
387    }
388
389    do {
390        if (zend_hash_exists(&((*pphar)->manifest), e, e_len)) {
391            if (u) {
392                u[0] = '/';
393                *ru = estrndup(u, u_len+1);
394                ++u_len;
395                u[0] = '\0';
396            } else {
397                *ru = NULL;
398            }
399            *ru_len = u_len;
400            *entry_len = e_len + 1;
401            return;
402        }
403
404        if (u) {
405            u1 = strrchr(e, '/');
406            u[0] = '/';
407            saveu = u;
408            e_len += u_len + 1;
409            u = u1;
410            if (!u) {
411                return;
412            }
413        } else {
414            u = strrchr(e, '/');
415            if (!u) {
416                if (saveu) {
417                    saveu[0] = '/';
418                }
419                return;
420            }
421        }
422
423        u[0] = '\0';
424        u_len = strlen(u + 1);
425        e_len -= u_len + 1;
426
427        if (e_len < 0) {
428            if (saveu) {
429                saveu[0] = '/';
430            }
431            return;
432        }
433    } while (1);
434}
435/* }}} */
436
437/* {{{ proto void Phar::running([bool retphar = true])
438 * return the name of the currently running phar archive.  If the optional parameter
439 * is set to true, return the phar:// URL to the currently running phar
440 */
441PHP_METHOD(Phar, running)
442{
443    char *fname, *arch, *entry;
444    int fname_len, arch_len, entry_len;
445    zend_bool retphar = 1;
446
447    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &retphar) == FAILURE) {
448        return;
449    }
450
451    fname = (char*)zend_get_executed_filename(TSRMLS_C);
452    fname_len = strlen(fname);
453
454    if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
455        efree(entry);
456        if (retphar) {
457            RETVAL_STRINGL(fname, arch_len + 7, 1);
458            efree(arch);
459            return;
460        } else {
461            RETURN_STRINGL(arch, arch_len, 0);
462        }
463    }
464
465    RETURN_STRINGL("", 0, 1);
466}
467/* }}} */
468
469/* {{{ proto void Phar::mount(string pharpath, string externalfile)
470 * mount an external file or path to a location within the phar.  This maps
471 * an external file or directory to a location within the phar archive, allowing
472 * reference to an external location as if it were within the phar archive.  This
473 * is useful for writable temp files like databases
474 */
475PHP_METHOD(Phar, mount)
476{
477    char *fname, *arch = NULL, *entry = NULL, *path, *actual;
478    int fname_len, arch_len, entry_len, path_len, actual_len;
479    phar_archive_data **pphar;
480
481    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &actual, &actual_len) == FAILURE) {
482        return;
483    }
484
485    fname = (char*)zend_get_executed_filename(TSRMLS_C);
486    fname_len = strlen(fname);
487
488#ifdef PHP_WIN32
489    phar_unixify_path_separators(fname, fname_len);
490#endif
491
492    if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
493        efree(entry);
494        entry = NULL;
495
496        if (path_len > 7 && !memcmp(path, "phar://", 7)) {
497            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path);
498            efree(arch);
499            return;
500        }
501carry_on2:
502        if (SUCCESS != zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **)&pphar)) {
503            if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, arch, arch_len, (void **)&pphar)) {
504                if (SUCCESS == phar_copy_on_write(pphar TSRMLS_CC)) {
505                    goto carry_on;
506                }
507            }
508
509            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s is not a phar archive, cannot mount", arch);
510
511            if (arch) {
512                efree(arch);
513            }
514            return;
515        }
516carry_on:
517        if (SUCCESS != phar_mount_entry(*pphar, actual, actual_len, path, path_len TSRMLS_CC)) {
518            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Mounting of %s to %s within phar %s failed", path, actual, arch);
519            if (path && path == entry) {
520                efree(entry);
521            }
522
523            if (arch) {
524                efree(arch);
525            }
526
527            return;
528        }
529
530        if (entry && path && path == entry) {
531            efree(entry);
532        }
533
534        if (arch) {
535            efree(arch);
536        }
537
538        return;
539    } else if (PHAR_GLOBALS->phar_fname_map.arBuckets && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, (void **)&pphar)) {
540        goto carry_on;
541    } else if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, fname, fname_len, (void **)&pphar)) {
542        if (SUCCESS == phar_copy_on_write(pphar TSRMLS_CC)) {
543            goto carry_on;
544        }
545
546        goto carry_on;
547    } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
548        path = entry;
549        path_len = entry_len;
550        goto carry_on2;
551    }
552
553    zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Mounting of %s to %s failed", path, actual);
554}
555/* }}} */
556
557/* {{{ proto void Phar::webPhar([string alias, [string index, [string f404, [array mimetypes, [callback rewrites]]]]])
558 * mapPhar for web-based phars. Reads the currently executed file (a phar)
559 * and registers its manifest. When executed in the CLI or CGI command-line sapi,
560 * this works exactly like mapPhar().  When executed by a web-based sapi, this
561 * reads $_SERVER['REQUEST_URI'] (the actual original value) and parses out the
562 * intended internal file.
563 */
564PHP_METHOD(Phar, webPhar)
565{
566    zval *mimeoverride = NULL, *rewrite = NULL;
567    char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
568    int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0;
569    char *fname, *path_info, *mime_type = NULL, *entry, *pt;
570    const char *basename;
571    int fname_len, entry_len, code, index_php_len = 0, not_cgi;
572    phar_archive_data *phar = NULL;
573    phar_entry_info *info = NULL;
574
575    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
576        return;
577    }
578
579    phar_request_initialize(TSRMLS_C);
580    fname = (char*)zend_get_executed_filename(TSRMLS_C);
581    fname_len = strlen(fname);
582
583    if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) {
584        if (error) {
585            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
586            efree(error);
587        }
588        return;
589    }
590
591    /* retrieve requested file within phar */
592    if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) {
593        return;
594    }
595
596#ifdef PHP_WIN32
597    fname = estrndup(fname, fname_len);
598    phar_unixify_path_separators(fname, fname_len);
599#endif
600    basename = zend_memrchr(fname, '/', fname_len);
601
602    if (!basename) {
603        basename = fname;
604    } else {
605        ++basename;
606    }
607
608    if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1))
609        || (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1))
610        || (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) {
611
612        if (PG(http_globals)[TRACK_VARS_SERVER]) {
613            HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
614            zval **z_script_name, **z_path_info;
615
616            if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) ||
617                IS_STRING != Z_TYPE_PP(z_script_name) ||
618                !strstr(Z_STRVAL_PP(z_script_name), basename)) {
619                return;
620            }
621
622            if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) &&
623                IS_STRING == Z_TYPE_PP(z_path_info)) {
624                entry_len = Z_STRLEN_PP(z_path_info);
625                entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len);
626                path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1);
627                memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
628                memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1);
629                free_pathinfo = 1;
630            } else {
631                entry_len = 0;
632                entry = estrndup("", 0);
633                path_info = Z_STRVAL_PP(z_script_name);
634            }
635
636            pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
637
638        } else {
639            char *testit;
640
641            testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
642            if (!(pt = strstr(testit, basename))) {
643                efree(testit);
644                return;
645            }
646
647            path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
648
649            if (path_info) {
650                entry = path_info;
651                entry_len = strlen(entry);
652                spprintf(&path_info, 0, "%s%s", testit, path_info);
653                free_pathinfo = 1;
654            } else {
655                path_info = testit;
656                free_pathinfo = 1;
657                entry = estrndup("", 0);
658                entry_len = 0;
659            }
660
661            pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
662        }
663        not_cgi = 0;
664    } else {
665        path_info = SG(request_info).request_uri;
666
667        if (!(pt = strstr(path_info, basename))) {
668            /* this can happen with rewrite rules - and we have no idea what to do then, so return */
669            return;
670        }
671
672        entry_len = strlen(path_info);
673        entry_len -= (pt - path_info) + (fname_len - (basename - fname));
674        entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
675
676        pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
677        not_cgi = 1;
678    }
679
680    if (rewrite) {
681        zend_fcall_info fci;
682        zend_fcall_info_cache fcc;
683        zval *params, *retval_ptr, **zp[1];
684
685        MAKE_STD_ZVAL(params);
686        ZVAL_STRINGL(params, entry, entry_len, 1);
687        zp[0] = &params;
688
689#if PHP_VERSION_ID < 50300
690        if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) {
691#else
692        if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) {
693#endif
694            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback");
695
696            if (free_pathinfo) {
697                efree(path_info);
698            }
699
700            return;
701        }
702
703        fci.param_count = 1;
704        fci.params = zp;
705#if PHP_VERSION_ID < 50300
706        ++(params->refcount);
707#else
708        Z_ADDREF_P(params);
709#endif
710        fci.retval_ptr_ptr = &retval_ptr;
711
712        if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) {
713            if (!EG(exception)) {
714                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback");
715            }
716
717            if (free_pathinfo) {
718                efree(path_info);
719            }
720
721            return;
722        }
723
724        if (!fci.retval_ptr_ptr || !retval_ptr) {
725            if (free_pathinfo) {
726                efree(path_info);
727            }
728            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
729            return;
730        }
731
732        switch (Z_TYPE_P(retval_ptr)) {
733#if PHP_VERSION_ID >= 60000
734            case IS_UNICODE:
735                zval_unicode_to_string(retval_ptr TSRMLS_CC);
736                /* break intentionally omitted */
737#endif
738            case IS_STRING:
739                efree(entry);
740
741                if (fci.retval_ptr_ptr != &retval_ptr) {
742                    entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr));
743                    entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr);
744                } else {
745                    entry = Z_STRVAL_P(retval_ptr);
746                    entry_len = Z_STRLEN_P(retval_ptr);
747                }
748
749                break;
750            case IS_BOOL:
751                phar_do_403(entry, entry_len TSRMLS_CC);
752
753                if (free_pathinfo) {
754                    efree(path_info);
755                }
756
757                zend_bailout();
758                return;
759            default:
760                efree(retval_ptr);
761
762                if (free_pathinfo) {
763                    efree(path_info);
764                }
765
766                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
767                return;
768        }
769    }
770
771    if (entry_len) {
772        phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC);
773    }
774
775    if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
776        efree(entry);
777        /* direct request */
778        if (index_php_len) {
779            entry = index_php;
780            entry_len = index_php_len;
781            if (entry[0] != '/') {
782                spprintf(&entry, 0, "/%s", index_php);
783                ++entry_len;
784            }
785        } else {
786            /* assume "index.php" is starting point */
787            entry = estrndup("/index.php", sizeof("/index.php"));
788            entry_len = sizeof("/index.php")-1;
789        }
790
791        if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
792            (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
793            phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
794
795            if (free_pathinfo) {
796                efree(path_info);
797            }
798
799            zend_bailout();
800        } else {
801            char *tmp = NULL, sa = '\0';
802            sapi_header_line ctr = {0};
803            ctr.response_code = 301;
804            ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
805            ctr.line = "HTTP/1.1 301 Moved Permanently";
806            sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
807
808            if (not_cgi) {
809                tmp = strstr(path_info, basename) + fname_len;
810                sa = *tmp;
811                *tmp = '\0';
812            }
813
814            ctr.response_code = 0;
815
816            if (path_info[strlen(path_info)-1] == '/') {
817                ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
818            } else {
819                ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
820            }
821
822            if (not_cgi) {
823                *tmp = sa;
824            }
825
826            if (free_pathinfo) {
827                efree(path_info);
828            }
829
830            sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
831            sapi_send_headers(TSRMLS_C);
832            efree(ctr.line);
833            zend_bailout();
834        }
835    }
836
837    if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
838        (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
839        phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
840#ifdef PHP_WIN32
841        efree(fname);
842#endif
843        zend_bailout();
844    }
845
846    if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
847        const char *ext = zend_memrchr(entry, '.', entry_len);
848        zval **val;
849
850        if (ext) {
851            ++ext;
852
853            if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) {
854                switch (Z_TYPE_PP(val)) {
855                    case IS_LONG:
856                        if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) {
857                            mime_type = "";
858                            code = Z_LVAL_PP(val);
859                        } else {
860                            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
861#ifdef PHP_WIN32
862                            efree(fname);
863#endif
864                            RETURN_FALSE;
865                        }
866                        break;
867                    case IS_STRING:
868                        mime_type = Z_STRVAL_PP(val);
869                        code = PHAR_MIME_OTHER;
870                        break;
871                    default:
872                        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
873#ifdef PHP_WIN32
874                        efree(fname);
875#endif
876                        RETURN_FALSE;
877                }
878            }
879        }
880    }
881
882    if (!mime_type) {
883        code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC);
884    }
885    ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC);
886}
887/* }}} */
888
889/* {{{ proto void Phar::mungServer(array munglist)
890 * Defines a list of up to 4 $_SERVER variables that should be modified for execution
891 * to mask the presence of the phar archive.  This should be used in conjunction with
892 * Phar::webPhar(), and has no effect otherwise
893 * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
894 */
895PHP_METHOD(Phar, mungServer)
896{
897    zval *mungvalues;
898
899    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) {
900        return;
901    }
902
903    if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
904        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
905        return;
906    }
907
908    if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
909        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
910        return;
911    }
912
913    phar_request_initialize(TSRMLS_C);
914
915    for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) {
916        zval **data = NULL;
917
918        if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) {
919            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()");
920            return;
921        }
922
923        if (Z_TYPE_PP(data) != IS_STRING) {
924            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
925            return;
926        }
927
928        if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
929            PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF;
930        }
931
932        if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) {
933            if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
934                PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI;
935            }
936            if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
937                PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME;
938            }
939        }
940
941        if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
942            PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME;
943        }
944    }
945}
946/* }}} */
947
948/* {{{ proto void Phar::interceptFileFuncs()
949 * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
950 * and return stat on files within the phar for relative paths
951 *
952 * Once called, this cannot be reversed, and continue until the end of the request.
953 *
954 * This allows legacy scripts to be pharred unmodified
955 */
956PHP_METHOD(Phar, interceptFileFuncs)
957{
958    if (zend_parse_parameters_none() == FAILURE) {
959        return;
960    }
961    phar_intercept_functions(TSRMLS_C);
962}
963/* }}} */
964
965/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
966 * Return a stub that can be used to run a phar-based archive without the phar extension
967 * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
968 * is the web startup filename, and also defaults to "index.php"
969 */
970PHP_METHOD(Phar, createDefaultStub)
971{
972    char *index = NULL, *webindex = NULL, *stub, *error;
973    int index_len = 0, webindex_len = 0;
974    size_t stub_len;
975
976    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
977        return;
978    }
979
980    stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
981
982    if (error) {
983        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
984        efree(error);
985        return;
986    }
987    RETURN_STRINGL(stub, stub_len, 0);
988}
989/* }}} */
990
991/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
992 * Reads the currently executed file (a phar) and registers its manifest */
993PHP_METHOD(Phar, mapPhar)
994{
995    char *alias = NULL, *error;
996    int alias_len = 0;
997    long dataoffset = 0;
998
999    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
1000        return;
1001    }
1002
1003    phar_request_initialize(TSRMLS_C);
1004
1005    RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS);
1006
1007    if (error) {
1008        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
1009        efree(error);
1010    }
1011} /* }}} */
1012
1013/* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
1014 * Loads any phar archive with an alias */
1015PHP_METHOD(Phar, loadPhar)
1016{
1017    char *fname, *alias = NULL, *error;
1018    int fname_len, alias_len = 0;
1019
1020    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
1021        return;
1022    }
1023
1024    phar_request_initialize(TSRMLS_C);
1025
1026    RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS);
1027
1028    if (error) {
1029        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
1030        efree(error);
1031    }
1032} /* }}} */
1033
1034/* {{{ proto string Phar::apiVersion()
1035 * Returns the api version */
1036PHP_METHOD(Phar, apiVersion)
1037{
1038    if (zend_parse_parameters_none() == FAILURE) {
1039        return;
1040    }
1041    RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1);
1042}
1043/* }}}*/
1044
1045/* {{{ proto bool Phar::canCompress([int method])
1046 * Returns whether phar extension supports compression using zlib/bzip2 */
1047PHP_METHOD(Phar, canCompress)
1048{
1049    long method = 0;
1050
1051    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
1052        return;
1053    }
1054
1055    phar_request_initialize(TSRMLS_C);
1056    switch (method) {
1057    case PHAR_ENT_COMPRESSED_GZ:
1058        if (PHAR_G(has_zlib)) {
1059            RETURN_TRUE;
1060        } else {
1061            RETURN_FALSE;
1062        }
1063    case PHAR_ENT_COMPRESSED_BZ2:
1064        if (PHAR_G(has_bz2)) {
1065            RETURN_TRUE;
1066        } else {
1067            RETURN_FALSE;
1068        }
1069    default:
1070        if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
1071            RETURN_TRUE;
1072        } else {
1073            RETURN_FALSE;
1074        }
1075    }
1076}
1077/* }}} */
1078
1079/* {{{ proto bool Phar::canWrite()
1080 * Returns whether phar extension supports writing and creating phars */
1081PHP_METHOD(Phar, canWrite)
1082{
1083    if (zend_parse_parameters_none() == FAILURE) {
1084        return;
1085    }
1086    RETURN_BOOL(!PHAR_G(readonly));
1087}
1088/* }}} */
1089
1090/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
1091 * Returns whether the given filename is a valid phar filename */
1092PHP_METHOD(Phar, isValidPharFilename)
1093{
1094    char *fname;
1095    const char *ext_str;
1096    int fname_len, ext_len, is_executable;
1097    zend_bool executable = 1;
1098
1099    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) {
1100        return;
1101    }
1102
1103    is_executable = executable;
1104    RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS);
1105}
1106/* }}} */
1107
1108#if HAVE_SPL
1109/**
1110 * from spl_directory
1111 */
1112static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */
1113{
1114    phar_archive_data *phar = (phar_archive_data *) object->oth;
1115
1116    if (!phar->is_persistent) {
1117        phar_archive_delref(phar TSRMLS_CC);
1118    }
1119
1120    object->oth = NULL;
1121}
1122/* }}} */
1123
1124/**
1125 * from spl_directory
1126 */
1127static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */
1128{
1129    phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
1130
1131    if (!phar_data->is_persistent) {
1132        ++(phar_data->refcount);
1133    }
1134}
1135/* }}} */
1136
1137static spl_other_handler phar_spl_foreign_handler = {
1138    phar_spl_foreign_dtor,
1139    phar_spl_foreign_clone
1140};
1141#endif /* HAVE_SPL */
1142
1143/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]])
1144 * Construct a Phar archive object
1145 *
1146 * proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
1147 * Construct a PharData archive object
1148 *
1149 * This function is used as the constructor for both the Phar and PharData
1150 * classes, hence the two prototypes above.
1151 */
1152PHP_METHOD(Phar, __construct)
1153{
1154#if !HAVE_SPL
1155    zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
1156#else
1157    char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
1158    int fname_len, alias_len = 0, arch_len, entry_len, is_data;
1159#if PHP_VERSION_ID < 50300
1160    long flags = 0;
1161#else
1162    long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
1163#endif
1164    long format = 0;
1165    phar_archive_object *phar_obj;
1166    phar_archive_data   *phar_data;
1167    zval *zobj = getThis(), arg1, arg2;
1168
1169    phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
1170
1171    is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
1172
1173    if (is_data) {
1174        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
1175            return;
1176        }
1177    } else {
1178        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
1179            return;
1180        }
1181    }
1182
1183    if (phar_obj->arc.archive) {
1184        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
1185        return;
1186    }
1187
1188    save_fname = fname;
1189    if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
1190        /* use arch (the basename for the archive) for fname instead of fname */
1191        /* this allows support for RecursiveDirectoryIterator of subdirectories */
1192#ifdef PHP_WIN32
1193        phar_unixify_path_separators(arch, arch_len);
1194#endif
1195        fname = arch;
1196        fname_len = arch_len;
1197#ifdef PHP_WIN32
1198    } else {
1199        arch = estrndup(fname, fname_len);
1200        arch_len = fname_len;
1201        fname = arch;
1202        phar_unixify_path_separators(arch, arch_len);
1203#endif
1204    }
1205
1206    if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
1207
1208        if (fname == arch && fname != save_fname) {
1209            efree(arch);
1210            fname = save_fname;
1211        }
1212
1213        if (entry) {
1214            efree(entry);
1215        }
1216
1217        if (error) {
1218            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
1219                "%s", error);
1220            efree(error);
1221        } else {
1222            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
1223                "Phar creation or opening failed");
1224        }
1225
1226        return;
1227    }
1228
1229    if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
1230        phar_data->is_zip = 1;
1231        phar_data->is_tar = 0;
1232    }
1233
1234    if (fname == arch) {
1235        efree(arch);
1236        fname = save_fname;
1237    }
1238
1239    if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
1240        if (is_data) {
1241            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
1242                "PharData class can only be used for non-executable tar and zip archives");
1243        } else {
1244            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
1245                "Phar class can only be used for executable tar and zip archives");
1246        }
1247        efree(entry);
1248        return;
1249    }
1250
1251    is_data = phar_data->is_data;
1252
1253    if (!phar_data->is_persistent) {
1254        ++(phar_data->refcount);
1255    }
1256
1257    phar_obj->arc.archive = phar_data;
1258    phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
1259
1260    if (entry) {
1261        fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
1262        efree(entry);
1263    } else {
1264        fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
1265    }
1266
1267    INIT_PZVAL(&arg1);
1268    ZVAL_STRINGL(&arg1, fname, fname_len, 0);
1269    INIT_PZVAL(&arg2);
1270    ZVAL_LONG(&arg2, flags);
1271
1272    zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
1273        &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
1274
1275    if (!phar_data->is_persistent) {
1276        phar_obj->arc.archive->is_data = is_data;
1277    } else if (!EG(exception)) {
1278        /* register this guy so we can modify if necessary */
1279        zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
1280    }
1281
1282    phar_obj->spl.info_class = phar_ce_entry;
1283    efree(fname);
1284#endif /* HAVE_SPL */
1285}
1286/* }}} */
1287
1288/* {{{ proto array Phar::getSupportedSignatures()
1289 * Return array of supported signature types
1290 */
1291PHP_METHOD(Phar, getSupportedSignatures)
1292{
1293    if (zend_parse_parameters_none() == FAILURE) {
1294        return;
1295    }
1296
1297    array_init(return_value);
1298
1299    add_next_index_stringl(return_value, "MD5", 3, 1);
1300    add_next_index_stringl(return_value, "SHA-1", 5, 1);
1301#ifdef PHAR_HASH_OK
1302    add_next_index_stringl(return_value, "SHA-256", 7, 1);
1303    add_next_index_stringl(return_value, "SHA-512", 7, 1);
1304#endif
1305#if PHAR_HAVE_OPENSSL
1306    add_next_index_stringl(return_value, "OpenSSL", 7, 1);
1307#else
1308    if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
1309        add_next_index_stringl(return_value, "OpenSSL", 7, 1);
1310    }
1311#endif
1312}
1313/* }}} */
1314
1315/* {{{ proto array Phar::getSupportedCompression()
1316 * Return array of supported comparession algorithms
1317 */
1318PHP_METHOD(Phar, getSupportedCompression)
1319{
1320    if (zend_parse_parameters_none() == FAILURE) {
1321        return;
1322    }
1323
1324    array_init(return_value);
1325    phar_request_initialize(TSRMLS_C);
1326
1327    if (PHAR_G(has_zlib)) {
1328        add_next_index_stringl(return_value, "GZ", 2, 1);
1329    }
1330
1331    if (PHAR_G(has_bz2)) {
1332        add_next_index_stringl(return_value, "BZIP2", 5, 1);
1333    }
1334}
1335/* }}} */
1336
1337/* {{{ proto array Phar::unlinkArchive(string archive)
1338 * Completely remove a phar archive from memory and disk
1339 */
1340PHP_METHOD(Phar, unlinkArchive)
1341{
1342    char *fname, *error, *zname, *arch, *entry;
1343    int fname_len, zname_len, arch_len, entry_len;
1344    phar_archive_data *phar;
1345
1346    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
1347        RETURN_FALSE;
1348    }
1349
1350    if (!fname_len) {
1351        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\"");
1352        return;
1353    }
1354
1355    if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) {
1356        if (error) {
1357            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error);
1358            efree(error);
1359        } else {
1360            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname);
1361        }
1362        return;
1363    }
1364
1365    zname = (char*)zend_get_executed_filename(TSRMLS_C);
1366    zname_len = strlen(zname);
1367
1368    if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
1369        if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
1370            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname);
1371            efree(arch);
1372            efree(entry);
1373            return;
1374        }
1375        efree(arch);
1376        efree(entry);
1377    }
1378
1379    if (phar->is_persistent) {
1380        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
1381        return;
1382    }
1383
1384    if (phar->refcount) {
1385        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects.  fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
1386        return;
1387    }
1388
1389    fname = estrndup(phar->fname, phar->fname_len);
1390
1391    /* invalidate phar cache */
1392    PHAR_G(last_phar) = NULL;
1393    PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
1394
1395    phar_archive_delref(phar TSRMLS_CC);
1396    unlink(fname);
1397    efree(fname);
1398    RETURN_TRUE;
1399}
1400/* }}} */
1401
1402#if HAVE_SPL
1403
1404#define PHAR_ARCHIVE_OBJECT() \
1405    phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
1406    if (!phar_obj->arc.archive) { \
1407        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
1408            "Cannot call method on an uninitialized Phar object"); \
1409        return; \
1410    }
1411
1412/* {{{ proto void Phar::__destruct()
1413 * if persistent, remove from the cache
1414 */
1415PHP_METHOD(Phar, __destruct)
1416{
1417    phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
1418
1419    if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) {
1420        zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive));
1421    }
1422}
1423/* }}} */
1424
1425struct _phar_t {
1426    phar_archive_object *p;
1427    zend_class_entry *c;
1428    char *b;
1429    uint l;
1430    zval *ret;
1431    int count;
1432    php_stream *fp;
1433};
1434
1435static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */
1436{
1437    zval **value;
1438    zend_uchar key_type;
1439    zend_bool close_fp = 1;
1440    ulong int_key;
1441    struct _phar_t *p_obj = (struct _phar_t*) puser;
1442    uint str_key_len, base_len = p_obj->l, fname_len;
1443    phar_entry_data *data;
1444    php_stream *fp;
1445    size_t contents_len;
1446    char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL;
1447    phar_zstr key;
1448    char *str_key;
1449    zend_class_entry *ce = p_obj->c;
1450    phar_archive_object *phar_obj = p_obj->p;
1451    char *str = "[stream]";
1452
1453    iter->funcs->get_current_data(iter, &value TSRMLS_CC);
1454
1455    if (EG(exception)) {
1456        return ZEND_HASH_APPLY_STOP;
1457    }
1458
1459    if (!value) {
1460        /* failure in get_current_data */
1461        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name);
1462        return ZEND_HASH_APPLY_STOP;
1463    }
1464
1465    switch (Z_TYPE_PP(value)) {
1466#if PHP_VERSION_ID >= 60000
1467        case IS_UNICODE:
1468            zval_unicode_to_string(*(value) TSRMLS_CC);
1469            /* break intentionally omitted */
1470#endif
1471        case IS_STRING:
1472            break;
1473        case IS_RESOURCE:
1474            php_stream_from_zval_no_verify(fp, value);
1475
1476            if (!fp) {
1477                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name);
1478                return ZEND_HASH_APPLY_STOP;
1479            }
1480
1481            if (iter->funcs->get_current_key) {
1482                key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
1483
1484                if (EG(exception)) {
1485                    return ZEND_HASH_APPLY_STOP;
1486                }
1487
1488                if (key_type == HASH_KEY_IS_LONG) {
1489                    zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
1490                    return ZEND_HASH_APPLY_STOP;
1491                }
1492
1493                if (key_type > 9) { /* IS_UNICODE == 10 */
1494#if PHP_VERSION_ID < 60000
1495/* this can never happen, but fixes a compile warning */
1496                    spprintf(&str_key, 0, "%s", key);
1497#else
1498                    spprintf(&str_key, 0, "%v", key);
1499                    ezfree(key);
1500#endif
1501                } else {
1502                    PHAR_STR(key, str_key);
1503                }
1504
1505                save = str_key;
1506
1507                if (str_key[str_key_len - 1] == '\0') {
1508                    str_key_len--;
1509                }
1510
1511            } else {
1512                zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
1513                return ZEND_HASH_APPLY_STOP;
1514            }
1515
1516            close_fp = 0;
1517            opened = (char *) estrndup(str, sizeof("[stream]") - 1);
1518            goto after_open_fp;
1519        case IS_OBJECT:
1520            if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) {
1521                char *test = NULL;
1522                zval dummy;
1523                spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC);
1524
1525                if (!base_len) {
1526                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name);
1527                    return ZEND_HASH_APPLY_STOP;
1528                }
1529
1530                switch (intern->type) {
1531                    case SPL_FS_DIR:
1532#if PHP_VERSION_ID >= 60000
1533                        test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s;
1534#elif PHP_VERSION_ID >= 50300
1535                        test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC);
1536#else
1537                        test = intern->path;
1538#endif
1539                        fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
1540                        php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC);
1541
1542                        if (Z_BVAL(dummy)) {
1543                            /* ignore directories */
1544                            efree(fname);
1545                            return ZEND_HASH_APPLY_KEEP;
1546                        }
1547
1548                        test = expand_filepath(fname, NULL TSRMLS_CC);
1549                        efree(fname);
1550
1551                        if (test) {
1552                            fname = test;
1553                            fname_len = strlen(fname);
1554                        } else {
1555                            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
1556                            return ZEND_HASH_APPLY_STOP;
1557                        }
1558
1559                        save = fname;
1560                        goto phar_spl_fileinfo;
1561                    case SPL_FS_INFO:
1562                    case SPL_FS_FILE:
1563#if PHP_VERSION_ID >= 60000
1564                        if (intern->file_name_type == IS_UNICODE) {
1565                            zval zv;
1566
1567                            INIT_ZVAL(zv);
1568                            Z_UNIVAL(zv) = intern->file_name;
1569                            Z_UNILEN(zv) = intern->file_name_len;
1570                            Z_TYPE(zv) = IS_UNICODE;
1571
1572                            zval_copy_ctor(&zv);
1573                            zval_unicode_to_string(&zv TSRMLS_CC);
1574                            fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC);
1575                            ezfree(Z_UNIVAL(zv));
1576                        } else {
1577                            fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC);
1578                        }
1579#else
1580                        fname = expand_filepath(intern->file_name, NULL TSRMLS_CC);
1581#endif
1582                        if (!fname) {
1583                            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
1584                            return ZEND_HASH_APPLY_STOP;
1585                        }
1586
1587                        fname_len = strlen(fname);
1588                        save = fname;
1589                        goto phar_spl_fileinfo;
1590                }
1591            }
1592            /* fall-through */
1593        default:
1594            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name);
1595            return ZEND_HASH_APPLY_STOP;
1596    }
1597
1598    fname = Z_STRVAL_PP(value);
1599    fname_len = Z_STRLEN_PP(value);
1600
1601phar_spl_fileinfo:
1602    if (base_len) {
1603        temp = expand_filepath(base, NULL TSRMLS_CC);
1604        if (!temp) {
1605            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
1606            if (save) {
1607                efree(save);
1608            }
1609            return ZEND_HASH_APPLY_STOP;
1610        }
1611
1612        base = temp;
1613        base_len = strlen(base);
1614
1615        if (strstr(fname, base)) {
1616            str_key_len = fname_len - base_len;
1617
1618            if (str_key_len <= 0) {
1619                if (save) {
1620                    efree(save);
1621                    efree(temp);
1622                }
1623                return ZEND_HASH_APPLY_KEEP;
1624            }
1625
1626            str_key = fname + base_len;
1627
1628            if (*str_key == '/' || *str_key == '\\') {
1629                str_key++;
1630                str_key_len--;
1631            }
1632
1633        } else {
1634            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base);
1635
1636            if (save) {
1637                efree(save);
1638                efree(temp);
1639            }
1640
1641            return ZEND_HASH_APPLY_STOP;
1642        }
1643    } else {
1644        if (iter->funcs->get_current_key) {
1645            key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
1646
1647            if (EG(exception)) {
1648                return ZEND_HASH_APPLY_STOP;
1649            }
1650
1651            if (key_type == HASH_KEY_IS_LONG) {
1652                zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
1653                return ZEND_HASH_APPLY_STOP;
1654            }
1655
1656            if (key_type > 9) { /* IS_UNICODE == 10 */
1657#if PHP_VERSION_ID < 60000
1658/* this can never happen, but fixes a compile warning */
1659                spprintf(&str_key, 0, "%s", key);
1660#else
1661                spprintf(&str_key, 0, "%v", key);
1662                ezfree(key);
1663#endif
1664            } else {
1665                PHAR_STR(key, str_key);
1666            }
1667
1668            save = str_key;
1669
1670            if (str_key[str_key_len - 1] == '\0') str_key_len--;
1671        } else {
1672            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
1673            return ZEND_HASH_APPLY_STOP;
1674        }
1675    }
1676#if PHP_API_VERSION < 20100412
1677    if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
1678        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname);
1679
1680        if (save) {
1681            efree(save);
1682        }
1683
1684        if (temp) {
1685            efree(temp);
1686        }
1687
1688        return ZEND_HASH_APPLY_STOP;
1689    }
1690#endif
1691
1692    if (php_check_open_basedir(fname TSRMLS_CC)) {
1693        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname);
1694
1695        if (save) {
1696            efree(save);
1697        }
1698
1699        if (temp) {
1700            efree(temp);
1701        }
1702
1703        return ZEND_HASH_APPLY_STOP;
1704    }
1705
1706    /* try to open source file, then create internal phar file and copy contents */
1707    fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
1708
1709    if (!fp) {
1710        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname);
1711
1712        if (save) {
1713            efree(save);
1714        }
1715
1716        if (temp) {
1717            efree(temp);
1718        }
1719
1720        return ZEND_HASH_APPLY_STOP;
1721    }
1722after_open_fp:
1723    if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
1724        /* silently skip any files that would be added to the magic .phar directory */
1725        if (save) {
1726            efree(save);
1727        }
1728
1729        if (temp) {
1730            efree(temp);
1731        }
1732
1733        if (opened) {
1734            efree(opened);
1735        }
1736
1737        if (close_fp) {
1738            php_stream_close(fp);
1739        }
1740
1741        return ZEND_HASH_APPLY_KEEP;
1742    }
1743
1744    if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
1745        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error);
1746        efree(error);
1747
1748        if (save) {
1749            efree(save);
1750        }
1751
1752        if (opened) {
1753            efree(opened);
1754        }
1755
1756        if (temp) {
1757            efree(temp);
1758        }
1759
1760        if (close_fp) {
1761            php_stream_close(fp);
1762        }
1763
1764        return ZEND_HASH_APPLY_STOP;
1765
1766    } else {
1767        if (error) {
1768            efree(error);
1769        }
1770        /* convert to PHAR_UFP */
1771        if (data->internal_file->fp_type == PHAR_MOD) {
1772            php_stream_close(data->internal_file->fp);
1773        }
1774
1775        data->internal_file->fp = NULL;
1776        data->internal_file->fp_type = PHAR_UFP;
1777        data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
1778        data->fp = NULL;
1779        phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
1780        data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
1781            php_stream_tell(p_obj->fp) - data->internal_file->offset;
1782    }
1783
1784    if (close_fp) {
1785        php_stream_close(fp);
1786    }
1787
1788    add_assoc_string(p_obj->ret, str_key, opened, 0);
1789
1790    if (save) {
1791        efree(save);
1792    }
1793
1794    if (temp) {
1795        efree(temp);
1796    }
1797
1798    data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
1799    phar_entry_delref(data TSRMLS_CC);
1800
1801    return ZEND_HASH_APPLY_KEEP;
1802}
1803/* }}} */
1804
1805/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
1806 * Construct a phar archive from an existing directory, recursively.
1807 * Optional second parameter is a regular expression for filtering directory contents.
1808 *
1809 * Return value is an array mapping phar index to actual files added.
1810 */
1811PHP_METHOD(Phar, buildFromDirectory)
1812{
1813    char *dir, *error, *regex = NULL;
1814    int dir_len, regex_len = 0;
1815    zend_bool apply_reg = 0;
1816    zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
1817    struct _phar_t pass;
1818
1819    PHAR_ARCHIVE_OBJECT();
1820
1821    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
1822        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
1823            "Cannot write to archive - write operations restricted by INI setting");
1824        return;
1825    }
1826
1827    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) {
1828        RETURN_FALSE;
1829    }
1830
1831    MAKE_STD_ZVAL(iter);
1832
1833    if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
1834        zval_ptr_dtor(&iter);
1835        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
1836        RETURN_FALSE;
1837    }
1838
1839    INIT_PZVAL(&arg);
1840    ZVAL_STRINGL(&arg, dir, dir_len, 0);
1841    INIT_PZVAL(&arg2);
1842#if PHP_VERSION_ID < 50300
1843    ZVAL_LONG(&arg2, 0);
1844#else
1845    ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
1846#endif
1847
1848    zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
1849            &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
1850
1851    if (EG(exception)) {
1852        zval_ptr_dtor(&iter);
1853        RETURN_FALSE;
1854    }
1855
1856    MAKE_STD_ZVAL(iteriter);
1857
1858    if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
1859        zval_ptr_dtor(&iter);
1860        zval_ptr_dtor(&iteriter);
1861        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
1862        RETURN_FALSE;
1863    }
1864
1865    zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
1866            &spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
1867
1868    if (EG(exception)) {
1869        zval_ptr_dtor(&iter);
1870        zval_ptr_dtor(&iteriter);
1871        RETURN_FALSE;
1872    }
1873
1874    zval_ptr_dtor(&iter);
1875
1876    if (regex_len > 0) {
1877        apply_reg = 1;
1878        MAKE_STD_ZVAL(regexiter);
1879
1880        if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
1881            zval_ptr_dtor(&iteriter);
1882            zval_dtor(regexiter);
1883            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
1884            RETURN_FALSE;
1885        }
1886
1887        INIT_PZVAL(&arg2);
1888        ZVAL_STRINGL(&arg2, regex, regex_len, 0);
1889
1890        zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator,
1891            &spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
1892    }
1893
1894    array_init(return_value);
1895
1896    pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
1897    pass.p = phar_obj;
1898    pass.b = dir;
1899    pass.l = dir_len;
1900    pass.count = 0;
1901    pass.ret = return_value;
1902    pass.fp = php_stream_fopen_tmpfile();
1903    if (pass.fp == NULL) {
1904        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
1905        return;
1906    }
1907
1908    if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
1909        zval_ptr_dtor(&iteriter);
1910        if (apply_reg) {
1911            zval_ptr_dtor(&regexiter);
1912        }
1913        php_stream_close(pass.fp);
1914        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
1915        return;
1916    }
1917
1918    if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
1919        zval_ptr_dtor(&iteriter);
1920
1921        if (apply_reg) {
1922            zval_ptr_dtor(&regexiter);
1923        }
1924
1925        phar_obj->arc.archive->ufp = pass.fp;
1926        phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
1927
1928        if (error) {
1929            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
1930            efree(error);
1931        }
1932
1933    } else {
1934        zval_ptr_dtor(&iteriter);
1935        if (apply_reg) {
1936            zval_ptr_dtor(&regexiter);
1937        }
1938        php_stream_close(pass.fp);
1939    }
1940}
1941/* }}} */
1942
1943/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
1944 * Construct a phar archive from an iterator.  The iterator must return a series of strings
1945 * that are full paths to files that should be added to the phar.  The iterator key should
1946 * be the path that the file will have within the phar archive.
1947 *
1948 * If base directory is specified, then the key will be ignored, and instead the portion of
1949 * the current value minus the base directory will be used
1950 *
1951 * Returned is an array mapping phar index to actual file added
1952 */
1953PHP_METHOD(Phar, buildFromIterator)
1954{
1955    zval *obj;
1956    char *error;
1957    uint base_len = 0;
1958    char *base = NULL;
1959    struct _phar_t pass;
1960
1961    PHAR_ARCHIVE_OBJECT();
1962
1963    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
1964        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
1965            "Cannot write out phar archive, phar is read-only");
1966        return;
1967    }
1968
1969    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
1970        RETURN_FALSE;
1971    }
1972
1973    if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
1974        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
1975        return;
1976    }
1977
1978    array_init(return_value);
1979
1980    pass.c = Z_OBJCE_P(obj);
1981    pass.p = phar_obj;
1982    pass.b = base;
1983    pass.l = base_len;
1984    pass.ret = return_value;
1985    pass.count = 0;
1986    pass.fp = php_stream_fopen_tmpfile();
1987    if (pass.fp == NULL) {
1988        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname);
1989        return;
1990    }
1991
1992    if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
1993        phar_obj->arc.archive->ufp = pass.fp;
1994        phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
1995        if (error) {
1996            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
1997            efree(error);
1998        }
1999    } else {
2000        php_stream_close(pass.fp);
2001    }
2002}
2003/* }}} */
2004
2005/* {{{ proto int Phar::count()
2006 * Returns the number of entries in the Phar archive
2007 */
2008PHP_METHOD(Phar, count)
2009{
2010    PHAR_ARCHIVE_OBJECT();
2011
2012    if (zend_parse_parameters_none() == FAILURE) {
2013        return;
2014    }
2015
2016    RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
2017}
2018/* }}} */
2019
2020/* {{{ proto bool Phar::isFileFormat(int format)
2021 * Returns true if the phar archive is based on the tar/zip/phar file format depending
2022 * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
2023 */
2024PHP_METHOD(Phar, isFileFormat)
2025{
2026    long type;
2027    PHAR_ARCHIVE_OBJECT();
2028
2029    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) {
2030        RETURN_FALSE;
2031    }
2032
2033    switch (type) {
2034        case PHAR_FORMAT_TAR:
2035            RETURN_BOOL(phar_obj->arc.archive->is_tar);
2036        case PHAR_FORMAT_ZIP:
2037            RETURN_BOOL(phar_obj->arc.archive->is_zip);
2038        case PHAR_FORMAT_PHAR:
2039            RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip);
2040        default:
2041            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified");
2042    }
2043}
2044/* }}} */
2045
2046static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
2047{
2048    char *error;
2049    off_t offset;
2050    phar_entry_info *link;
2051
2052    if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) {
2053        if (error) {
2054            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2055                "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
2056            efree(error);
2057        } else {
2058            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2059                "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
2060        }
2061        return FAILURE;
2062    }
2063
2064    /* copy old contents in entirety */
2065    phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC);
2066    offset = php_stream_tell(fp);
2067    link = phar_get_link_source(entry TSRMLS_CC);
2068
2069    if (!link) {
2070        link = entry;
2071    }
2072
2073    if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) {
2074        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2075            "Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
2076        return FAILURE;
2077    }
2078
2079    if (entry->fp_type == PHAR_MOD) {
2080        /* save for potential restore on error */
2081        entry->cfp = entry->fp;
2082        entry->fp = NULL;
2083    }
2084
2085    /* set new location of file contents */
2086    entry->fp_type = PHAR_FP;
2087    entry->offset = offset;
2088    return SUCCESS;
2089}
2090/* }}} */
2091
2092static zval *phar_rename_archive(phar_archive_data **sphar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
2093{
2094    const char *oldname = NULL;
2095    phar_archive_data *phar = *sphar;
2096    char *oldpath = NULL;
2097    char *basename = NULL, *basepath = NULL;
2098    char *newname = NULL, *newpath = NULL;
2099    zval *ret, arg1;
2100    zend_class_entry *ce;
2101    char *error;
2102    const char *pcr_error;
2103    int ext_len = ext ? strlen(ext) : 0;
2104    int oldname_len;
2105    phar_archive_data **pphar = NULL;
2106    php_stream_statbuf ssb;
2107
2108    if (!ext) {
2109        if (phar->is_zip) {
2110
2111            if (phar->is_data) {
2112                ext = "zip";
2113            } else {
2114                ext = "phar.zip";
2115            }
2116
2117        } else if (phar->is_tar) {
2118
2119            switch (phar->flags) {
2120                case PHAR_FILE_COMPRESSED_GZ:
2121                    if (phar->is_data) {
2122                        ext = "tar.gz";
2123                    } else {
2124                        ext = "phar.tar.gz";
2125                    }
2126                    break;
2127                case PHAR_FILE_COMPRESSED_BZ2:
2128                    if (phar->is_data) {
2129                        ext = "tar.bz2";
2130                    } else {
2131                        ext = "phar.tar.bz2";
2132                    }
2133                    break;
2134                default:
2135                    if (phar->is_data) {
2136                        ext = "tar";
2137                    } else {
2138                        ext = "phar.tar";
2139                    }
2140            }
2141        } else {
2142
2143            switch (phar->flags) {
2144                case PHAR_FILE_COMPRESSED_GZ:
2145                    ext = "phar.gz";
2146                    break;
2147                case PHAR_FILE_COMPRESSED_BZ2:
2148                    ext = "phar.bz2";
2149                    break;
2150                default:
2151                    ext = "phar";
2152            }
2153        }
2154    } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
2155
2156        if (phar->is_data) {
2157            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
2158        } else {
2159            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
2160        }
2161        return NULL;
2162    }
2163
2164    if (ext[0] == '.') {
2165        ++ext;
2166    }
2167
2168    oldpath = estrndup(phar->fname, phar->fname_len);
2169    oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
2170    ++oldname;
2171    oldname_len = strlen(oldname);
2172
2173    basename = estrndup(oldname, oldname_len);
2174    spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
2175    efree(basename);
2176
2177
2178
2179    basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
2180    phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
2181    phar->fname = newpath;
2182    phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
2183    efree(basepath);
2184    efree(newname);
2185
2186    if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
2187        efree(oldpath);
2188        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
2189        return NULL;
2190    }
2191
2192    if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
2193        if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
2194            if (!zend_hash_num_elements(&phar->manifest)) {
2195                (*pphar)->is_tar = phar->is_tar;
2196                (*pphar)->is_zip = phar->is_zip;
2197                (*pphar)->is_data = phar->is_data;
2198                (*pphar)->flags = phar->flags;
2199                (*pphar)->fp = phar->fp;
2200                phar->fp = NULL;
2201                phar_destroy_phar_data(phar TSRMLS_CC);
2202                phar = *pphar;
2203                *sphar = NULL;
2204                phar->refcount++;
2205                newpath = oldpath;
2206                goto its_ok;
2207            }
2208        }
2209
2210        efree(oldpath);
2211        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
2212        return NULL;
2213    }
2214its_ok:
2215    if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
2216        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
2217        efree(oldpath);
2218        return NULL;
2219    }
2220    if (!phar->is_data) {
2221        if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
2222            efree(oldpath);
2223            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
2224            return NULL;
2225        }
2226
2227        if (phar->alias) {
2228            if (phar->is_temporary_alias) {
2229                phar->alias = NULL;
2230                phar->alias_len = 0;
2231            } else {
2232                phar->alias = estrndup(newpath, strlen(newpath));
2233                phar->alias_len = strlen(newpath);
2234                phar->is_temporary_alias = 1;
2235                zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
2236            }
2237        }
2238
2239    } else {
2240
2241        if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
2242            efree(oldpath);
2243            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
2244            return NULL;
2245        }
2246
2247        phar->alias = NULL;
2248        phar->alias_len = 0;
2249    }
2250
2251    if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
2252        efree(oldpath);
2253        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
2254        return NULL;
2255    }
2256
2257    phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
2258
2259    if (error) {
2260        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
2261        efree(error);
2262        efree(oldpath);
2263        return NULL;
2264    }
2265
2266    efree(oldpath);
2267
2268    if (phar->is_data) {
2269        ce = phar_ce_data;
2270    } else {
2271        ce = phar_ce_archive;
2272    }
2273
2274    MAKE_STD_ZVAL(ret);
2275
2276    if (SUCCESS != object_init_ex(ret, ce)) {
2277        zval_dtor(ret);
2278        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
2279        return NULL;
2280    }
2281
2282    INIT_PZVAL(&arg1);
2283    ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
2284
2285    zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
2286    return ret;
2287}
2288/* }}} */
2289
2290static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */
2291{
2292    phar_archive_data *phar;
2293    phar_entry_info *entry, newentry;
2294    zval *ret;
2295
2296    /* invalidate phar cache */
2297    PHAR_G(last_phar) = NULL;
2298    PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
2299
2300    phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
2301    /* set whole-archive compression and type from parameter */
2302    phar->flags = flags;
2303    phar->is_data = source->is_data;
2304
2305    switch (convert) {
2306        case PHAR_FORMAT_TAR:
2307            phar->is_tar = 1;
2308            break;
2309        case PHAR_FORMAT_ZIP:
2310            phar->is_zip = 1;
2311            break;
2312        default:
2313            phar->is_data = 0;
2314            break;
2315    }
2316
2317    zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
2318        zend_get_hash_value, destroy_phar_manifest_entry, 0);
2319    zend_hash_init(&phar->mounted_dirs, sizeof(char *),
2320        zend_get_hash_value, NULL, 0);
2321    zend_hash_init(&phar->virtual_dirs, sizeof(char *),
2322        zend_get_hash_value, NULL, 0);
2323
2324    phar->fp = php_stream_fopen_tmpfile();
2325    if (phar->fp == NULL) {
2326        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file");
2327        return NULL;
2328    }
2329    phar->fname = source->fname;
2330    phar->fname_len = source->fname_len;
2331    phar->is_temporary_alias = source->is_temporary_alias;
2332    phar->alias = source->alias;
2333
2334    if (source->metadata) {
2335        zval *t;
2336
2337        t = source->metadata;
2338        ALLOC_ZVAL(phar->metadata);
2339        *phar->metadata = *t;
2340        zval_copy_ctor(phar->metadata);
2341#if PHP_VERSION_ID < 50300
2342        phar->metadata->refcount = 1;
2343#else
2344        Z_SET_REFCOUNT_P(phar->metadata, 1);
2345#endif
2346
2347        phar->metadata_len = 0;
2348    }
2349
2350    /* first copy each file's uncompressed contents to a temporary file and set per-file flags */
2351    for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) {
2352
2353        if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) {
2354            zend_hash_destroy(&(phar->manifest));
2355            php_stream_close(phar->fp);
2356            efree(phar);
2357            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2358                "Cannot convert phar archive \"%s\"", source->fname);
2359            return NULL;
2360        }
2361
2362        newentry = *entry;
2363
2364        if (newentry.link) {
2365            newentry.link = estrdup(newentry.link);
2366            goto no_copy;
2367        }
2368
2369        if (newentry.tmp) {
2370            newentry.tmp = estrdup(newentry.tmp);
2371            goto no_copy;
2372        }
2373
2374        newentry.metadata_str.c = 0;
2375
2376        if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) {
2377            zend_hash_destroy(&(phar->manifest));
2378            php_stream_close(phar->fp);
2379            efree(phar);
2380            /* exception already thrown */
2381            return NULL;
2382        }
2383no_copy:
2384        newentry.filename = estrndup(newentry.filename, newentry.filename_len);
2385
2386        if (newentry.metadata) {
2387            zval *t;
2388
2389            t = newentry.metadata;
2390            ALLOC_ZVAL(newentry.metadata);
2391            *newentry.metadata = *t;
2392            zval_copy_ctor(newentry.metadata);
2393#if PHP_VERSION_ID < 50300
2394            newentry.metadata->refcount = 1;
2395#else
2396            Z_SET_REFCOUNT_P(newentry.metadata, 1);
2397#endif
2398
2399            newentry.metadata_str.c = NULL;
2400            newentry.metadata_str.len = 0;
2401        }
2402
2403        newentry.is_zip = phar->is_zip;
2404        newentry.is_tar = phar->is_tar;
2405
2406        if (newentry.is_tar) {
2407            newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
2408        }
2409
2410        newentry.is_modified = 1;
2411        newentry.phar = phar;
2412        newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
2413        phar_set_inode(&newentry TSRMLS_CC);
2414        zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
2415        phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC);
2416    }
2417
2418    if ((ret = phar_rename_archive(&phar, ext, 0 TSRMLS_CC))) {
2419        return ret;
2420    } else {
2421        if(phar != NULL) {
2422            zend_hash_destroy(&(phar->manifest));
2423            zend_hash_destroy(&(phar->mounted_dirs));
2424            zend_hash_destroy(&(phar->virtual_dirs));
2425            if (phar->fp) {
2426                php_stream_close(phar->fp);
2427            }
2428            efree(phar->fname);
2429            efree(phar);
2430        }
2431        return NULL;
2432    }
2433}
2434/* }}} */
2435
2436/* {{{ proto object Phar::convertToExecutable([int format[, int compression [, string file_ext]]])
2437 * Convert a phar.tar or phar.zip archive to the phar file format. The
2438 * optional parameter allows the user to determine the new
2439 * filename extension (default is phar).
2440 */
2441PHP_METHOD(Phar, convertToExecutable)
2442{
2443    char *ext = NULL;
2444    int is_data, ext_len = 0;
2445    php_uint32 flags;
2446    zval *ret;
2447    /* a number that is not 0, 1 or 2 (Which is also Greg's birthday, so there) */
2448    long format = 9021976, method = 9021976;
2449    PHAR_ARCHIVE_OBJECT();
2450
2451    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &format, &method, &ext, &ext_len) == FAILURE) {
2452        return;
2453    }
2454
2455    if (PHAR_G(readonly)) {
2456        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2457            "Cannot write out executable phar archive, phar is read-only");
2458        return;
2459    }
2460
2461    switch (format) {
2462        case 9021976:
2463        case PHAR_FORMAT_SAME: /* null is converted to 0 */
2464            /* by default, use the existing format */
2465            if (phar_obj->arc.archive->is_tar) {
2466                format = PHAR_FORMAT_TAR;
2467            } else if (phar_obj->arc.archive->is_zip) {
2468                format = PHAR_FORMAT_ZIP;
2469            } else {
2470                format = PHAR_FORMAT_PHAR;
2471            }
2472            break;
2473        case PHAR_FORMAT_PHAR:
2474        case PHAR_FORMAT_TAR:
2475        case PHAR_FORMAT_ZIP:
2476            break;
2477        default:
2478            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2479                "Unknown file format specified, please pass one of Phar::PHAR, Phar::TAR or Phar::ZIP");
2480            return;
2481    }
2482
2483    switch (method) {
2484        case 9021976:
2485            flags = phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSION_MASK;
2486            break;
2487        case 0:
2488            flags = PHAR_FILE_COMPRESSED_NONE;
2489            break;
2490        case PHAR_ENT_COMPRESSED_GZ:
2491            if (format == PHAR_FORMAT_ZIP) {
2492                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2493                    "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression");
2494                return;
2495            }
2496
2497            if (!PHAR_G(has_zlib)) {
2498                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2499                    "Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
2500                return;
2501            }
2502
2503            flags = PHAR_FILE_COMPRESSED_GZ;
2504            break;
2505        case PHAR_ENT_COMPRESSED_BZ2:
2506            if (format == PHAR_FORMAT_ZIP) {
2507                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2508                    "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression");
2509                return;
2510            }
2511
2512            if (!PHAR_G(has_bz2)) {
2513                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2514                    "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
2515                return;
2516            }
2517
2518            flags = PHAR_FILE_COMPRESSED_BZ2;
2519            break;
2520        default:
2521            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2522                "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
2523            return;
2524    }
2525
2526    is_data = phar_obj->arc.archive->is_data;
2527    phar_obj->arc.archive->is_data = 0;
2528    ret = phar_convert_to_other(phar_obj->arc.archive, format, ext, flags TSRMLS_CC);
2529    phar_obj->arc.archive->is_data = is_data;
2530
2531    if (ret) {
2532        RETURN_ZVAL(ret, 1, 1);
2533    } else {
2534        RETURN_NULL();
2535    }
2536}
2537/* }}} */
2538
2539/* {{{ proto object Phar::convertToData([int format[, int compression [, string file_ext]]])
2540 * Convert an archive to a non-executable .tar or .zip.
2541 * The optional parameter allows the user to determine the new
2542 * filename extension (default is .zip or .tar).
2543 */
2544PHP_METHOD(Phar, convertToData)
2545{
2546    char *ext = NULL;
2547    int is_data, ext_len = 0;
2548    php_uint32 flags;
2549    zval *ret;
2550    /* a number that is not 0, 1 or 2 (Which is also Greg's birthday so there) */
2551    long format = 9021976, method = 9021976;
2552    PHAR_ARCHIVE_OBJECT();
2553
2554    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &format, &method, &ext, &ext_len) == FAILURE) {
2555        return;
2556    }
2557
2558    switch (format) {
2559        case 9021976:
2560        case PHAR_FORMAT_SAME: /* null is converted to 0 */
2561            /* by default, use the existing format */
2562            if (phar_obj->arc.archive->is_tar) {
2563                format = PHAR_FORMAT_TAR;
2564            } else if (phar_obj->arc.archive->is_zip) {
2565                format = PHAR_FORMAT_ZIP;
2566            } else {
2567                zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2568                    "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP");
2569                return;
2570            }
2571            break;
2572        case PHAR_FORMAT_PHAR:
2573            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2574                "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP");
2575            return;
2576        case PHAR_FORMAT_TAR:
2577        case PHAR_FORMAT_ZIP:
2578            break;
2579        default:
2580            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2581                "Unknown file format specified, please pass one of Phar::TAR or Phar::ZIP");
2582            return;
2583    }
2584
2585    switch (method) {
2586        case 9021976:
2587            flags = phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSION_MASK;
2588            break;
2589        case 0:
2590            flags = PHAR_FILE_COMPRESSED_NONE;
2591            break;
2592        case PHAR_ENT_COMPRESSED_GZ:
2593            if (format == PHAR_FORMAT_ZIP) {
2594                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2595                    "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression");
2596                return;
2597            }
2598
2599            if (!PHAR_G(has_zlib)) {
2600                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2601                    "Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
2602                return;
2603            }
2604
2605            flags = PHAR_FILE_COMPRESSED_GZ;
2606            break;
2607        case PHAR_ENT_COMPRESSED_BZ2:
2608            if (format == PHAR_FORMAT_ZIP) {
2609                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2610                    "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression");
2611                return;
2612            }
2613
2614            if (!PHAR_G(has_bz2)) {
2615                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2616                    "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
2617                return;
2618            }
2619
2620            flags = PHAR_FILE_COMPRESSED_BZ2;
2621            break;
2622        default:
2623            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
2624                "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
2625            return;
2626    }
2627
2628    is_data = phar_obj->arc.archive->is_data;
2629    phar_obj->arc.archive->is_data = 1;
2630    ret = phar_convert_to_other(phar_obj->arc.archive, format, ext, flags TSRMLS_CC);
2631    phar_obj->arc.archive->is_data = is_data;
2632
2633    if (ret) {
2634        RETURN_ZVAL(ret, 1, 1);
2635    } else {
2636        RETURN_NULL();
2637    }
2638}
2639/* }}} */
2640
2641/* {{{ proto int|false Phar::isCompressed()
2642 * Returns Phar::GZ or PHAR::BZ2 if the entire archive is compressed
2643 * (.tar.gz/tar.bz2 and so on), or FALSE otherwise.
2644 */
2645PHP_METHOD(Phar, isCompressed)
2646{
2647    PHAR_ARCHIVE_OBJECT();
2648
2649    if (zend_parse_parameters_none() == FAILURE) {
2650        return;
2651    }
2652
2653    if (phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSED_GZ) {
2654        RETURN_LONG(PHAR_ENT_COMPRESSED_GZ);
2655    }
2656
2657    if (phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSED_BZ2) {
2658        RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2);
2659    }
2660
2661    RETURN_FALSE;
2662}
2663/* }}} */
2664
2665/* {{{ proto bool Phar::isWritable()
2666 * Returns true if phar.readonly=0 or phar is a PharData AND the actual file is writable.
2667 */
2668PHP_METHOD(Phar, isWritable)
2669{
2670    php_stream_statbuf ssb;
2671    PHAR_ARCHIVE_OBJECT();
2672
2673    if (zend_parse_parameters_none() == FAILURE) {
2674        return;
2675    }
2676
2677    if (!phar_obj->arc.archive->is_writeable) {
2678        RETURN_FALSE;
2679    }
2680
2681    if (SUCCESS != php_stream_stat_path(phar_obj->arc.archive->fname, &ssb)) {
2682        if (phar_obj->arc.archive->is_brandnew) {
2683            /* assume it works if the file doesn't exist yet */
2684            RETURN_TRUE;
2685        }
2686        RETURN_FALSE;
2687    }
2688
2689    RETURN_BOOL((ssb.sb.st_mode & (S_IWOTH | S_IWGRP | S_IWUSR)) != 0);
2690}
2691/* }}} */
2692
2693/* {{{ proto bool Phar::delete(string entry)
2694 * Deletes a named file within the archive.
2695 */
2696PHP_METHOD(Phar, delete)
2697{
2698    char *fname;
2699    int fname_len;
2700    char *error;
2701    phar_entry_info *entry;
2702    PHAR_ARCHIVE_OBJECT();
2703
2704    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
2705        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2706            "Cannot write out phar archive, phar is read-only");
2707        return;
2708    }
2709
2710    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
2711        RETURN_FALSE;
2712    }
2713
2714    if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
2715        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
2716        return;
2717    }
2718    if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) {
2719        if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) {
2720            if (entry->is_deleted) {
2721                /* entry is deleted, but has not been flushed to disk yet */
2722                RETURN_TRUE;
2723            } else {
2724                entry->is_deleted = 1;
2725                entry->is_modified = 1;
2726                phar_obj->arc.archive->is_modified = 1;
2727            }
2728        }
2729    } else {
2730        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be deleted", fname);
2731        RETURN_FALSE;
2732    }
2733
2734    phar_flush(phar_obj->arc.archive, NULL, 0, 0, &error TSRMLS_CC);
2735    if (error) {
2736        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
2737        efree(error);
2738    }
2739
2740    RETURN_TRUE;
2741}
2742/* }}} */
2743
2744/* {{{ proto int Phar::getAlias()
2745 * Returns the alias for the Phar or NULL.
2746 */
2747PHP_METHOD(Phar, getAlias)
2748{
2749    PHAR_ARCHIVE_OBJECT();
2750
2751    if (zend_parse_parameters_none() == FAILURE) {
2752        return;
2753    }
2754
2755    if (phar_obj->arc.archive->alias && phar_obj->arc.archive->alias != phar_obj->arc.archive->fname) {
2756        RETURN_STRINGL(phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len, 1);
2757    }
2758}
2759/* }}} */
2760
2761/* {{{ proto int Phar::getPath()
2762 * Returns the real path to the phar archive on disk
2763 */
2764PHP_METHOD(Phar, getPath)
2765{
2766    PHAR_ARCHIVE_OBJECT();
2767
2768    if (zend_parse_parameters_none() == FAILURE) {
2769        return;
2770    }
2771
2772    RETURN_STRINGL(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, 1);
2773}
2774/* }}} */
2775
2776/* {{{ proto bool Phar::setAlias(string alias)
2777 * Sets the alias for a Phar archive. The default value is the full path
2778 * to the archive.
2779 */
2780PHP_METHOD(Phar, setAlias)
2781{
2782    char *alias, *error, *oldalias;
2783    phar_archive_data **fd_ptr;
2784    int alias_len, oldalias_len, old_temp, readd = 0;
2785
2786    PHAR_ARCHIVE_OBJECT();
2787
2788    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
2789        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2790            "Cannot write out phar archive, phar is read-only");
2791        RETURN_FALSE;
2792    }
2793
2794    /* invalidate phar cache */
2795    PHAR_G(last_phar) = NULL;
2796    PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
2797
2798    if (phar_obj->arc.archive->is_data) {
2799        if (phar_obj->arc.archive->is_tar) {
2800            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2801                "A Phar alias cannot be set in a plain tar archive");
2802        } else {
2803            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2804                "A Phar alias cannot be set in a plain zip archive");
2805        }
2806        RETURN_FALSE;
2807    }
2808
2809    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &alias, &alias_len) == SUCCESS) {
2810        if (alias_len == phar_obj->arc.archive->alias_len && memcmp(phar_obj->arc.archive->alias, alias, alias_len) == 0) {
2811            RETURN_TRUE;
2812        }
2813        if (alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void**)&fd_ptr)) {
2814            spprintf(&error, 0, "alias \"%s\" is already used for archive \"%s\" and cannot be used for other archives", alias, (*fd_ptr)->fname);
2815            if (SUCCESS == phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
2816                efree(error);
2817                goto valid_alias;
2818            }
2819            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
2820            efree(error);
2821            RETURN_FALSE;
2822        }
2823        if (!phar_validate_alias(alias, alias_len)) {
2824            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2825                "Invalid alias \"%s\" specified for phar \"%s\"", alias, phar_obj->arc.archive->fname);
2826            RETURN_FALSE;
2827        }
2828valid_alias:
2829        if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
2830            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
2831            return;
2832        }
2833        if (phar_obj->arc.archive->alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len, (void**)&fd_ptr)) {
2834            zend_hash_del(&(PHAR_GLOBALS->phar_alias_map), phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len);
2835            readd = 1;
2836        }
2837
2838        oldalias = phar_obj->arc.archive->alias;
2839        oldalias_len = phar_obj->arc.archive->alias_len;
2840        old_temp = phar_obj->arc.archive->is_temporary_alias;
2841
2842        if (alias_len) {
2843            phar_obj->arc.archive->alias = estrndup(alias, alias_len);
2844        } else {
2845            phar_obj->arc.archive->alias = NULL;
2846        }
2847
2848        phar_obj->arc.archive->alias_len = alias_len;
2849        phar_obj->arc.archive->is_temporary_alias = 0;
2850        phar_flush(phar_obj->arc.archive, NULL, 0, 0, &error TSRMLS_CC);
2851
2852        if (error) {
2853            phar_obj->arc.archive->alias = oldalias;
2854            phar_obj->arc.archive->alias_len = oldalias_len;
2855            phar_obj->arc.archive->is_temporary_alias = old_temp;
2856            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
2857            if (readd) {
2858                zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), oldalias, oldalias_len, (void*)&(phar_obj->arc.archive), sizeof(phar_archive_data*), NULL);
2859            }
2860            efree(error);
2861            RETURN_FALSE;
2862        }
2863
2864        zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&(phar_obj->arc.archive), sizeof(phar_archive_data*), NULL);
2865
2866        if (oldalias) {
2867            efree(oldalias);
2868        }
2869
2870        RETURN_TRUE;
2871    }
2872
2873    RETURN_FALSE;
2874}
2875/* }}} */
2876
2877/* {{{ proto string Phar::getVersion()
2878 * Return version info of Phar archive
2879 */
2880PHP_METHOD(Phar, getVersion)
2881{
2882    PHAR_ARCHIVE_OBJECT();
2883
2884    if (zend_parse_parameters_none() == FAILURE) {
2885        return;
2886    }
2887
2888    RETURN_STRING(phar_obj->arc.archive->version, 1);
2889}
2890/* }}} */
2891
2892/* {{{ proto void Phar::startBuffering()
2893 * Do not flush a writeable phar (save its contents) until explicitly requested
2894 */
2895PHP_METHOD(Phar, startBuffering)
2896{
2897    PHAR_ARCHIVE_OBJECT();
2898
2899    if (zend_parse_parameters_none() == FAILURE) {
2900        return;
2901    }
2902
2903    phar_obj->arc.archive->donotflush = 1;
2904}
2905/* }}} */
2906
2907/* {{{ proto bool Phar::isBuffering()
2908 * Returns whether write operations are flushing to disk immediately.
2909 */
2910PHP_METHOD(Phar, isBuffering)
2911{
2912    PHAR_ARCHIVE_OBJECT();
2913
2914    if (zend_parse_parameters_none() == FAILURE) {
2915        return;
2916    }
2917
2918    RETURN_BOOL(phar_obj->arc.archive->donotflush);
2919}
2920/* }}} */
2921
2922/* {{{ proto bool Phar::stopBuffering()
2923 * Saves the contents of a modified archive to disk.
2924 */
2925PHP_METHOD(Phar, stopBuffering)
2926{
2927    char *error;
2928
2929    PHAR_ARCHIVE_OBJECT();
2930
2931    if (zend_parse_parameters_none() == FAILURE) {
2932        return;
2933    }
2934
2935    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
2936        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2937            "Cannot write out phar archive, phar is read-only");
2938        return;
2939    }
2940
2941    phar_obj->arc.archive->donotflush = 0;
2942    phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
2943
2944    if (error) {
2945        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
2946        efree(error);
2947    }
2948}
2949/* }}} */
2950
2951/* {{{ proto bool Phar::setStub(string|stream stub [, int len])
2952 * Change the stub in a phar, phar.tar or phar.zip archive to something other
2953 * than the default. The stub *must* end with a call to __HALT_COMPILER().
2954 */
2955PHP_METHOD(Phar, setStub)
2956{
2957    zval *zstub;
2958    char *stub, *error;
2959    int stub_len;
2960    long len = -1;
2961    php_stream *stream;
2962    PHAR_ARCHIVE_OBJECT();
2963
2964    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
2965        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2966            "Cannot change stub, phar is read-only");
2967        return;
2968    }
2969
2970    if (phar_obj->arc.archive->is_data) {
2971        if (phar_obj->arc.archive->is_tar) {
2972            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2973                "A Phar stub cannot be set in a plain tar archive");
2974        } else {
2975            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
2976                "A Phar stub cannot be set in a plain zip archive");
2977        }
2978        return;
2979    }
2980
2981    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &zstub, &len) == SUCCESS) {
2982        if ((php_stream_from_zval_no_verify(stream, &zstub)) != NULL) {
2983            if (len > 0) {
2984                len = -len;
2985            } else {
2986                len = -1;
2987            }
2988            if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
2989                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
2990                return;
2991            }
2992            phar_flush(phar_obj->arc.archive, (char *) &zstub, len, 0, &error TSRMLS_CC);
2993            if (error) {
2994                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
2995                efree(error);
2996            }
2997            RETURN_TRUE;
2998        } else {
2999            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3000                "Cannot change stub, unable to read from input stream");
3001        }
3002    } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &stub, &stub_len) == SUCCESS) {
3003        if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3004            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3005            return;
3006        }
3007        phar_flush(phar_obj->arc.archive, stub, stub_len, 0, &error TSRMLS_CC);
3008
3009        if (error) {
3010            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3011            efree(error);
3012        }
3013
3014        RETURN_TRUE;
3015    }
3016
3017    RETURN_FALSE;
3018}
3019/* }}} */
3020
3021/* {{{ proto bool Phar::setDefaultStub([string index[, string webindex]])
3022 * In a pure phar archive, sets a stub that can be used to run the archive
3023 * regardless of whether the phar extension is available. The first parameter
3024 * is the CLI startup filename, which defaults to "index.php". The second
3025 * parameter is the web startup filename and also defaults to "index.php"
3026 * (falling back to CLI behaviour).
3027 * Both parameters are optional.
3028 * In a phar.zip or phar.tar archive, the default stub is used only to
3029 * identify the archive to the extension as a Phar object. This allows the
3030 * extension to treat phar.zip and phar.tar types as honorary phars. Since
3031 * files cannot be loaded via this kind of stub, no parameters are accepted
3032 * when the Phar object is zip- or tar-based.
3033 */
3034PHP_METHOD(Phar, setDefaultStub)
3035{
3036    char *index = NULL, *webindex = NULL, *error = NULL, *stub = NULL;
3037    int index_len = 0, webindex_len = 0, created_stub = 0;
3038    size_t stub_len = 0;
3039    PHAR_ARCHIVE_OBJECT();
3040
3041    if (phar_obj->arc.archive->is_data) {
3042        if (phar_obj->arc.archive->is_tar) {
3043            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3044                "A Phar stub cannot be set in a plain tar archive");
3045        } else {
3046            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3047                "A Phar stub cannot be set in a plain zip archive");
3048        }
3049        return;
3050    }
3051
3052    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
3053        RETURN_FALSE;
3054    }
3055
3056    if (ZEND_NUM_ARGS() > 0 && (phar_obj->arc.archive->is_tar || phar_obj->arc.archive->is_zip)) {
3057        php_error_docref(NULL TSRMLS_CC, E_WARNING, "method accepts no arguments for a tar- or zip-based phar stub, %d given", ZEND_NUM_ARGS());
3058        RETURN_FALSE;
3059    }
3060
3061    if (PHAR_G(readonly)) {
3062        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3063            "Cannot change stub: phar.readonly=1");
3064        RETURN_FALSE;
3065    }
3066
3067    if (!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip) {
3068        stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
3069
3070        if (error) {
3071            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error);
3072            efree(error);
3073            if (stub) {
3074                efree(stub);
3075            }
3076            RETURN_FALSE;
3077        }
3078
3079        created_stub = 1;
3080    }
3081
3082    if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3083        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3084        return;
3085    }
3086    phar_flush(phar_obj->arc.archive, stub, stub_len, 1, &error TSRMLS_CC);
3087
3088    if (created_stub) {
3089        efree(stub);
3090    }
3091
3092    if (error) {
3093        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3094        efree(error);
3095        RETURN_FALSE;
3096    }
3097
3098    RETURN_TRUE;
3099}
3100/* }}} */
3101
3102/* {{{ proto array Phar::setSignatureAlgorithm(int sigtype[, string privatekey])
3103 * Sets the signature algorithm for a phar and applies it. The signature
3104 * algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256,
3105 * Phar::SHA512, or Phar::OPENSSL. Note that zip- based phar archives
3106 * cannot support signatures.
3107 */
3108PHP_METHOD(Phar, setSignatureAlgorithm)
3109{
3110    long algo;
3111    char *error, *key = NULL;
3112    int key_len = 0;
3113
3114    PHAR_ARCHIVE_OBJECT();
3115
3116    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3117        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3118            "Cannot set signature algorithm, phar is read-only");
3119        return;
3120    }
3121
3122    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "l|s", &algo, &key, &key_len) != SUCCESS) {
3123        return;
3124    }
3125
3126    switch (algo) {
3127        case PHAR_SIG_SHA256:
3128        case PHAR_SIG_SHA512:
3129#ifndef PHAR_HASH_OK
3130            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3131                "SHA-256 and SHA-512 signatures are only supported if the hash extension is enabled and built non-shared");
3132            return;
3133#endif
3134        case PHAR_SIG_MD5:
3135        case PHAR_SIG_SHA1:
3136        case PHAR_SIG_OPENSSL:
3137            if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3138                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3139                return;
3140            }
3141            phar_obj->arc.archive->sig_flags = algo;
3142            phar_obj->arc.archive->is_modified = 1;
3143            PHAR_G(openssl_privatekey) = key;
3144            PHAR_G(openssl_privatekey_len) = key_len;
3145
3146            phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
3147            if (error) {
3148                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3149                efree(error);
3150            }
3151            break;
3152        default:
3153            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3154                "Unknown signature algorithm specified");
3155    }
3156}
3157/* }}} */
3158
3159/* {{{ proto array|false Phar::getSignature()
3160 * Returns a hash signature, or FALSE if the archive is unsigned.
3161 */
3162PHP_METHOD(Phar, getSignature)
3163{
3164    PHAR_ARCHIVE_OBJECT();
3165
3166    if (zend_parse_parameters_none() == FAILURE) {
3167        return;
3168    }
3169
3170    if (phar_obj->arc.archive->signature) {
3171        char *unknown;
3172        int unknown_len;
3173
3174        array_init(return_value);
3175        add_assoc_stringl(return_value, "hash", phar_obj->arc.archive->signature, phar_obj->arc.archive->sig_len, 1);
3176        switch(phar_obj->arc.archive->sig_flags) {
3177            case PHAR_SIG_MD5:
3178                add_assoc_stringl(return_value, "hash_type", "MD5", 3, 1);
3179                break;
3180            case PHAR_SIG_SHA1:
3181                add_assoc_stringl(return_value, "hash_type", "SHA-1", 5, 1);
3182                break;
3183            case PHAR_SIG_SHA256:
3184                add_assoc_stringl(return_value, "hash_type", "SHA-256", 7, 1);
3185                break;
3186            case PHAR_SIG_SHA512:
3187                add_assoc_stringl(return_value, "hash_type", "SHA-512", 7, 1);
3188                break;
3189            case PHAR_SIG_OPENSSL:
3190                add_assoc_stringl(return_value, "hash_type", "OpenSSL", 7, 1);
3191                break;
3192            default:
3193                unknown_len = spprintf(&unknown, 0, "Unknown (%u)", phar_obj->arc.archive->sig_flags);
3194                add_assoc_stringl(return_value, "hash_type", unknown, unknown_len, 0);
3195                break;
3196        }
3197    } else {
3198        RETURN_FALSE;
3199    }
3200}
3201/* }}} */
3202
3203/* {{{ proto bool Phar::getModified()
3204 * Return whether phar was modified
3205 */
3206PHP_METHOD(Phar, getModified)
3207{
3208    PHAR_ARCHIVE_OBJECT();
3209
3210    if (zend_parse_parameters_none() == FAILURE) {
3211        return;
3212    }
3213
3214    RETURN_BOOL(phar_obj->arc.archive->is_modified);
3215}
3216/* }}} */
3217
3218static int phar_set_compression(void *pDest, void *argument TSRMLS_DC) /* {{{ */
3219{
3220    phar_entry_info *entry = (phar_entry_info *)pDest;
3221    php_uint32 compress = *(php_uint32 *)argument;
3222
3223    if (entry->is_deleted) {
3224        return ZEND_HASH_APPLY_KEEP;
3225    }
3226
3227    entry->old_flags = entry->flags;
3228    entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
3229    entry->flags |= compress;
3230    entry->is_modified = 1;
3231    return ZEND_HASH_APPLY_KEEP;
3232}
3233/* }}} */
3234
3235static int phar_test_compression(void *pDest, void *argument TSRMLS_DC) /* {{{ */
3236{
3237    phar_entry_info *entry = (phar_entry_info *)pDest;
3238
3239    if (entry->is_deleted) {
3240        return ZEND_HASH_APPLY_KEEP;
3241    }
3242
3243    if (!PHAR_G(has_bz2)) {
3244        if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
3245            *(int *) argument = 0;
3246        }
3247    }
3248
3249    if (!PHAR_G(has_zlib)) {
3250        if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
3251            *(int *) argument = 0;
3252        }
3253    }
3254
3255    return ZEND_HASH_APPLY_KEEP;
3256}
3257/* }}} */
3258
3259static void pharobj_set_compression(HashTable *manifest, php_uint32 compress TSRMLS_DC) /* {{{ */
3260{
3261    zend_hash_apply_with_argument(manifest, phar_set_compression, &compress TSRMLS_CC);
3262}
3263/* }}} */
3264
3265static int pharobj_cancompress(HashTable *manifest TSRMLS_DC) /* {{{ */
3266{
3267    int test;
3268
3269    test = 1;
3270    zend_hash_apply_with_argument(manifest, phar_test_compression, &test TSRMLS_CC);
3271    return test;
3272}
3273/* }}} */
3274
3275/* {{{ proto object Phar::compress(int method[, string extension])
3276 * Compress a .tar, or .phar.tar with whole-file compression
3277 * The parameter can be one of Phar::GZ or Phar::BZ2 to specify
3278 * the kind of compression desired
3279 */
3280PHP_METHOD(Phar, compress)
3281{
3282    long method;
3283    char *ext = NULL;
3284    int ext_len = 0;
3285    php_uint32 flags;
3286    zval *ret;
3287    PHAR_ARCHIVE_OBJECT();
3288
3289    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|s", &method, &ext, &ext_len) == FAILURE) {
3290        return;
3291    }
3292
3293    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3294        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3295            "Cannot compress phar archive, phar is read-only");
3296        return;
3297    }
3298
3299    if (phar_obj->arc.archive->is_zip) {
3300        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3301            "Cannot compress zip-based archives with whole-archive compression");
3302        return;
3303    }
3304
3305    switch (method) {
3306        case 0:
3307            flags = PHAR_FILE_COMPRESSED_NONE;
3308            break;
3309        case PHAR_ENT_COMPRESSED_GZ:
3310            if (!PHAR_G(has_zlib)) {
3311                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3312                    "Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
3313                return;
3314            }
3315            flags = PHAR_FILE_COMPRESSED_GZ;
3316            break;
3317
3318        case PHAR_ENT_COMPRESSED_BZ2:
3319            if (!PHAR_G(has_bz2)) {
3320                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3321                    "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
3322                return;
3323            }
3324            flags = PHAR_FILE_COMPRESSED_BZ2;
3325            break;
3326        default:
3327            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3328                "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
3329            return;
3330    }
3331
3332    if (phar_obj->arc.archive->is_tar) {
3333        ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_TAR, ext, flags TSRMLS_CC);
3334    } else {
3335        ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_PHAR, ext, flags TSRMLS_CC);
3336    }
3337
3338    if (ret) {
3339        RETURN_ZVAL(ret, 1, 1);
3340    } else {
3341        RETURN_NULL();
3342    }
3343}
3344/* }}} */
3345
3346/* {{{ proto object Phar::decompress([string extension])
3347 * Decompress a .tar, or .phar.tar with whole-file compression
3348 */
3349PHP_METHOD(Phar, decompress)
3350{
3351    char *ext = NULL;
3352    int ext_len = 0;
3353    zval *ret;
3354    PHAR_ARCHIVE_OBJECT();
3355
3356    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &ext, &ext_len) == FAILURE) {
3357        return;
3358    }
3359
3360    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3361        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3362            "Cannot decompress phar archive, phar is read-only");
3363        return;
3364    }
3365
3366    if (phar_obj->arc.archive->is_zip) {
3367        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3368            "Cannot decompress zip-based archives with whole-archive compression");
3369        return;
3370    }
3371
3372    if (phar_obj->arc.archive->is_tar) {
3373        ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_TAR, ext, PHAR_FILE_COMPRESSED_NONE TSRMLS_CC);
3374    } else {
3375        ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_PHAR, ext, PHAR_FILE_COMPRESSED_NONE TSRMLS_CC);
3376    }
3377
3378    if (ret) {
3379        RETURN_ZVAL(ret, 1, 1);
3380    } else {
3381        RETURN_NULL();
3382    }
3383}
3384/* }}} */
3385
3386/* {{{ proto object Phar::compressFiles(int method)
3387 * Compress all files within a phar or zip archive using the specified compression
3388 * The parameter can be one of Phar::GZ or Phar::BZ2 to specify
3389 * the kind of compression desired
3390 */
3391PHP_METHOD(Phar, compressFiles)
3392{
3393    char *error;
3394    php_uint32 flags;
3395    long method;
3396    PHAR_ARCHIVE_OBJECT();
3397
3398    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) {
3399        return;
3400    }
3401
3402    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3403        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3404            "Phar is readonly, cannot change compression");
3405        return;
3406    }
3407
3408    switch (method) {
3409        case PHAR_ENT_COMPRESSED_GZ:
3410            if (!PHAR_G(has_zlib)) {
3411                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3412                    "Cannot compress files within archive with gzip, enable ext/zlib in php.ini");
3413                return;
3414            }
3415            flags = PHAR_ENT_COMPRESSED_GZ;
3416            break;
3417
3418        case PHAR_ENT_COMPRESSED_BZ2:
3419            if (!PHAR_G(has_bz2)) {
3420                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3421                    "Cannot compress files within archive with bz2, enable ext/bz2 in php.ini");
3422                return;
3423            }
3424            flags = PHAR_ENT_COMPRESSED_BZ2;
3425            break;
3426        default:
3427            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3428                "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
3429            return;
3430    }
3431
3432    if (phar_obj->arc.archive->is_tar) {
3433        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3434            "Cannot compress with Gzip compression, tar archives cannot compress individual files, use compress() to compress the whole archive");
3435        return;
3436    }
3437
3438    if (!pharobj_cancompress(&phar_obj->arc.archive->manifest TSRMLS_CC)) {
3439        if (flags == PHAR_FILE_COMPRESSED_GZ) {
3440            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3441                "Cannot compress all files as Gzip, some are compressed as bzip2 and cannot be decompressed");
3442        } else {
3443            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3444                "Cannot compress all files as Bzip2, some are compressed as gzip and cannot be decompressed");
3445        }
3446        return;
3447    }
3448
3449    if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3450        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3451        return;
3452    }
3453    pharobj_set_compression(&phar_obj->arc.archive->manifest, flags TSRMLS_CC);
3454    phar_obj->arc.archive->is_modified = 1;
3455    phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
3456
3457    if (error) {
3458        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
3459        efree(error);
3460    }
3461}
3462/* }}} */
3463
3464/* {{{ proto bool Phar::decompressFiles()
3465 * decompress every file
3466 */
3467PHP_METHOD(Phar, decompressFiles)
3468{
3469    char *error;
3470    PHAR_ARCHIVE_OBJECT();
3471
3472    if (zend_parse_parameters_none() == FAILURE) {
3473        return;
3474    }
3475
3476    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3477        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3478            "Phar is readonly, cannot change compression");
3479        return;
3480    }
3481
3482    if (!pharobj_cancompress(&phar_obj->arc.archive->manifest TSRMLS_CC)) {
3483        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
3484            "Cannot decompress all files, some are compressed as bzip2 or gzip and cannot be decompressed");
3485        return;
3486    }
3487
3488    if (phar_obj->arc.archive->is_tar) {
3489        RETURN_TRUE;
3490    } else {
3491        if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3492            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3493            return;
3494        }
3495        pharobj_set_compression(&phar_obj->arc.archive->manifest, PHAR_ENT_COMPRESSED_NONE TSRMLS_CC);
3496    }
3497
3498    phar_obj->arc.archive->is_modified = 1;
3499    phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
3500
3501    if (error) {
3502        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
3503        efree(error);
3504    }
3505
3506    RETURN_TRUE;
3507}
3508/* }}} */
3509
3510/* {{{ proto bool Phar::copy(string oldfile, string newfile)
3511 * copy a file internal to the phar archive to another new file within the phar
3512 */
3513PHP_METHOD(Phar, copy)
3514{
3515    char *oldfile, *newfile, *error;
3516    const char *pcr_error;
3517    int oldfile_len, newfile_len;
3518    phar_entry_info *oldentry, newentry = {0}, *temp;
3519
3520    PHAR_ARCHIVE_OBJECT();
3521
3522    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
3523        return;
3524    }
3525
3526    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3527        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3528            "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
3529        RETURN_FALSE;
3530    }
3531
3532    if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
3533        /* can't copy a meta file */
3534        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3535            "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->arc.archive->fname);
3536        RETURN_FALSE;
3537    }
3538
3539    if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
3540        /* can't copy a meta file */
3541        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3542            "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->arc.archive->fname);
3543        RETURN_FALSE;
3544    }
3545
3546    if (!zend_hash_exists(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len) || SUCCESS != zend_hash_find(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len, (void**)&oldentry) || oldentry->is_deleted) {
3547        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3548            "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->arc.archive->fname);
3549        RETURN_FALSE;
3550    }
3551
3552    if (zend_hash_exists(&phar_obj->arc.archive->manifest, newfile, (uint) newfile_len)) {
3553        if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, newfile, (uint) newfile_len, (void**)&temp) || !temp->is_deleted) {
3554            zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3555                "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->arc.archive->fname);
3556            RETURN_FALSE;
3557        }
3558    }
3559
3560    if (phar_path_check(&newfile, &newfile_len, &pcr_error) > pcr_is_ok) {
3561        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
3562                "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->arc.archive->fname);
3563        RETURN_FALSE;
3564    }
3565
3566    if (phar_obj->arc.archive->is_persistent) {
3567        if (FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3568            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3569            return;
3570        }
3571        /* re-populate with copied-on-write entry */
3572        zend_hash_find(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len, (void**)&oldentry);
3573    }
3574
3575    memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
3576
3577    if (newentry.metadata) {
3578        zval *t;
3579
3580        t = newentry.metadata;
3581        ALLOC_ZVAL(newentry.metadata);
3582        *newentry.metadata = *t;
3583        zval_copy_ctor(newentry.metadata);
3584#if PHP_VERSION_ID < 50300
3585        newentry.metadata->refcount = 1;
3586#else
3587        Z_SET_REFCOUNT_P(newentry.metadata, 1);
3588#endif
3589
3590        newentry.metadata_str.c = NULL;
3591        newentry.metadata_str.len = 0;
3592    }
3593
3594    newentry.filename = estrndup(newfile, newfile_len);
3595    newentry.filename_len = newfile_len;
3596    newentry.fp_refcount = 0;
3597
3598    if (oldentry->fp_type != PHAR_FP) {
3599        if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error TSRMLS_CC)) {
3600            efree(newentry.filename);
3601            php_stream_close(newentry.fp);
3602            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3603            efree(error);
3604            return;
3605        }
3606    }
3607
3608    zend_hash_add(&oldentry->phar->manifest, newfile, newfile_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
3609    phar_obj->arc.archive->is_modified = 1;
3610    phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
3611
3612    if (error) {
3613        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3614        efree(error);
3615    }
3616
3617    RETURN_TRUE;
3618}
3619/* }}} */
3620
3621/* {{{ proto int Phar::offsetExists(string entry)
3622 * determines whether a file exists in the phar
3623 */
3624PHP_METHOD(Phar, offsetExists)
3625{
3626    char *fname;
3627    int fname_len;
3628    phar_entry_info *entry;
3629
3630    PHAR_ARCHIVE_OBJECT();
3631
3632    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
3633        return;
3634    }
3635
3636    if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) {
3637        if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) {
3638            if (entry->is_deleted) {
3639                /* entry is deleted, but has not been flushed to disk yet */
3640                RETURN_FALSE;
3641            }
3642        }
3643
3644        if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
3645            /* none of these are real files, so they don't exist */
3646            RETURN_FALSE;
3647        }
3648        RETURN_TRUE;
3649    } else {
3650        if (zend_hash_exists(&phar_obj->arc.archive->virtual_dirs, fname, (uint) fname_len)) {
3651            RETURN_TRUE;
3652        }
3653        RETURN_FALSE;
3654    }
3655}
3656/* }}} */
3657
3658/* {{{ proto int Phar::offsetGet(string entry)
3659 * get a PharFileInfo object for a specific file
3660 */
3661PHP_METHOD(Phar, offsetGet)
3662{
3663    char *fname, *error;
3664    int fname_len;
3665    zval *zfname;
3666    phar_entry_info *entry;
3667    PHAR_ARCHIVE_OBJECT();
3668
3669    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
3670        return;
3671    }
3672
3673    /* security is 0 here so that we can get a better error message than "entry doesn't exist" */
3674    if (!(entry = phar_get_entry_info_dir(phar_obj->arc.archive, fname, fname_len, 1, &error, 0 TSRMLS_CC))) {
3675        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:"");
3676    } else {
3677        if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
3678            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->arc.archive->fname);
3679            return;
3680        }
3681
3682        if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
3683            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->arc.archive->fname);
3684            return;
3685        }
3686
3687        if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
3688            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->arc.archive->fname);
3689            return;
3690        }
3691
3692        if (entry->is_temp_dir) {
3693            efree(entry->filename);
3694            efree(entry);
3695        }
3696
3697        fname_len = spprintf(&fname, 0, "phar://%s/%s", phar_obj->arc.archive->fname, fname);
3698        MAKE_STD_ZVAL(zfname);
3699        ZVAL_STRINGL(zfname, fname, fname_len, 0);
3700        spl_instantiate_arg_ex1(phar_obj->spl.info_class, &return_value, 0, zfname TSRMLS_CC);
3701        zval_ptr_dtor(&zfname);
3702    }
3703}
3704/* }}} */
3705
3706/* {{{ add a file within the phar archive from a string or resource
3707 */
3708static void phar_add_file(phar_archive_data **pphar, char *filename, int filename_len, char *cont_str, int cont_len, zval *zresource TSRMLS_DC)
3709{
3710    char *error;
3711    size_t contents_len;
3712    phar_entry_data *data;
3713    php_stream *contents_file;
3714
3715    if (filename_len >= sizeof(".phar")-1 && !memcmp(filename, ".phar", sizeof(".phar")-1)) {
3716        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot create any files in magic \".phar\" directory", (*pphar)->fname);
3717        return;
3718    }
3719
3720    if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, filename, filename_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
3721        if (error) {
3722            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be created: %s", filename, error);
3723            efree(error);
3724        } else {
3725            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be created", filename);
3726        }
3727        return;
3728    } else {
3729        if (error) {
3730            efree(error);
3731        }
3732
3733        if (!data->internal_file->is_dir) {
3734            if (cont_str) {
3735                contents_len = php_stream_write(data->fp, cont_str, cont_len);
3736                if (contents_len != cont_len) {
3737                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s could not be written to", filename);
3738                    return;
3739                }
3740            } else {
3741                if (!(php_stream_from_zval_no_verify(contents_file, &zresource))) {
3742                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s could not be written to", filename);
3743                    return;
3744                }
3745                phar_stream_copy_to_stream(contents_file, data->fp, PHP_STREAM_COPY_ALL, &contents_len);
3746            }
3747
3748            data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
3749        }
3750
3751        /* check for copy-on-write */
3752        if (pphar[0] != data->phar) {
3753            *pphar = data->phar;
3754        }
3755        phar_entry_delref(data TSRMLS_CC);
3756        phar_flush(*pphar, 0, 0, 0, &error TSRMLS_CC);
3757
3758        if (error) {
3759            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3760            efree(error);
3761        }
3762    }
3763}
3764/* }}} */
3765
3766/* {{{ create a directory within the phar archive
3767 */
3768static void phar_mkdir(phar_archive_data **pphar, char *dirname, int dirname_len TSRMLS_DC)
3769{
3770    char *error;
3771    phar_entry_data *data;
3772
3773    if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, dirname, dirname_len, "w+b", 2, &error, 1 TSRMLS_CC))) {
3774        if (error) {
3775            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Directory %s does not exist and cannot be created: %s", dirname, error);
3776            efree(error);
3777        } else {
3778            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Directory %s does not exist and cannot be created", dirname);
3779        }
3780
3781        return;
3782    } else {
3783        if (error) {
3784            efree(error);
3785        }
3786
3787        /* check for copy on write */
3788        if (data->phar != *pphar) {
3789            *pphar = data->phar;
3790        }
3791        phar_entry_delref(data TSRMLS_CC);
3792        phar_flush(*pphar, 0, 0, 0, &error TSRMLS_CC);
3793
3794        if (error) {
3795            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3796            efree(error);
3797        }
3798    }
3799}
3800/* }}} */
3801
3802/* {{{ proto int Phar::offsetSet(string entry, string value)
3803 * set the contents of an internal file to those of an external file
3804 */
3805PHP_METHOD(Phar, offsetSet)
3806{
3807    char *fname, *cont_str = NULL;
3808    int fname_len, cont_len;
3809    zval *zresource;
3810    PHAR_ARCHIVE_OBJECT();
3811
3812    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3813        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
3814        return;
3815    }
3816
3817    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sr", &fname, &fname_len, &zresource) == FAILURE
3818    && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) {
3819        return;
3820    }
3821
3822    if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
3823        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->arc.archive->fname);
3824        return;
3825    }
3826
3827    if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
3828        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->arc.archive->fname);
3829        return;
3830    }
3831
3832    if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
3833        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->arc.archive->fname);
3834        return;
3835    }
3836
3837    phar_add_file(&(phar_obj->arc.archive), fname, fname_len, cont_str, cont_len, zresource TSRMLS_CC);
3838}
3839/* }}} */
3840
3841/* {{{ proto int Phar::offsetUnset(string entry)
3842 * remove a file from a phar
3843 */
3844PHP_METHOD(Phar, offsetUnset)
3845{
3846    char *fname, *error;
3847    int fname_len;
3848    phar_entry_info *entry;
3849    PHAR_ARCHIVE_OBJECT();
3850
3851    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
3852        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
3853        return;
3854    }
3855
3856    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
3857        return;
3858    }
3859
3860    if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) {
3861        if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) {
3862            if (entry->is_deleted) {
3863                /* entry is deleted, but has not been flushed to disk yet */
3864                return;
3865            }
3866
3867            if (phar_obj->arc.archive->is_persistent) {
3868                if (FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
3869                    zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
3870                    return;
3871                }
3872                /* re-populate entry after copy on write */
3873                zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void **)&entry);
3874            }
3875            entry->is_modified = 0;
3876            entry->is_deleted = 1;
3877            /* we need to "flush" the stream to save the newly deleted file on disk */
3878            phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
3879
3880            if (error) {
3881                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
3882                efree(error);
3883            }
3884
3885            RETURN_TRUE;
3886        }
3887    } else {
3888        RETURN_FALSE;
3889    }
3890}
3891/* }}} */
3892
3893/* {{{ proto string Phar::addEmptyDir(string dirname)
3894 * Adds an empty directory to the phar archive
3895 */
3896PHP_METHOD(Phar, addEmptyDir)
3897{
3898    char *dirname;
3899    int dirname_len;
3900
3901    PHAR_ARCHIVE_OBJECT();
3902
3903    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &dirname, &dirname_len) == FAILURE) {
3904        return;
3905    }
3906
3907    if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) {
3908        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot create a directory in magic \".phar\" directory");
3909        return;
3910    }
3911
3912    phar_mkdir(&phar_obj->arc.archive, dirname, dirname_len TSRMLS_CC);
3913}
3914/* }}} */
3915
3916/* {{{ proto string Phar::addFile(string filename[, string localname])
3917 * Adds a file to the archive using the filename, or the second parameter as the name within the archive
3918 */
3919PHP_METHOD(Phar, addFile)
3920{
3921    char *fname, *localname = NULL;
3922    int fname_len, localname_len = 0;
3923    php_stream *resource;
3924    zval *zresource;
3925
3926    PHAR_ARCHIVE_OBJECT();
3927
3928    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) {
3929        return;
3930    }
3931
3932#if PHP_API_VERSION < 20100412
3933    if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
3934        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname);
3935        return;
3936    }
3937#endif
3938
3939    if (!strstr(fname, "://") && php_check_open_basedir(fname TSRMLS_CC)) {
3940        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname);
3941        return;
3942    }
3943
3944    if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) {
3945        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive", fname);
3946        return;
3947    }
3948
3949    if (localname) {
3950        fname = localname;
3951        fname_len = localname_len;
3952    }
3953
3954    MAKE_STD_ZVAL(zresource);
3955    php_stream_to_zval(resource, zresource);
3956    phar_add_file(&(phar_obj->arc.archive), fname, fname_len, NULL, 0, zresource TSRMLS_CC);
3957    efree(zresource);
3958    php_stream_close(resource);
3959}
3960/* }}} */
3961
3962/* {{{ proto string Phar::addFromString(string localname, string contents)
3963 * Adds a file to the archive using its contents as a string
3964 */
3965PHP_METHOD(Phar, addFromString)
3966{
3967    char *localname, *cont_str;
3968    int localname_len, cont_len;
3969
3970    PHAR_ARCHIVE_OBJECT();
3971
3972    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) {
3973        return;
3974    }
3975
3976    phar_add_file(&(phar_obj->arc.archive), localname, localname_len, cont_str, cont_len, NULL TSRMLS_CC);
3977}
3978/* }}} */
3979
3980/* {{{ proto string Phar::getStub()
3981 * Returns the stub at the head of a phar archive as a string.
3982 */
3983PHP_METHOD(Phar, getStub)
3984{
3985    size_t len;
3986    char *buf;
3987    php_stream *fp;
3988    php_stream_filter *filter = NULL;
3989    phar_entry_info *stub;
3990
3991    PHAR_ARCHIVE_OBJECT();
3992
3993    if (zend_parse_parameters_none() == FAILURE) {
3994        return;
3995    }
3996
3997    if (phar_obj->arc.archive->is_tar || phar_obj->arc.archive->is_zip) {
3998
3999        if (SUCCESS == zend_hash_find(&(phar_obj->arc.archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) {
4000            if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) {
4001                fp = phar_obj->arc.archive->fp;
4002            } else {
4003                if (!(fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL))) {
4004                    zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to open phar \"%s\"", phar_obj->arc.archive->fname);
4005                    return;
4006                }
4007                if (stub->flags & PHAR_ENT_COMPRESSION_MASK) {
4008                    char *filter_name;
4009
4010                    if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) {
4011                        filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp) TSRMLS_CC);
4012                    } else {
4013                        filter = NULL;
4014                    }
4015                    if (!filter) {
4016                        zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->arc.archive->fname, phar_decompress_filter(stub, 1));
4017                        return;
4018                    }
4019                    php_stream_filter_append(&fp->readfilters, filter);
4020                }
4021            }
4022
4023            if (!fp)  {
4024                zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4025                    "Unable to read stub");
4026                return;
4027            }
4028
4029            php_stream_seek(fp, stub->offset_abs, SEEK_SET);
4030            len = stub->uncompressed_filesize;
4031            goto carry_on;
4032        } else {
4033            RETURN_STRINGL("", 0, 1);
4034        }
4035    }
4036    len = phar_obj->arc.archive->halt_offset;
4037
4038    if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew) {
4039        fp = phar_obj->arc.archive->fp;
4040    } else {
4041        fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL);
4042    }
4043
4044    if (!fp)  {
4045        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4046            "Unable to read stub");
4047        return;
4048    }
4049
4050    php_stream_rewind(fp);
4051carry_on:
4052    buf = safe_emalloc(len, 1, 1);
4053
4054    if (len != php_stream_read(fp, buf, len)) {
4055        if (fp != phar_obj->arc.archive->fp) {
4056            php_stream_close(fp);
4057        }
4058        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4059            "Unable to read stub");
4060        efree(buf);
4061        return;
4062    }
4063
4064    if (filter) {
4065        php_stream_filter_flush(filter, 1);
4066        php_stream_filter_remove(filter, 1 TSRMLS_CC);
4067    }
4068
4069    if (fp != phar_obj->arc.archive->fp) {
4070        php_stream_close(fp);
4071    }
4072
4073    buf[len] = '\0';
4074    RETURN_STRINGL(buf, len, 0);
4075}
4076/* }}}*/
4077
4078/* {{{ proto int Phar::hasMetaData()
4079 * Returns TRUE if the phar has global metadata, FALSE otherwise.
4080 */
4081PHP_METHOD(Phar, hasMetadata)
4082{
4083    PHAR_ARCHIVE_OBJECT();
4084
4085    RETURN_BOOL(phar_obj->arc.archive->metadata != NULL);
4086}
4087/* }}} */
4088
4089/* {{{ proto int Phar::getMetaData()
4090 * Returns the global metadata of the phar
4091 */
4092PHP_METHOD(Phar, getMetadata)
4093{
4094    PHAR_ARCHIVE_OBJECT();
4095
4096    if (zend_parse_parameters_none() == FAILURE) {
4097        return;
4098    }
4099
4100    if (phar_obj->arc.archive->metadata) {
4101        if (phar_obj->arc.archive->is_persistent) {
4102            zval *ret;
4103            char *buf = estrndup((char *) phar_obj->arc.archive->metadata, phar_obj->arc.archive->metadata_len);
4104            /* assume success, we would have failed before */
4105            phar_parse_metadata(&buf, &ret, phar_obj->arc.archive->metadata_len TSRMLS_CC);
4106            efree(buf);
4107            RETURN_ZVAL(ret, 0, 1);
4108        }
4109        RETURN_ZVAL(phar_obj->arc.archive->metadata, 1, 0);
4110    }
4111}
4112/* }}} */
4113
4114/* {{{ proto int Phar::setMetaData(mixed $metadata)
4115 * Sets the global metadata of the phar
4116 */
4117PHP_METHOD(Phar, setMetadata)
4118{
4119    char *error;
4120    zval *metadata;
4121
4122    PHAR_ARCHIVE_OBJECT();
4123
4124    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
4125        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
4126        return;
4127    }
4128
4129    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) {
4130        return;
4131    }
4132
4133    if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
4134        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
4135        return;
4136    }
4137    if (phar_obj->arc.archive->metadata) {
4138        zval_ptr_dtor(&phar_obj->arc.archive->metadata);
4139        phar_obj->arc.archive->metadata = NULL;
4140    }
4141
4142    MAKE_STD_ZVAL(phar_obj->arc.archive->metadata);
4143    ZVAL_ZVAL(phar_obj->arc.archive->metadata, metadata, 1, 0);
4144    phar_obj->arc.archive->is_modified = 1;
4145    phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
4146
4147    if (error) {
4148        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
4149        efree(error);
4150    }
4151}
4152/* }}} */
4153
4154/* {{{ proto int Phar::delMetadata()
4155 * Deletes the global metadata of the phar
4156 */
4157PHP_METHOD(Phar, delMetadata)
4158{
4159    char *error;
4160
4161    PHAR_ARCHIVE_OBJECT();
4162
4163    if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
4164        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
4165        return;
4166    }
4167
4168    if (phar_obj->arc.archive->metadata) {
4169        zval_ptr_dtor(&phar_obj->arc.archive->metadata);
4170        phar_obj->arc.archive->metadata = NULL;
4171        phar_obj->arc.archive->is_modified = 1;
4172        phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
4173
4174        if (error) {
4175            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
4176            efree(error);
4177            RETURN_FALSE;
4178        } else {
4179            RETURN_TRUE;
4180        }
4181
4182    } else {
4183        RETURN_TRUE;
4184    }
4185}
4186/* }}} */
4187#if PHP_API_VERSION < 20100412
4188#define PHAR_OPENBASEDIR_CHECKPATH(filename) \
4189    (PG(safe_mode) && (!php_checkuid(filename, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(filename TSRMLS_CC)
4190#else
4191#define PHAR_OPENBASEDIR_CHECKPATH(filename) \
4192    php_check_open_basedir(filename TSRMLS_CC)
4193#endif
4194
4195static int phar_extract_file(zend_bool overwrite, phar_entry_info *entry, char *dest, int dest_len, char **error TSRMLS_DC) /* {{{ */
4196{
4197    php_stream_statbuf ssb;
4198    int len;
4199    php_stream *fp;
4200    char *fullpath;
4201    const char *slash;
4202    mode_t mode;
4203    cwd_state new_state;
4204    char *filename;
4205    size_t filename_len;
4206
4207    if (entry->is_mounted) {
4208        /* silently ignore mounted entries */
4209        return SUCCESS;
4210    }
4211
4212    if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) {
4213        return SUCCESS;
4214    }
4215    /* strip .. from path and restrict it to be under dest directory */
4216    new_state.cwd = (char*)malloc(2);
4217    new_state.cwd[0] = DEFAULT_SLASH;
4218    new_state.cwd[1] = '\0';
4219    new_state.cwd_length = 1;
4220    if (virtual_file_ex(&new_state, entry->filename, NULL, CWD_EXPAND TSRMLS_CC) != 0 ||
4221            new_state.cwd_length <= 1) {
4222        if (EINVAL == errno && entry->filename_len > 50) {
4223            char *tmp = estrndup(entry->filename, 50);
4224            spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, dest);
4225            efree(tmp);
4226        } else {
4227            spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename);
4228        }
4229        free(new_state.cwd);
4230        return FAILURE;
4231    }
4232    filename = new_state.cwd + 1;
4233    filename_len = new_state.cwd_length - 1;
4234#ifdef PHP_WIN32
4235    /* unixify the path back, otherwise non zip formats might be broken */
4236    {
4237        int cnt = filename_len;
4238
4239        do {
4240            if ('\\' == filename[cnt]) {
4241                filename[cnt] = '/';
4242            }
4243        } while (cnt-- >= 0);
4244    }
4245#endif
4246
4247    len = spprintf(&fullpath, 0, "%s/%s", dest, filename);
4248
4249    if (len >= MAXPATHLEN) {
4250        char *tmp;
4251        /* truncate for error message */
4252        fullpath[50] = '\0';
4253        if (entry->filename_len > 50) {
4254            tmp = estrndup(entry->filename, 50);
4255            spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath);
4256            efree(tmp);
4257        } else {
4258            spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath);
4259        }
4260        efree(fullpath);
4261        free(new_state.cwd);
4262        return FAILURE;
4263    }
4264
4265    if (!len) {
4266        spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename);
4267        efree(fullpath);
4268        free(new_state.cwd);
4269        return FAILURE;
4270    }
4271
4272    if (PHAR_OPENBASEDIR_CHECKPATH(fullpath)) {
4273        spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath);
4274        efree(fullpath);
4275        free(new_state.cwd);
4276        return FAILURE;
4277    }
4278
4279    /* let see if the path already exists */
4280    if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) {
4281        spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath);
4282        efree(fullpath);
4283        free(new_state.cwd);
4284        return FAILURE;
4285    }
4286
4287    /* perform dirname */
4288    slash = zend_memrchr(filename, '/', filename_len);
4289
4290    if (slash) {
4291        fullpath[dest_len + (slash - filename) + 1] = '\0';
4292    } else {
4293        fullpath[dest_len] = '\0';
4294    }
4295
4296    if (FAILURE == php_stream_stat_path(fullpath, &ssb)) {
4297        if (entry->is_dir) {
4298            if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK,  PHP_STREAM_MKDIR_RECURSIVE, NULL)) {
4299                spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath);
4300                efree(fullpath);
4301                free(new_state.cwd);
4302                return FAILURE;
4303            }
4304        } else {
4305            if (!php_stream_mkdir(fullpath, 0777,  PHP_STREAM_MKDIR_RECURSIVE, NULL)) {
4306                spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath);
4307                efree(fullpath);
4308                free(new_state.cwd);
4309                return FAILURE;
4310            }
4311        }
4312    }
4313
4314    if (slash) {
4315        fullpath[dest_len + (slash - filename) + 1] = '/';
4316    } else {
4317        fullpath[dest_len] = '/';
4318    }
4319
4320    filename = NULL;
4321    free(new_state.cwd);
4322    /* it is a standalone directory, job done */
4323    if (entry->is_dir) {
4324        efree(fullpath);
4325        return SUCCESS;
4326    }
4327
4328#if PHP_API_VERSION < 20100412
4329    fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL);
4330#else
4331    fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL);
4332#endif
4333
4334    if (!fp) {
4335        spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath);
4336        efree(fullpath);
4337        return FAILURE;
4338    }
4339
4340    if (!phar_get_efp(entry, 0 TSRMLS_CC)) {
4341        if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) {
4342            if (error) {
4343                spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error);
4344            } else {
4345                spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath);
4346            }
4347            efree(fullpath);
4348            php_stream_close(fp);
4349            return FAILURE;
4350        }
4351    }
4352
4353    if (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) {
4354        spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath);
4355        efree(fullpath);
4356        php_stream_close(fp);
4357        return FAILURE;
4358    }
4359
4360    if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(entry, 0 TSRMLS_CC), fp, entry->uncompressed_filesize, NULL)) {
4361        spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath);
4362        efree(fullpath);
4363        php_stream_close(fp);
4364        return FAILURE;
4365    }
4366
4367    php_stream_close(fp);
4368    mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK;
4369
4370    if (FAILURE == VCWD_CHMOD(fullpath, mode)) {
4371        spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath);
4372        efree(fullpath);
4373        return FAILURE;
4374    }
4375
4376    efree(fullpath);
4377    return SUCCESS;
4378}
4379/* }}} */
4380
4381/* {{{ proto bool Phar::extractTo(string pathto[[, mixed files], bool overwrite])
4382 * Extract one or more file from a phar archive, optionally overwriting existing files
4383 */
4384PHP_METHOD(Phar, extractTo)
4385{
4386    char *error = NULL;
4387    php_stream *fp;
4388    php_stream_statbuf ssb;
4389    phar_entry_info *entry;
4390    char *pathto, *filename, *actual;
4391    int pathto_len, filename_len;
4392    int ret, i;
4393    int nelems;
4394    zval *zval_files = NULL;
4395    zend_bool overwrite = 0;
4396
4397    PHAR_ARCHIVE_OBJECT();
4398
4399    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) {
4400        return;
4401    }
4402
4403    fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual);
4404
4405    if (!fp) {
4406        zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,
4407            "Invalid argument, %s cannot be found", phar_obj->arc.archive->fname);
4408        return;
4409    }
4410
4411    efree(actual);
4412    php_stream_close(fp);
4413
4414    if (pathto_len < 1) {
4415        zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,
4416            "Invalid argument, extraction path must be non-zero length");
4417        return;
4418    }
4419
4420    if (pathto_len >= MAXPATHLEN) {
4421        char *tmp = estrndup(pathto, 50);
4422        /* truncate for error message */
4423        zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp);
4424        efree(tmp);
4425        return;
4426    }
4427
4428    if (php_stream_stat_path(pathto, &ssb) < 0) {
4429        ret = php_stream_mkdir(pathto, 0777,  PHP_STREAM_MKDIR_RECURSIVE, NULL);
4430        if (!ret) {
4431            zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4432                "Unable to create path \"%s\" for extraction", pathto);
4433            return;
4434        }
4435    } else if (!(ssb.sb.st_mode & S_IFDIR)) {
4436        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4437            "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto);
4438        return;
4439    }
4440
4441    if (zval_files) {
4442        switch (Z_TYPE_P(zval_files)) {
4443            case IS_NULL:
4444                goto all_files;
4445#if PHP_VERSION_ID >= 60000
4446            case IS_UNICODE:
4447                zval_unicode_to_string(zval_files TSRMLS_CC);
4448                /* break intentionally omitted */
4449#endif
4450            case IS_STRING:
4451                filename = Z_STRVAL_P(zval_files);
4452                filename_len = Z_STRLEN_P(zval_files);
4453                break;
4454            case IS_ARRAY:
4455                nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files));
4456                if (nelems == 0 ) {
4457                    RETURN_FALSE;
4458                }
4459                for (i = 0; i < nelems; i++) {
4460                    zval **zval_file;
4461                    if (zend_hash_index_find(Z_ARRVAL_P(zval_files), i, (void **) &zval_file) == SUCCESS) {
4462                        switch (Z_TYPE_PP(zval_file)) {
4463#if PHP_VERSION_ID >= 60000
4464                            case IS_UNICODE:
4465                                zval_unicode_to_string(*(zval_file) TSRMLS_CC);
4466                                /* break intentionally omitted */
4467#endif
4468                            case IS_STRING:
4469                                break;
4470                            default:
4471                                zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,
4472                                    "Invalid argument, array of filenames to extract contains non-string value");
4473                                return;
4474                        }
4475                        if (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, Z_STRVAL_PP(zval_file), Z_STRLEN_PP(zval_file), (void **)&entry)) {
4476                            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,
4477                                "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_PP(zval_file), phar_obj->arc.archive->fname);
4478                        }
4479                        if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) {
4480                            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,
4481                                "Extraction from phar \"%s\" failed: %s", phar_obj->arc.archive->fname, error);
4482                            efree(error);
4483                            return;
4484                        }
4485                    }
4486                }
4487                RETURN_TRUE;
4488            default:
4489                zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,
4490                    "Invalid argument, expected a filename (string) or array of filenames");
4491                return;
4492        }
4493
4494        if (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, filename, filename_len, (void **)&entry)) {
4495            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,
4496                "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->arc.archive->fname);
4497            return;
4498        }
4499
4500        if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) {
4501            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,
4502                "Extraction from phar \"%s\" failed: %s", phar_obj->arc.archive->fname, error);
4503            efree(error);
4504            return;
4505        }
4506    } else {
4507        phar_archive_data *phar;
4508all_files:
4509        phar = phar_obj->arc.archive;
4510        /* Extract all files */
4511        if (!zend_hash_num_elements(&(phar->manifest))) {
4512            RETURN_TRUE;
4513        }
4514
4515        for (zend_hash_internal_pointer_reset(&phar->manifest);
4516        zend_hash_has_more_elements(&phar->manifest) == SUCCESS;
4517        zend_hash_move_forward(&phar->manifest)) {
4518
4519            if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) {
4520                continue;
4521            }
4522
4523            if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) {
4524                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,
4525                    "Extraction from phar \"%s\" failed: %s", phar->fname, error);
4526                efree(error);
4527                return;
4528            }
4529        }
4530    }
4531    RETURN_TRUE;
4532}
4533/* }}} */
4534
4535
4536/* {{{ proto void PharFileInfo::__construct(string entry)
4537 * Construct a Phar entry object
4538 */
4539PHP_METHOD(PharFileInfo, __construct)
4540{
4541    char *fname, *arch, *entry, *error;
4542    int fname_len, arch_len, entry_len;
4543    phar_entry_object *entry_obj;
4544    phar_entry_info *entry_info;
4545    phar_archive_data *phar_data;
4546    zval *zobj = getThis(), arg1;
4547
4548    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
4549        return;
4550    }
4551
4552    entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
4553
4554    if (entry_obj->ent.entry) {
4555        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
4556        return;
4557    }
4558
4559    if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC) == FAILURE) {
4560        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4561            "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname);
4562        return;
4563    }
4564
4565    if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
4566        efree(arch);
4567        efree(entry);
4568        if (error) {
4569            zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4570                "Cannot open phar file '%s': %s", fname, error);
4571            efree(error);
4572        } else {
4573            zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4574                "Cannot open phar file '%s'", fname);
4575        }
4576        return;
4577    }
4578
4579    if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1 TSRMLS_CC)) == NULL) {
4580        zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
4581            "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : "");
4582        efree(arch);
4583        efree(entry);
4584        return;
4585    }
4586
4587    efree(arch);
4588    efree(entry);
4589
4590    entry_obj->ent.entry = entry_info;
4591
4592    INIT_PZVAL(&arg1);
4593    ZVAL_STRINGL(&arg1, fname, fname_len, 0);
4594
4595    zend_call_method_with_1_params(&zobj, Z_OBJCE_P(zobj),
4596        &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1);
4597}
4598/* }}} */
4599
4600#define PHAR_ENTRY_OBJECT() \
4601    phar_entry_object *entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
4602    if (!entry_obj->ent.entry) { \
4603        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4604            "Cannot call method on an uninitialized PharFileInfo object"); \
4605        return; \
4606    }
4607
4608/* {{{ proto void PharFileInfo::__destruct()
4609 * clean up directory-based entry objects
4610 */
4611PHP_METHOD(PharFileInfo, __destruct)
4612{
4613    phar_entry_object *entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
4614
4615    if (entry_obj->ent.entry && entry_obj->ent.entry->is_temp_dir) {
4616        if (entry_obj->ent.entry->filename) {
4617            efree(entry_obj->ent.entry->filename);
4618            entry_obj->ent.entry->filename = NULL;
4619        }
4620
4621        efree(entry_obj->ent.entry);
4622        entry_obj->ent.entry = NULL;
4623    }
4624}
4625/* }}} */
4626
4627/* {{{ proto int PharFileInfo::getCompressedSize()
4628 * Returns the compressed size
4629 */
4630PHP_METHOD(PharFileInfo, getCompressedSize)
4631{
4632    PHAR_ENTRY_OBJECT();
4633
4634    if (zend_parse_parameters_none() == FAILURE) {
4635        return;
4636    }
4637
4638    RETURN_LONG(entry_obj->ent.entry->compressed_filesize);
4639}
4640/* }}} */
4641
4642/* {{{ proto bool PharFileInfo::isCompressed([int compression_type])
4643 * Returns whether the entry is compressed, and whether it is compressed with Phar::GZ or Phar::BZ2 if specified
4644 */
4645PHP_METHOD(PharFileInfo, isCompressed)
4646{
4647    /* a number that is not Phar::GZ or Phar::BZ2 */
4648    long method = 9021976;
4649    PHAR_ENTRY_OBJECT();
4650
4651    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
4652        return;
4653    }
4654
4655    switch (method) {
4656        case 9021976:
4657            RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSION_MASK);
4658        case PHAR_ENT_COMPRESSED_GZ:
4659            RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ);
4660        case PHAR_ENT_COMPRESSED_BZ2:
4661            RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2);
4662        default:
4663            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4664                "Unknown compression type specified"); \
4665    }
4666}
4667/* }}} */
4668
4669/* {{{ proto int PharFileInfo::getCRC32()
4670 * Returns CRC32 code or throws an exception if not CRC checked
4671 */
4672PHP_METHOD(PharFileInfo, getCRC32)
4673{
4674    PHAR_ENTRY_OBJECT();
4675
4676    if (zend_parse_parameters_none() == FAILURE) {
4677        return;
4678    }
4679
4680    if (entry_obj->ent.entry->is_dir) {
4681        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4682            "Phar entry is a directory, does not have a CRC"); \
4683        return;
4684    }
4685
4686    if (entry_obj->ent.entry->is_crc_checked) {
4687        RETURN_LONG(entry_obj->ent.entry->crc32);
4688    } else {
4689        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4690            "Phar entry was not CRC checked"); \
4691    }
4692}
4693/* }}} */
4694
4695/* {{{ proto int PharFileInfo::isCRCChecked()
4696 * Returns whether file entry is CRC checked
4697 */
4698PHP_METHOD(PharFileInfo, isCRCChecked)
4699{
4700    PHAR_ENTRY_OBJECT();
4701
4702    if (zend_parse_parameters_none() == FAILURE) {
4703        return;
4704    }
4705
4706    RETURN_BOOL(entry_obj->ent.entry->is_crc_checked);
4707}
4708/* }}} */
4709
4710/* {{{ proto int PharFileInfo::getPharFlags()
4711 * Returns the Phar file entry flags
4712 */
4713PHP_METHOD(PharFileInfo, getPharFlags)
4714{
4715    PHAR_ENTRY_OBJECT();
4716
4717    if (zend_parse_parameters_none() == FAILURE) {
4718        return;
4719    }
4720
4721    RETURN_LONG(entry_obj->ent.entry->flags & ~(PHAR_ENT_PERM_MASK|PHAR_ENT_COMPRESSION_MASK));
4722}
4723/* }}} */
4724
4725/* {{{ proto int PharFileInfo::chmod()
4726 * set the file permissions for the Phar.  This only allows setting execution bit, read/write
4727 */
4728PHP_METHOD(PharFileInfo, chmod)
4729{
4730    char *error;
4731    long perms;
4732    PHAR_ENTRY_OBJECT();
4733
4734    if (entry_obj->ent.entry->is_temp_dir) {
4735        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4736            "Phar entry \"%s\" is a temporary directory (not an actual entry in the archive), cannot chmod", entry_obj->ent.entry->filename); \
4737        return;
4738    }
4739
4740    if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) {
4741        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Cannot modify permissions for file \"%s\" in phar \"%s\", write operations are prohibited", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname);
4742        return;
4743    }
4744
4745    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &perms) == FAILURE) {
4746        return;
4747    }
4748
4749    if (entry_obj->ent.entry->is_persistent) {
4750        phar_archive_data *phar = entry_obj->ent.entry->phar;
4751
4752        if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) {
4753            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4754            return;
4755        }
4756        /* re-populate after copy-on-write */
4757        zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry);
4758    }
4759    /* clear permissions */
4760    entry_obj->ent.entry->flags &= ~PHAR_ENT_PERM_MASK;
4761    perms &= 0777;
4762    entry_obj->ent.entry->flags |= perms;
4763    entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags;
4764    entry_obj->ent.entry->phar->is_modified = 1;
4765    entry_obj->ent.entry->is_modified = 1;
4766
4767    /* hackish cache in php_stat needs to be cleared */
4768    /* if this code fails to work, check main/streams/streams.c, _php_stream_stat_path */
4769    if (BG(CurrentLStatFile)) {
4770        efree(BG(CurrentLStatFile));
4771    }
4772
4773    if (BG(CurrentStatFile)) {
4774        efree(BG(CurrentStatFile));
4775    }
4776
4777    BG(CurrentLStatFile) = NULL;
4778    BG(CurrentStatFile) = NULL;
4779    phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC);
4780
4781    if (error) {
4782        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
4783        efree(error);
4784    }
4785}
4786/* }}} */
4787
4788/* {{{ proto int PharFileInfo::hasMetaData()
4789 * Returns the metadata of the entry
4790 */
4791PHP_METHOD(PharFileInfo, hasMetadata)
4792{
4793    PHAR_ENTRY_OBJECT();
4794
4795    if (zend_parse_parameters_none() == FAILURE) {
4796        return;
4797    }
4798
4799    RETURN_BOOL(entry_obj->ent.entry->metadata != NULL);
4800}
4801/* }}} */
4802
4803/* {{{ proto int PharFileInfo::getMetaData()
4804 * Returns the metadata of the entry
4805 */
4806PHP_METHOD(PharFileInfo, getMetadata)
4807{
4808    PHAR_ENTRY_OBJECT();
4809
4810    if (zend_parse_parameters_none() == FAILURE) {
4811        return;
4812    }
4813
4814    if (entry_obj->ent.entry->metadata) {
4815        if (entry_obj->ent.entry->is_persistent) {
4816            zval *ret;
4817            char *buf = estrndup((char *) entry_obj->ent.entry->metadata, entry_obj->ent.entry->metadata_len);
4818            /* assume success, we would have failed before */
4819            phar_parse_metadata(&buf, &ret, entry_obj->ent.entry->metadata_len TSRMLS_CC);
4820            efree(buf);
4821            RETURN_ZVAL(ret, 0, 1);
4822        }
4823        RETURN_ZVAL(entry_obj->ent.entry->metadata, 1, 0);
4824    }
4825}
4826/* }}} */
4827
4828/* {{{ proto int PharFileInfo::setMetaData(mixed $metadata)
4829 * Sets the metadata of the entry
4830 */
4831PHP_METHOD(PharFileInfo, setMetadata)
4832{
4833    char *error;
4834    zval *metadata;
4835
4836    PHAR_ENTRY_OBJECT();
4837
4838    if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) {
4839        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
4840        return;
4841    }
4842
4843    if (entry_obj->ent.entry->is_temp_dir) {
4844        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4845            "Phar entry is a temporary directory (not an actual entry in the archive), cannot set metadata"); \
4846        return;
4847    }
4848
4849    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) {
4850        return;
4851    }
4852
4853    if (entry_obj->ent.entry->is_persistent) {
4854        phar_archive_data *phar = entry_obj->ent.entry->phar;
4855
4856        if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) {
4857            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4858            return;
4859        }
4860        /* re-populate after copy-on-write */
4861        zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry);
4862    }
4863    if (entry_obj->ent.entry->metadata) {
4864        zval_ptr_dtor(&entry_obj->ent.entry->metadata);
4865        entry_obj->ent.entry->metadata = NULL;
4866    }
4867
4868    MAKE_STD_ZVAL(entry_obj->ent.entry->metadata);
4869    ZVAL_ZVAL(entry_obj->ent.entry->metadata, metadata, 1, 0);
4870
4871    entry_obj->ent.entry->is_modified = 1;
4872    entry_obj->ent.entry->phar->is_modified = 1;
4873    phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC);
4874
4875    if (error) {
4876        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
4877        efree(error);
4878    }
4879}
4880/* }}} */
4881
4882/* {{{ proto bool PharFileInfo::delMetaData()
4883 * Deletes the metadata of the entry
4884 */
4885PHP_METHOD(PharFileInfo, delMetadata)
4886{
4887    char *error;
4888
4889    PHAR_ENTRY_OBJECT();
4890
4891    if (zend_parse_parameters_none() == FAILURE) {
4892        return;
4893    }
4894
4895    if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) {
4896        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
4897        return;
4898    }
4899
4900    if (entry_obj->ent.entry->is_temp_dir) {
4901        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
4902            "Phar entry is a temporary directory (not an actual entry in the archive), cannot delete metadata"); \
4903        return;
4904    }
4905
4906    if (entry_obj->ent.entry->metadata) {
4907        if (entry_obj->ent.entry->is_persistent) {
4908            phar_archive_data *phar = entry_obj->ent.entry->phar;
4909
4910            if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) {
4911                zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4912                return;
4913            }
4914            /* re-populate after copy-on-write */
4915            zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry);
4916        }
4917        zval_ptr_dtor(&entry_obj->ent.entry->metadata);
4918        entry_obj->ent.entry->metadata = NULL;
4919        entry_obj->ent.entry->is_modified = 1;
4920        entry_obj->ent.entry->phar->is_modified = 1;
4921
4922        phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC);
4923
4924        if (error) {
4925            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
4926            efree(error);
4927            RETURN_FALSE;
4928        } else {
4929            RETURN_TRUE;
4930        }
4931
4932    } else {
4933        RETURN_TRUE;
4934    }
4935}
4936/* }}} */
4937
4938/* {{{ proto string PharFileInfo::getContent()
4939 * return the complete file contents of the entry (like file_get_contents)
4940 */
4941PHP_METHOD(PharFileInfo, getContent)
4942{
4943    char *error;
4944    php_stream *fp;
4945    phar_entry_info *link;
4946
4947    PHAR_ENTRY_OBJECT();
4948
4949    if (zend_parse_parameters_none() == FAILURE) {
4950        return;
4951    }
4952
4953    if (entry_obj->ent.entry->is_dir) {
4954        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
4955            "Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\" is a directory", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname);
4956        return;
4957    }
4958
4959    link = phar_get_link_source(entry_obj->ent.entry TSRMLS_CC);
4960
4961    if (!link) {
4962        link = entry_obj->ent.entry;
4963    }
4964
4965    if (SUCCESS != phar_open_entry_fp(link, &error, 0 TSRMLS_CC)) {
4966        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
4967            "Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\": %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error);
4968        efree(error);
4969        return;
4970    }
4971
4972    if (!(fp = phar_get_efp(link, 0 TSRMLS_CC))) {
4973        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
4974            "Phar error: Cannot retrieve contents of \"%s\" in phar \"%s\"", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname);
4975        return;
4976    }
4977
4978    phar_seek_efp(link, 0, SEEK_SET, 0, 0 TSRMLS_CC);
4979    Z_TYPE_P(return_value) = IS_STRING;
4980    Z_STRLEN_P(return_value) = php_stream_copy_to_mem(fp, &(Z_STRVAL_P(return_value)), link->uncompressed_filesize, 0);
4981
4982    if (!Z_STRVAL_P(return_value)) {
4983        Z_STRVAL_P(return_value) = estrndup("", 0);
4984    }
4985}
4986/* }}} */
4987
4988/* {{{ proto int PharFileInfo::compress(int compression_type)
4989 * Instructs the Phar class to compress the current file using zlib or bzip2 compression
4990 */
4991PHP_METHOD(PharFileInfo, compress)
4992{
4993    long method;
4994    char *error;
4995    PHAR_ENTRY_OBJECT();
4996
4997    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) {
4998        return;
4999    }
5000
5001    if (entry_obj->ent.entry->is_tar) {
5002        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5003            "Cannot compress with Gzip compression, not possible with tar-based phar archives");
5004        return;
5005    }
5006
5007    if (entry_obj->ent.entry->is_dir) {
5008        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
5009            "Phar entry is a directory, cannot set compression"); \
5010        return;
5011    }
5012
5013    if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) {
5014        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5015            "Phar is readonly, cannot change compression");
5016        return;
5017    }
5018
5019    if (entry_obj->ent.entry->is_deleted) {
5020        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5021            "Cannot compress deleted file");
5022        return;
5023    }
5024
5025    if (entry_obj->ent.entry->is_persistent) {
5026        phar_archive_data *phar = entry_obj->ent.entry->phar;
5027
5028        if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) {
5029            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
5030            return;
5031        }
5032        /* re-populate after copy-on-write */
5033        zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry);
5034    }
5035    switch (method) {
5036        case PHAR_ENT_COMPRESSED_GZ:
5037            if (entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) {
5038                RETURN_TRUE;
5039            }
5040
5041            if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0) {
5042                if (!PHAR_G(has_bz2)) {
5043                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5044                        "Cannot compress with gzip compression, file is already compressed with bzip2 compression and bz2 extension is not enabled, cannot decompress");
5045                    return;
5046                }
5047
5048                /* decompress this file indirectly */
5049                if (SUCCESS != phar_open_entry_fp(entry_obj->ent.entry, &error, 1 TSRMLS_CC)) {
5050                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5051                        "Phar error: Cannot decompress bzip2-compressed file \"%s\" in phar \"%s\" in order to compress with gzip: %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error);
5052                    efree(error);
5053                    return;
5054                }
5055            }
5056
5057            if (!PHAR_G(has_zlib)) {
5058                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5059                    "Cannot compress with gzip compression, zlib extension is not enabled");
5060                return;
5061            }
5062
5063            entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags;
5064            entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
5065            entry_obj->ent.entry->flags |= PHAR_ENT_COMPRESSED_GZ;
5066            break;
5067        case PHAR_ENT_COMPRESSED_BZ2:
5068            if (entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
5069                RETURN_TRUE;
5070            }
5071
5072            if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0) {
5073                if (!PHAR_G(has_zlib)) {
5074                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5075                        "Cannot compress with bzip2 compression, file is already compressed with gzip compression and zlib extension is not enabled, cannot decompress");
5076                    return;
5077                }
5078
5079                /* decompress this file indirectly */
5080                if (SUCCESS != phar_open_entry_fp(entry_obj->ent.entry, &error, 1 TSRMLS_CC)) {
5081                    zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5082                        "Phar error: Cannot decompress gzip-compressed file \"%s\" in phar \"%s\" in order to compress with bzip2: %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error);
5083                    efree(error);
5084                    return;
5085                }
5086            }
5087
5088            if (!PHAR_G(has_bz2)) {
5089                zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5090                    "Cannot compress with bzip2 compression, bz2 extension is not enabled");
5091                return;
5092            }
5093            entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags;
5094            entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
5095            entry_obj->ent.entry->flags |= PHAR_ENT_COMPRESSED_BZ2;
5096            break;
5097        default:
5098            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
5099                "Unknown compression type specified"); \
5100    }
5101
5102    entry_obj->ent.entry->phar->is_modified = 1;
5103    entry_obj->ent.entry->is_modified = 1;
5104    phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC);
5105
5106    if (error) {
5107        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
5108        efree(error);
5109    }
5110
5111    RETURN_TRUE;
5112}
5113/* }}} */
5114
5115/* {{{ proto int PharFileInfo::decompress()
5116 * Instructs the Phar class to decompress the current file
5117 */
5118PHP_METHOD(PharFileInfo, decompress)
5119{
5120    char *error;
5121    PHAR_ENTRY_OBJECT();
5122
5123    if (zend_parse_parameters_none() == FAILURE) {
5124        return;
5125    }
5126
5127    if (entry_obj->ent.entry->is_dir) {
5128        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
5129            "Phar entry is a directory, cannot set compression"); \
5130        return;
5131    }
5132
5133    if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSION_MASK) == 0) {
5134        RETURN_TRUE;
5135    }
5136
5137    if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) {
5138        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5139            "Phar is readonly, cannot decompress");
5140        return;
5141    }
5142
5143    if (entry_obj->ent.entry->is_deleted) {
5144        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5145            "Cannot compress deleted file");
5146        return;
5147    }
5148
5149    if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0 && !PHAR_G(has_zlib)) {
5150        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5151            "Cannot decompress Gzip-compressed file, zlib extension is not enabled");
5152        return;
5153    }
5154
5155    if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0 && !PHAR_G(has_bz2)) {
5156        zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC,
5157            "Cannot decompress Bzip2-compressed file, bz2 extension is not enabled");
5158        return;
5159    }
5160
5161    if (entry_obj->ent.entry->is_persistent) {
5162        phar_archive_data *phar = entry_obj->ent.entry->phar;
5163
5164        if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) {
5165            zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
5166            return;
5167        }
5168        /* re-populate after copy-on-write */
5169        zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry);
5170    }
5171    if (!entry_obj->ent.entry->fp) {
5172        if (FAILURE == phar_open_archive_fp(entry_obj->ent.entry->phar TSRMLS_CC)) {
5173            zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress entry \"%s\", phar error: Cannot open phar archive \"%s\" for reading", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname);
5174            return;
5175        }
5176        entry_obj->ent.entry->fp_type = PHAR_FP;
5177    }
5178
5179    entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags;
5180    entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
5181    entry_obj->ent.entry->phar->is_modified = 1;
5182    entry_obj->ent.entry->is_modified = 1;
5183    phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC);
5184
5185    if (error) {
5186        zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
5187        efree(error);
5188    }
5189    RETURN_TRUE;
5190}
5191/* }}} */
5192
5193#endif /* HAVE_SPL */
5194
5195/* {{{ phar methods */
5196PHAR_ARG_INFO
5197ZEND_BEGIN_ARG_INFO_EX(arginfo_phar___construct, 0, 0, 1)
5198    ZEND_ARG_INFO(0, filename)
5199    ZEND_ARG_INFO(0, flags)
5200    ZEND_ARG_INFO(0, alias)
5201    ZEND_ARG_INFO(0, fileformat)
5202ZEND_END_ARG_INFO()
5203
5204PHAR_ARG_INFO
5205ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_createDS, 0, 0, 0)
5206    ZEND_ARG_INFO(0, index)
5207    ZEND_ARG_INFO(0, webindex)
5208ZEND_END_ARG_INFO()
5209
5210PHAR_ARG_INFO
5211ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_cancompress, 0, 0, 0)
5212    ZEND_ARG_INFO(0, method)
5213ZEND_END_ARG_INFO()
5214
5215PHAR_ARG_INFO
5216ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_isvalidpharfilename, 0, 0, 1)
5217    ZEND_ARG_INFO(0, filename)
5218    ZEND_ARG_INFO(0, executable)
5219ZEND_END_ARG_INFO()
5220
5221PHAR_ARG_INFO
5222ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_loadPhar, 0, 0, 1)
5223    ZEND_ARG_INFO(0, filename)
5224    ZEND_ARG_INFO(0, alias)
5225ZEND_END_ARG_INFO()
5226
5227PHAR_ARG_INFO
5228ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mapPhar, 0, 0, 0)
5229    ZEND_ARG_INFO(0, alias)
5230    ZEND_ARG_INFO(0, offset)
5231ZEND_END_ARG_INFO()
5232
5233PHAR_ARG_INFO
5234ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mount, 0, 0, 2)
5235    ZEND_ARG_INFO(0, inphar)
5236    ZEND_ARG_INFO(0, externalfile)
5237ZEND_END_ARG_INFO()
5238
5239PHAR_ARG_INFO
5240ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mungServer, 0, 0, 1)
5241    ZEND_ARG_INFO(0, munglist)
5242ZEND_END_ARG_INFO()
5243
5244PHAR_ARG_INFO
5245ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_webPhar, 0, 0, 0)
5246    ZEND_ARG_INFO(0, alias)
5247    ZEND_ARG_INFO(0, index)
5248    ZEND_ARG_INFO(0, f404)
5249    ZEND_ARG_INFO(0, mimetypes)
5250    ZEND_ARG_INFO(0, rewrites)
5251ZEND_END_ARG_INFO()
5252
5253PHAR_ARG_INFO
5254ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_running, 0, 0, 1)
5255    ZEND_ARG_INFO(0, retphar)
5256ZEND_END_ARG_INFO()
5257
5258PHAR_ARG_INFO
5259ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_ua, 0, 0, 1)
5260    ZEND_ARG_INFO(0, archive)
5261ZEND_END_ARG_INFO()
5262
5263#if HAVE_SPL
5264PHAR_ARG_INFO
5265ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_build, 0, 0, 1)
5266    ZEND_ARG_INFO(0, iterator)
5267    ZEND_ARG_INFO(0, base_directory)
5268ZEND_END_ARG_INFO()
5269
5270PHAR_ARG_INFO
5271ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_conv, 0, 0, 0)
5272    ZEND_ARG_INFO(0, format)
5273    ZEND_ARG_INFO(0, compression_type)
5274    ZEND_ARG_INFO(0, file_ext)
5275ZEND_END_ARG_INFO()
5276
5277PHAR_ARG_INFO
5278ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comps, 0, 0, 1)
5279    ZEND_ARG_INFO(0, compression_type)
5280    ZEND_ARG_INFO(0, file_ext)
5281ZEND_END_ARG_INFO()
5282
5283PHAR_ARG_INFO
5284ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_decomp, 0, 0, 0)
5285    ZEND_ARG_INFO(0, file_ext)
5286ZEND_END_ARG_INFO()
5287
5288PHAR_ARG_INFO
5289ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comp, 0, 0, 1)
5290    ZEND_ARG_INFO(0, compression_type)
5291ZEND_END_ARG_INFO()
5292
5293PHAR_ARG_INFO
5294ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_compo, 0, 0, 0)
5295    ZEND_ARG_INFO(0, compression_type)
5296ZEND_END_ARG_INFO()
5297
5298PHAR_ARG_INFO
5299ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_copy, 0, 0, 2)
5300    ZEND_ARG_INFO(0, newfile)
5301    ZEND_ARG_INFO(0, oldfile)
5302ZEND_END_ARG_INFO()
5303
5304PHAR_ARG_INFO
5305ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_delete, 0, 0, 1)
5306    ZEND_ARG_INFO(0, entry)
5307ZEND_END_ARG_INFO()
5308
5309PHAR_ARG_INFO
5310ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromdir, 0, 0, 1)
5311    ZEND_ARG_INFO(0, base_dir)
5312    ZEND_ARG_INFO(0, regex)
5313ZEND_END_ARG_INFO()
5314
5315PHAR_ARG_INFO
5316ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetExists, 0, 0, 1)
5317    ZEND_ARG_INFO(0, entry)
5318ZEND_END_ARG_INFO()
5319
5320PHAR_ARG_INFO
5321ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetSet, 0, 0, 2)
5322    ZEND_ARG_INFO(0, entry)
5323    ZEND_ARG_INFO(0, value)
5324ZEND_END_ARG_INFO()
5325
5326PHAR_ARG_INFO
5327ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setAlias, 0, 0, 1)
5328    ZEND_ARG_INFO(0, alias)
5329ZEND_END_ARG_INFO()
5330
5331PHAR_ARG_INFO
5332ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setMetadata, 0, 0, 1)
5333    ZEND_ARG_INFO(0, metadata)
5334ZEND_END_ARG_INFO()
5335
5336PHAR_ARG_INFO
5337ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setSigAlgo, 0, 0, 1)
5338    ZEND_ARG_INFO(0, algorithm)
5339    ZEND_ARG_INFO(0, privatekey)
5340ZEND_END_ARG_INFO()
5341
5342PHAR_ARG_INFO
5343ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setStub, 0, 0, 1)
5344    ZEND_ARG_INFO(0, newstub)
5345    ZEND_ARG_INFO(0, maxlen)
5346ZEND_END_ARG_INFO()
5347
5348PHAR_ARG_INFO
5349ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_emptydir, 0, 0, 0)
5350    ZEND_ARG_INFO(0, dirname)
5351ZEND_END_ARG_INFO()
5352
5353PHAR_ARG_INFO
5354ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_extract, 0, 0, 1)
5355    ZEND_ARG_INFO(0, pathto)
5356    ZEND_ARG_INFO(0, files)
5357    ZEND_ARG_INFO(0, overwrite)
5358ZEND_END_ARG_INFO()
5359
5360PHAR_ARG_INFO
5361ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_addfile, 0, 0, 1)
5362    ZEND_ARG_INFO(0, filename)
5363    ZEND_ARG_INFO(0, localname)
5364ZEND_END_ARG_INFO()
5365
5366PHAR_ARG_INFO
5367ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromstring, 0, 0, 1)
5368    ZEND_ARG_INFO(0, localname)
5369    ZEND_ARG_INFO(0, contents)
5370ZEND_END_ARG_INFO()
5371
5372PHAR_ARG_INFO
5373ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_isff, 0, 0, 1)
5374    ZEND_ARG_INFO(0, fileformat)
5375ZEND_END_ARG_INFO()
5376
5377PHAR_ARG_INFO
5378ZEND_BEGIN_ARG_INFO(arginfo_phar__void, 0)
5379ZEND_END_ARG_INFO()
5380
5381
5382#endif /* HAVE_SPL */
5383
5384zend_function_entry php_archive_methods[] = {
5385#if !HAVE_SPL
5386    PHP_ME(Phar, __construct,           arginfo_phar___construct,  ZEND_ACC_PRIVATE)
5387#else
5388    PHP_ME(Phar, __construct,           arginfo_phar___construct,  ZEND_ACC_PUBLIC)
5389    PHP_ME(Phar, __destruct,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5390    PHP_ME(Phar, addEmptyDir,           arginfo_phar_emptydir,     ZEND_ACC_PUBLIC)
5391    PHP_ME(Phar, addFile,               arginfo_phar_addfile,      ZEND_ACC_PUBLIC)
5392    PHP_ME(Phar, addFromString,         arginfo_phar_fromstring,   ZEND_ACC_PUBLIC)
5393    PHP_ME(Phar, buildFromDirectory,    arginfo_phar_fromdir,      ZEND_ACC_PUBLIC)
5394    PHP_ME(Phar, buildFromIterator,     arginfo_phar_build,        ZEND_ACC_PUBLIC)
5395    PHP_ME(Phar, compressFiles,         arginfo_phar_comp,         ZEND_ACC_PUBLIC)
5396    PHP_ME(Phar, decompressFiles,       arginfo_phar__void,        ZEND_ACC_PUBLIC)
5397    PHP_ME(Phar, compress,              arginfo_phar_comps,        ZEND_ACC_PUBLIC)
5398    PHP_ME(Phar, decompress,            arginfo_phar_decomp,       ZEND_ACC_PUBLIC)
5399    PHP_ME(Phar, convertToExecutable,   arginfo_phar_conv,         ZEND_ACC_PUBLIC)
5400    PHP_ME(Phar, convertToData,         arginfo_phar_conv,         ZEND_ACC_PUBLIC)
5401    PHP_ME(Phar, copy,                  arginfo_phar_copy,         ZEND_ACC_PUBLIC)
5402    PHP_ME(Phar, count,                 arginfo_phar__void,        ZEND_ACC_PUBLIC)
5403    PHP_ME(Phar, delete,                arginfo_phar_delete,       ZEND_ACC_PUBLIC)
5404    PHP_ME(Phar, delMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5405    PHP_ME(Phar, extractTo,             arginfo_phar_extract,      ZEND_ACC_PUBLIC)
5406    PHP_ME(Phar, getAlias,              arginfo_phar__void,        ZEND_ACC_PUBLIC)
5407    PHP_ME(Phar, getPath,               arginfo_phar__void,        ZEND_ACC_PUBLIC)
5408    PHP_ME(Phar, getMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5409    PHP_ME(Phar, getModified,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5410    PHP_ME(Phar, getSignature,          arginfo_phar__void,        ZEND_ACC_PUBLIC)
5411    PHP_ME(Phar, getStub,               arginfo_phar__void,        ZEND_ACC_PUBLIC)
5412    PHP_ME(Phar, getVersion,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5413    PHP_ME(Phar, hasMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5414    PHP_ME(Phar, isBuffering,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5415    PHP_ME(Phar, isCompressed,          arginfo_phar__void,        ZEND_ACC_PUBLIC)
5416    PHP_ME(Phar, isFileFormat,          arginfo_phar_isff,         ZEND_ACC_PUBLIC)
5417    PHP_ME(Phar, isWritable,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5418    PHP_ME(Phar, offsetExists,          arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5419    PHP_ME(Phar, offsetGet,             arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5420    PHP_ME(Phar, offsetSet,             arginfo_phar_offsetSet,    ZEND_ACC_PUBLIC)
5421    PHP_ME(Phar, offsetUnset,           arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5422    PHP_ME(Phar, setAlias,              arginfo_phar_setAlias,     ZEND_ACC_PUBLIC)
5423    PHP_ME(Phar, setDefaultStub,        arginfo_phar_createDS,     ZEND_ACC_PUBLIC)
5424    PHP_ME(Phar, setMetadata,           arginfo_phar_setMetadata,  ZEND_ACC_PUBLIC)
5425    PHP_ME(Phar, setSignatureAlgorithm, arginfo_phar_setSigAlgo,   ZEND_ACC_PUBLIC)
5426    PHP_ME(Phar, setStub,               arginfo_phar_setStub,      ZEND_ACC_PUBLIC)
5427    PHP_ME(Phar, startBuffering,        arginfo_phar__void,        ZEND_ACC_PUBLIC)
5428    PHP_ME(Phar, stopBuffering,         arginfo_phar__void,        ZEND_ACC_PUBLIC)
5429#endif
5430    /* static member functions */
5431    PHP_ME(Phar, apiVersion,            arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5432    PHP_ME(Phar, canCompress,           arginfo_phar_cancompress,  ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5433    PHP_ME(Phar, canWrite,              arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5434    PHP_ME(Phar, createDefaultStub,     arginfo_phar_createDS,     ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5435    PHP_ME(Phar, getSupportedCompression,arginfo_phar__void,       ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5436    PHP_ME(Phar, getSupportedSignatures,arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5437    PHP_ME(Phar, interceptFileFuncs,    arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5438    PHP_ME(Phar, isValidPharFilename,   arginfo_phar_isvalidpharfilename, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5439    PHP_ME(Phar, loadPhar,              arginfo_phar_loadPhar,     ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5440    PHP_ME(Phar, mapPhar,               arginfo_phar_mapPhar,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5441    PHP_ME(Phar, running,               arginfo_phar_running,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5442    PHP_ME(Phar, mount,                 arginfo_phar_mount,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5443    PHP_ME(Phar, mungServer,            arginfo_phar_mungServer,   ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5444    PHP_ME(Phar, unlinkArchive,         arginfo_phar_ua,           ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5445    PHP_ME(Phar, webPhar,               arginfo_phar_webPhar,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5446    PHP_FE_END
5447};
5448
5449#if HAVE_SPL
5450PHAR_ARG_INFO
5451ZEND_BEGIN_ARG_INFO_EX(arginfo_entry___construct, 0, 0, 1)
5452    ZEND_ARG_INFO(0, filename)
5453ZEND_END_ARG_INFO()
5454
5455PHAR_ARG_INFO
5456ZEND_BEGIN_ARG_INFO_EX(arginfo_entry_chmod, 0, 0, 1)
5457    ZEND_ARG_INFO(0, perms)
5458ZEND_END_ARG_INFO()
5459
5460zend_function_entry php_entry_methods[] = {
5461    PHP_ME(PharFileInfo, __construct,        arginfo_entry___construct,  ZEND_ACC_PUBLIC)
5462    PHP_ME(PharFileInfo, __destruct,         arginfo_phar__void,         ZEND_ACC_PUBLIC)
5463    PHP_ME(PharFileInfo, chmod,              arginfo_entry_chmod,        ZEND_ACC_PUBLIC)
5464    PHP_ME(PharFileInfo, compress,           arginfo_phar_comp,          ZEND_ACC_PUBLIC)
5465    PHP_ME(PharFileInfo, decompress,         arginfo_phar__void,         ZEND_ACC_PUBLIC)
5466    PHP_ME(PharFileInfo, delMetadata,        arginfo_phar__void,         ZEND_ACC_PUBLIC)
5467    PHP_ME(PharFileInfo, getCompressedSize,  arginfo_phar__void,         ZEND_ACC_PUBLIC)
5468    PHP_ME(PharFileInfo, getCRC32,           arginfo_phar__void,         ZEND_ACC_PUBLIC)
5469    PHP_ME(PharFileInfo, getContent,         arginfo_phar__void,         ZEND_ACC_PUBLIC)
5470    PHP_ME(PharFileInfo, getMetadata,        arginfo_phar__void,         ZEND_ACC_PUBLIC)
5471    PHP_ME(PharFileInfo, getPharFlags,       arginfo_phar__void,         ZEND_ACC_PUBLIC)
5472    PHP_ME(PharFileInfo, hasMetadata,        arginfo_phar__void,         ZEND_ACC_PUBLIC)
5473    PHP_ME(PharFileInfo, isCompressed,       arginfo_phar_compo,         ZEND_ACC_PUBLIC)
5474    PHP_ME(PharFileInfo, isCRCChecked,       arginfo_phar__void,         ZEND_ACC_PUBLIC)
5475    PHP_ME(PharFileInfo, setMetadata,        arginfo_phar_setMetadata,   ZEND_ACC_PUBLIC)
5476    PHP_FE_END
5477};
5478#endif /* HAVE_SPL */
5479
5480zend_function_entry phar_exception_methods[] = {
5481    PHP_FE_END
5482};
5483/* }}} */
5484
5485#define REGISTER_PHAR_CLASS_CONST_LONG(class_name, const_name, value) \
5486    zend_declare_class_constant_long(class_name, const_name, sizeof(const_name)-1, (long)value TSRMLS_CC);
5487
5488#if PHP_VERSION_ID < 50200
5489# define phar_exception_get_default() zend_exception_get_default()
5490#else
5491# define phar_exception_get_default() zend_exception_get_default(TSRMLS_C)
5492#endif
5493
5494void phar_object_init(TSRMLS_D) /* {{{ */
5495{
5496    zend_class_entry ce;
5497
5498    INIT_CLASS_ENTRY(ce, "PharException", phar_exception_methods);
5499    phar_ce_PharException = zend_register_internal_class_ex(&ce, phar_exception_get_default(), NULL  TSRMLS_CC);
5500
5501#if HAVE_SPL
5502    INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods);
5503    phar_ce_archive = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator, NULL  TSRMLS_CC);
5504
5505    zend_class_implements(phar_ce_archive TSRMLS_CC, 2, spl_ce_Countable, zend_ce_arrayaccess);
5506
5507    INIT_CLASS_ENTRY(ce, "PharData", php_archive_methods);
5508    phar_ce_data = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator, NULL  TSRMLS_CC);
5509
5510    zend_class_implements(phar_ce_data TSRMLS_CC, 2, spl_ce_Countable, zend_ce_arrayaccess);
5511
5512    INIT_CLASS_ENTRY(ce, "PharFileInfo", php_entry_methods);
5513    phar_ce_entry = zend_register_internal_class_ex(&ce, spl_ce_SplFileInfo, NULL  TSRMLS_CC);
5514#else
5515    INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods);
5516    phar_ce_archive = zend_register_internal_class(&ce TSRMLS_CC);
5517    phar_ce_archive->ce_flags |= ZEND_ACC_FINAL_CLASS;
5518
5519    INIT_CLASS_ENTRY(ce, "PharData", php_archive_methods);
5520    phar_ce_data = zend_register_internal_class(&ce TSRMLS_CC);
5521    phar_ce_data->ce_flags |= ZEND_ACC_FINAL_CLASS;
5522#endif
5523
5524    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "BZ2", PHAR_ENT_COMPRESSED_BZ2)
5525    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "GZ", PHAR_ENT_COMPRESSED_GZ)
5526    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "NONE", PHAR_ENT_COMPRESSED_NONE)
5527    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHAR", PHAR_FORMAT_PHAR)
5528    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "TAR", PHAR_FORMAT_TAR)
5529    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "ZIP", PHAR_FORMAT_ZIP)
5530    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "COMPRESSED", PHAR_ENT_COMPRESSION_MASK)
5531    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHP", PHAR_MIME_PHP)
5532    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHPS", PHAR_MIME_PHPS)
5533    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "MD5", PHAR_SIG_MD5)
5534    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "OPENSSL", PHAR_SIG_OPENSSL)
5535    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA1", PHAR_SIG_SHA1)
5536    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA256", PHAR_SIG_SHA256)
5537    REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA512", PHAR_SIG_SHA512)
5538}
5539/* }}} */
5540
5541/*
5542 * Local variables:
5543 * tab-width: 4
5544 * c-basic-offset: 4
5545 * End:
5546 * vim600: noet sw=4 ts=4 fdm=marker
5547 * vim<600: noet sw=4 ts=4
5548 */
5549