-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathext_zip.cpp
1570 lines (1264 loc) · 44.9 KB
/
ext_zip.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <zip.h>
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/file-util.h"
#include "hphp/runtime/base/preg.h"
#include "hphp/runtime/base/stream-wrapper-registry.h"
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
#include "hphp/runtime/server/cli-server.h"
#include "hphp/runtime/vm/native-prop-handler.h"
namespace HPHP {
static String to_full_path(const String& filename) {
if (filename.charAt(0) == '/') {
return filename;
}
return HHVM_FN(getcwd)().toString() + String::FromChar('/') + filename;
}
// A wrapper for `zip_open` that prepares a full path
// file name to consider current working directory.
static zip* _zip_open(const String& filename, int _flags, int* zep) {
if (is_cli_server_mode()) {
int open_flags =
(_flags & ZIP_EXCL ? O_EXCL : 0)
| (_flags & ZIP_TRUNCATE ? O_TRUNC : 0)
| (_flags & ZIP_CREATE ? O_CREAT : 0)
| (_flags & ZIP_RDONLY ? O_RDONLY : O_RDWR);
auto fd = cli_openfd_unsafe(
filename,
open_flags,
static_cast<mode_t>(-1),
/* use_include_path */ false,
/* quiet */ true);
if (fd == -1) {
*zep = ZIP_ER_OPEN;
return nullptr;
}
if (auto z = zip_fdopen(fd, _flags & ZIP_CHECKCONS, zep)) return z;
close(fd);
return nullptr;
}
return zip_open(to_full_path(filename).c_str(), _flags, zep);
}
struct ZipStream : File {
DECLARE_RESOURCE_ALLOCATION(ZipStream);
ZipStream(zip* z, const String& name)
: File(false), m_zipFile(nullptr) {
if (name.empty()) {
return;
}
struct zip_stat zipStat;
if (zip_stat(z, name.c_str(), 0, &zipStat) != 0) {
return;
}
m_zipFile = zip_fopen(z, name.c_str(), 0);
}
~ZipStream() override { close(); }
bool open(const String&, const String&) override { return false; }
bool close(int* unused = nullptr) final {
bool noError = true;
if (!eof()) {
if (zip_fclose(m_zipFile) != 0) {
noError = false;
}
m_zipFile = nullptr;
}
return noError;
}
int64_t readImpl(char *buffer, int64_t length) override {
auto n = zip_fread(m_zipFile, buffer, length);
if (n <= 0) {
if (n == -1) {
raise_warning("Zip stream error");
n = 0;
}
close();
}
return n;
}
int64_t writeImpl(const char* /*buffer*/, int64_t /*length*/) override {
return 0;
}
bool eof() override { return m_zipFile == nullptr; }
private:
zip_file* m_zipFile;
};
void ZipStream::sweep() {
close();
File::sweep();
}
struct ZipStreamWrapper final : Stream::Wrapper {
req::ptr<File>
open(const String& filename, const String& /*mode*/, int /*options*/,
const req::ptr<StreamContext>& /*context*/) override {
std::string url(filename.c_str());
auto pound = url.find('#');
if (pound == std::string::npos) {
return nullptr;
}
// 6 is the position after zip://
auto path = url.substr(6, pound - 6);
auto file = url.substr(pound + 1);
if (path.empty() || file.empty()) {
return nullptr;
}
int err;
auto z = _zip_open(path, 0, &err);
if (z == nullptr) {
return nullptr;
}
return req::make<ZipStream>(z, file);
}
};
struct ZipDirectory : SweepableResourceData {
DECLARE_RESOURCE_ALLOCATION(ZipDirectory);
CLASSNAME_IS("ZipDirectory");
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
explicit ZipDirectory(zip *z) : m_zip(z),
m_numFiles(zip_get_num_files(z)),
m_curIndex(0) {}
~ZipDirectory() override { close(); }
bool close() {
bool noError = true;
if (isValid()) {
if (zip_close(m_zip) != 0) {
zip_discard(m_zip);
noError = false;
}
m_zip = nullptr;
}
return noError;
}
bool isValid() const {
return m_zip != nullptr;
}
Variant nextFile();
zip* getZip() {
return m_zip;
}
private:
zip* m_zip;
int m_numFiles;
int m_curIndex;
};
IMPLEMENT_RESOURCE_ALLOCATION(ZipDirectory);
struct ZipEntry : SweepableResourceData {
DECLARE_RESOURCE_ALLOCATION_NO_SWEEP(ZipEntry);
CLASSNAME_IS("ZipEntry");
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
ZipEntry(ZipDirectory* d, int index) : m_zipDir(d), m_zipFile(nullptr) {
if (zip_stat_index(d->getZip(), index, 0, &m_zipStat) == 0) {
m_zipFile = zip_fopen_index(d->getZip(), index, 0);
}
}
~ZipEntry() override { sweep(); }
void sweep() override { close(); }
bool close() {
bool noError = true;
if (isValid()) {
if (zip_fclose(m_zipFile) != 0) {
noError = false;
}
m_zipFile = nullptr;
}
return noError;
}
bool isValid() {
return m_zipFile != nullptr;
}
String read(int64_t len) {
StringBuffer sb(len);
auto buf = sb.appendCursor(len);
auto n = zip_fread(m_zipFile, buf, len);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string();
}
uint64_t getCompressedSize() {
return m_zipStat.comp_size;
}
String getCompressionMethod() {
switch (m_zipStat.comp_method) {
case 0:
return "stored";
case 1:
return "shrunk";
case 2:
case 3:
case 4:
case 5:
return "reduced";
case 6:
return "imploded";
case 7:
return "tokenized";
case 8:
return "deflated";
case 9:
return "deflatedX";
case 10:
return "implodedX";
default:
return false;
}
}
String getName() {
return m_zipStat.name;
}
uint64_t getSize() {
return m_zipStat.size;
}
private:
req::ptr<ZipDirectory> m_zipDir;
struct zip_stat m_zipStat;
zip_file* m_zipFile;
};
Variant ZipDirectory::nextFile() {
if (m_curIndex >= m_numFiles) {
return false;
}
auto zipEntry = req::make<ZipEntry>(this, m_curIndex);
if (!zipEntry->isValid()) {
return false;
}
++m_curIndex;
return Variant(std::move(zipEntry));
}
const StaticString s_ZipArchive("ZipArchive");
template<class T>
ALWAYS_INLINE
static req::ptr<T> getResource(ObjectData* obj, const char* varName) {
auto var = obj->o_get(varName, true, s_ZipArchive);
if (var.getType() == KindOfNull) {
return nullptr;
}
return cast<T>(var);
}
#define FAIL_IF_EMPTY_STRING(func, str) \
if (str.empty()) { \
raise_warning(#func "(): Empty string as source"); \
return false; \
}
#define FAIL_IF_EMPTY_STRING_ZIPARCHIVE(func, str) \
if (str.empty()) { \
raise_warning("ZipArchive::" #func "(): Empty string as source"); \
return false; \
}
#define FAIL_IF_INVALID_INDEX(index) \
if (index < 0) { \
return false; \
}
#define FAIL_IF_INVALID_PTR(ptr) \
if (ptr == nullptr) { \
return false; \
}
#define FAIL_IF_INVALID_ZIPARCHIVE(func, res) \
if (res == nullptr || !res->isValid()) { \
raise_warning("ZipArchive::" #func \
"(): Invalid or uninitialized Zip object"); \
return false; \
}
#define FAIL_IF_INVALID_ZIPDIRECTORY(func, res) \
if (!res->isValid()) { \
raise_warning(#func "(): %d is not a valid " \
"Zip Directory resource", res->getId()); \
return false; \
}
#define FAIL_IF_INVALID_ZIPENTRY(func, res) \
if (!res->isValid()) { \
raise_warning(#func "(): %d is not a valid Zip Entry resource", \
res->getId()); \
return false; \
}
//////////////////////////////////////////////////////////////////////////////
// class ZipArchive
#define TRY_GET_ZIP(this_, default) \
auto zipDir = getResource<ZipDirectory>(this_.get(), "zipDir"); \
if (zipDir == nullptr) return default; \
auto zip = zipDir->getZip();
static Variant getStatus(const Object& this_) {
TRY_GET_ZIP(this_, 0)
return zip_error_code_zip(zip_get_error(zip));
}
static Variant getStatusSys(const Object& this_) {
TRY_GET_ZIP(this_, 0);
return zip_error_code_system(zip_get_error(zip));
}
static Variant getNumFiles(const Object& this_) {
TRY_GET_ZIP(this_, 0);
return zip_get_num_files(zip);
}
static Variant getComment(const Object& this_) {
TRY_GET_ZIP(this_, empty_string_variant());
int len;
auto comment = zip_get_archive_comment(zip, &len, 0);
if (comment == nullptr) return empty_string_variant();
return String(comment, len, CopyString);
}
static Native::PropAccessor zip_archive_properties[] = {
{ "status", getStatus },
{ "statusSys", getStatusSys },
{ "numFiles", getNumFiles },
{ "comment", getComment },
{ nullptr }
};
Native::PropAccessorMap zip_archive_properties_map{zip_archive_properties};
struct ZipArchivePropHandler : Native::MapPropHandler<ZipArchivePropHandler> {
static constexpr Native::PropAccessorMap& map = zip_archive_properties_map;
};
static bool HHVM_METHOD(ZipArchive, addEmptyDir, const String& dirname) {
if (dirname.empty()) {
return false;
}
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addEmptyDir, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addEmptyDir, dirname);
std::string dirStr(dirname.c_str());
if (dirStr[dirStr.length() - 1] != '/') {
dirStr.push_back('/');
}
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), dirStr.c_str(), 0, &zipStat) != -1) {
return false;
}
if (zip_add_dir(zipDir->getZip(), dirStr.c_str()) == -1) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool addFile(zip* zipStruct, const char* source, const char* dest,
int64_t start = 0, int64_t length = 0) {
if (!HHVM_FN(is_file)(source)) {
return false;
}
auto zipSource = zip_source_file(zipStruct, source, start, length);
FAIL_IF_INVALID_PTR(zipSource);
auto index = zip_name_locate(zipStruct, dest, 0);
if (index < 0) {
if (zip_add(zipStruct, dest, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
} else {
if (zip_replace(zipStruct, index, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
}
zip_error_clear(zipStruct);
return true;
}
static bool HHVM_METHOD(ZipArchive, addFile, const String& filename,
const String& localname, int64_t start,
int64_t length) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addFile, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addFile, filename);
return addFile(zipDir->getZip(), filename.c_str(),
localname.empty() ? filename.c_str() : localname.c_str(),
start, length);
}
static bool HHVM_METHOD(ZipArchive, addFromString, const String& localname,
const String& contents) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addFromString, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addFromString, localname);
auto data = malloc(contents.length());
FAIL_IF_INVALID_PTR(data);
memcpy(data, contents.c_str(), contents.length());
auto zipSource = zip_source_buffer(zipDir->getZip(), data, contents.length(),
1); // this will free data ptr
if (zipSource == nullptr) {
free(data);
return false;
}
auto index = zip_name_locate(zipDir->getZip(), localname.c_str(), 0);
if (index < 0) {
if (zip_add(zipDir->getZip(), localname.c_str(), zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
} else {
if (zip_replace(zipDir->getZip(), index, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool addPattern(zip* zipStruct, const String& pattern, const Array& options,
std::string path, int64_t flags, bool glob) {
std::string removePath;
if (options->exists(String("remove_path"))) {
auto const rval = options->get(String("remove_path"));
if (isStringType(rval.type())) {
auto const sd = rval.val().pstr;
removePath.append(sd->data(), sd->size());
}
}
bool removeAllPath = false;
if (options->exists(String("remove_all_path"))) {
auto const rval = options->get(String("remove_all_path"));
if (isBoolType(rval.type())) {
removeAllPath = rval.val().num;
}
}
std::string addPath;
if (options->exists(String("add_path"))) {
auto const rval = options->get(String("add_path"));
if (isStringType(rval.type())) {
auto const sd = rval.val().pstr;
addPath.append(sd->data(), sd->size());
}
}
Array files;
if (glob) {
auto match = HHVM_FN(glob)(pattern, flags);
if (match.isArray()) {
files = match.asArrRef();
} else {
return false;
}
} else {
if (path[path.size() - 1] != '/') {
path.push_back('/');
}
auto allFiles = HHVM_FN(scandir)(path);
if (allFiles.isArray()) {
files = allFiles.asArrRef();
} else {
return false;
}
}
std::string dest;
auto pathLen = path.size();
for (ArrayIter it(files); it; ++it) {
auto var = it.second();
if (!var.isString()) {
return false;
}
auto source = var.asCStrRef();
if (HHVM_FN(is_dir)(source)) {
continue;
}
if (!glob) {
auto var = preg_match(pattern.get(), source.get());
if (var.isInteger()) {
if (var.asInt64Val() == 0) {
continue;
}
} else {
return false;
}
}
dest.resize(0);
dest.append(source.c_str());
if (removeAllPath) {
auto index = dest.rfind('/');
if (index != std::string::npos) {
dest.erase(0, index + 1);
}
} else if (!removePath.empty()) {
auto index = dest.find(removePath);
if (index == 0) {
dest.erase(0, removePath.size());
}
}
if (!addPath.empty()) {
dest.insert(0, addPath);
}
path.resize(pathLen);
path.append(source.c_str());
if (!addFile(zipStruct, path.c_str(), dest.c_str())) {
return false;
}
}
zip_error_clear(zipStruct);
return true;
}
static bool HHVM_METHOD(ZipArchive, addGlob, const String& pattern,
int64_t flags, const Array& options) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addGlob, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addGlob, pattern);
return addPattern(zipDir->getZip(), pattern, options, "", flags, true);
}
static bool HHVM_METHOD(ZipArchive, addPattern, const String& pattern,
const String& path, const Array& options) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addPattern, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addPattern, pattern);
return addPattern(zipDir->getZip(), pattern, options, path.c_str(), 0, false);
}
static bool HHVM_METHOD(ZipArchive, close) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(close, zipDir);
bool ret = zipDir->close();
this_->o_set("zipDir", null_resource, s_ZipArchive);
return ret;
}
static bool HHVM_METHOD(ZipArchive, deleteIndex, int64_t index) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(deleteIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (zip_delete(zipDir->getZip(), index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, deleteName, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(deleteName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(deleteName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_delete(zipDir->getZip(), zipStat.index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
// Make the path relative to "." by flattening.
// This function is named the same and similar in implementation to that in
// php-src:php_zip.c
// One difference is that we canonicalize here whereas php-src is already
// assumed passed a canonicalized path.
static std::string make_relative_path(const std::string& path) {
if (path.empty()) {
return path;
}
// First get the path to a state where we don't have .. in the middle of it
// etc. canonicalize handles Windows paths too.
std::string canonical(FileUtil::canonicalize(path));
// If we have a slash at the beginning, then just remove it and we are
// relative. This check will hold because we have canonicalized the
// path above to remove .. from the path, so we know we can be sure
// we are at a good place for this check.
if (FileUtil::isDirSeparator(canonical[0])) {
return canonical.substr(1);
}
// If we get here, canonical looks something like:
// a/b/c
// Search through the path and if we find a place where we have a slash
// and a "." just before that slash, then cut the path off right there
// and just take everything after the slash.
std::string relative(canonical);
int idx = canonical.length() - 1;
while (1) {
while (idx > 0 && !(FileUtil::isDirSeparator(canonical[idx]))) {
idx--;
}
// If we ever get to idx == 0, then there were no other slashes to deal with
if (idx == 0) {
return canonical;
}
if (idx >= 1 && (canonical[idx - 1] == '.' || canonical[idx - 1] == ':')) {
relative = canonical.substr(idx + 1);
break;
}
idx--;
}
return relative;
}
static bool extractFileTo(zip* zip, const std::string &file, std::string& to,
char* buf, size_t len) {
struct zip_stat zipStat;
// Verify the file to be extracted is actually in the zip file
if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {
return false;
}
auto clean_file = file;
auto sep = std::string::npos;
// Normally would just use std::string::rfind here, but if we want to be
// consistent between Windows and Linux, even if techincally Linux won't use
// backslash for a separator, we are checking for both types.
int idx = file.length() - 1;
while (idx >= 0) {
if (FileUtil::isDirSeparator(file[idx])) {
sep = idx;
break;
}
idx--;
}
if (sep != std::string::npos) {
// make_relative_path so we do not try to put files or dirs in bad
// places. This securely "cleans" the file.
clean_file = make_relative_path(file);
std::string path = to + clean_file;
bool is_dir_only = true;
if (sep < file.length() - 1) { // not just a directory
auto clean_file_dir = HHVM_FN(dirname)(clean_file);
path = to + clean_file_dir.toCppString();
is_dir_only = false;
}
// Make sure the directory path to extract to exists or can be created
if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {
return false;
}
// If we have a good directory to extract to above, we now check whether
// the "file" parameter passed in is a directory or actually a file.
if (is_dir_only) { // directory, like /usr/bin/
return true;
}
// otherwise file is actually a file, so we actually extract.
}
// We have ensured that clean_file will be added to a relative path by the
// time we get here.
to.append(clean_file);
auto zipFile = zip_fopen_index(zip, zipStat.index, 0);
FAIL_IF_INVALID_PTR(zipFile);
auto stream = Stream::getWrapperFromURI(to);
if (stream == nullptr) {
zip_fclose(zipFile);
return false;
}
auto outFile = stream->open(to, "wb", 0, nullptr);
if (outFile == nullptr) {
zip_fclose(zipFile);
return false;
}
for (auto n = zip_fread(zipFile, buf, len); n != 0;
n = zip_fread(zipFile, buf, len)) {
if (n < 0
|| outFile->write(String(buf, n, CopyStringMode::CopyString)) != n) {
zip_fclose(zipFile);
outFile->close();
remove(to.c_str());
return false;
}
}
zip_fclose(zipFile);
return outFile->close();
}
static bool HHVM_METHOD(ZipArchive, extractTo, const String& destination,
const Variant& entries) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(extractTo, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(extractTo, destination);
auto fileCount = zip_get_num_files(zipDir->getZip());
if (fileCount == -1) {
raise_warning("Illegal archive");
return false;
}
std::string to(destination.c_str());
if (to[to.size() - 1] != '/') {
to.push_back('/');
}
if (!HHVM_FN(is_dir)(to) && !HHVM_FN(mkdir)(to)) {
return false;
}
char buf[1024];
auto toSize = to.size();
if (entries.isString()) {
// extract only this file
if (!extractFileTo(zipDir->getZip(), entries.asCStrRef().c_str(),
to, buf, sizeof(buf))) {
return false;
}
} else if (entries.isArray() && entries.asCArrRef().size() != 0) {
// extract ones in the array
for (ArrayIter it(entries.asCArrRef()); it; ++it) {
auto var = it.second();
if (!var.isString() || !extractFileTo(zipDir->getZip(),
var.asCStrRef().c_str(),
to, buf, sizeof(buf))) {
return false;
}
to.resize(toSize);
}
} else {
// extract all files
for (decltype(fileCount) index = 0; index < fileCount; ++index) {
auto file = zip_get_name(zipDir->getZip(), index, ZIP_FL_UNCHANGED);
if (file == nullptr ||
!extractFileTo(zipDir->getZip(), file, to, buf, sizeof(buf))) {
return false;
}
to.resize(toSize);
}
}
zip_error_clear(zipDir->getZip());
return true;
}
static Variant HHVM_METHOD(ZipArchive, getArchiveComment, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getArchiveComment, zipDir);
int len;
auto comment = zip_get_archive_comment(zipDir->getZip(), &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getCommentIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getCommentIndex, zipDir);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
int len;
auto comment = zip_get_file_comment(zipDir->getZip(), index, &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getCommentName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getCommentName, zipDir);
if (name.empty()) {
raise_notice("ZipArchive::getCommentName(): Empty string as source");
return false;
}
int index = zip_name_locate(zipDir->getZip(), name.c_str(), 0);
if (index != 0) {
return false;
}
int len;
auto comment = zip_get_file_comment(zipDir->getZip(), index, &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getFromIndex, int64_t index,
int64_t length, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getFromIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (length < 0) {
return empty_string_variant();
}
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
if (zipStat.size < 1) {
return empty_string_variant();
}
auto zipFile = zip_fopen_index(zipDir->getZip(), index, flags);
FAIL_IF_INVALID_PTR(zipFile);
if (length == 0) {
length = zipStat.size;
}
StringBuffer sb(length);
auto buf = sb.appendCursor(length);
auto n = zip_fread(zipFile, buf, length);
zip_fclose(zipFile);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string_variant();
}
static Variant HHVM_METHOD(ZipArchive, getFromName, const String& name,
int64_t length, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getFromName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(getFromName, name);
if (length < 0) {
return empty_string_variant();
}
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), flags, &zipStat) != 0) {
return false;
}
if (zipStat.size < 1) {
return empty_string_variant();
}
auto zipFile = zip_fopen(zipDir->getZip(), name.c_str(), flags);
FAIL_IF_INVALID_PTR(zipFile);
if (length == 0) {
length = zipStat.size;
}
StringBuffer sb(length);
auto buf = sb.appendCursor(length);
auto n = zip_fread(zipFile, buf, length);
zip_fclose(zipFile);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string_variant();
}
static Variant HHVM_METHOD(ZipArchive, getNameIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getNameIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
auto name = zip_get_name(zipDir->getZip(), index, flags);
FAIL_IF_INVALID_PTR(name);
return String(name, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getStatusString) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getStatusString, zipDir);
int zep, sep, len;
zip_error_get(zipDir->getZip(), &zep, &sep);
char error_string[128];