Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/misc/zipfile.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / misc / zipfile.c` 2326 lines ยท 69373 bytes Raw Blame History 1 /* 2 ** 2017-12-26 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ****************************************************************************** 12 ** 13 ** This file implements a virtual table for reading and writing ZIP archive 14 ** files. 15 ** 16 ** Usage example: 17 ** 18 ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename); 19 ** 20 ** Current limitations: 21 ** 22 ** * No support for encryption 23 ** * No support for ZIP archives spanning multiple files 24 ** * No support for zip64 extensions 25 ** * Only the "inflate/deflate" (zlib) compression method is supported 26 ** * No support for transactions. ROLLBACK is the same as COMMIT. 27 ** A crash mid-transaction can leave the ZIP archive in a corrupt state. 28 */ 29 #include "sqlite3ext.h" 30 SQLITE_EXTENSION_INIT1 31 #include 32 #include 33 #include 34 #ifndef SQLITE_NO_STDINT 35 # include 36 #endif 37 38 #include 39 40 /* When used as part of the CLI, the sqlite3_stdio.h module will have 41 ** been included before this one. In that case use the sqlite3_stdio.h 42 ** #defines. If not, create our own for fopen(). 43 */ 44 #ifndef _SQLITE3_STDIO_H_ 45 # define sqlite3_fopen fopen 46 #endif 47 48 #ifndef SQLITE_OMIT_VIRTUALTABLE 49 50 #ifndef SQLITE_AMALGAMATION 51 52 #ifndef UINT32_TYPE 53 # ifdef HAVE_UINT32_T 54 # define UINT32_TYPE uint32_t 55 # else 56 # define UINT32_TYPE unsigned int 57 # endif 58 #endif 59 #ifndef UINT16_TYPE 60 # ifdef HAVE_UINT16_T 61 # define UINT16_TYPE uint16_t 62 # else 63 # define UINT16_TYPE unsigned short int 64 # endif 65 #endif 66 typedef sqlite3_int64 i64; 67 typedef unsigned char u8; 68 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ 69 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ 70 #define MIN(a,b) ((a)<(b) ? (a) : (b)) 71 72 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) 73 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1 74 #endif 75 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS) 76 # define ALWAYS(X) (1) 77 # define NEVER(X) (0) 78 #elif !defined(NDEBUG) 79 # define ALWAYS(X) ((X)?1:(assert(0),0)) 80 # define NEVER(X) ((X)?(assert(0),1):0) 81 #else 82 # define ALWAYS(X) (X) 83 # define NEVER(X) (X) 84 #endif 85 86 #endif /* SQLITE_AMALGAMATION */ 87 88 /* 89 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. 90 ** 91 ** In some ways it would be better to obtain these values from system 92 ** header files. But, the dependency is undesirable and (a) these 93 ** have been stable for decades, (b) the values are part of POSIX and 94 ** are also made explicit in [man stat], and (c) are part of the 95 ** file format for zip archives. 96 */ 97 #ifndef S_IFDIR 98 # define S_IFDIR `0040000` 99 #endif 100 #ifndef S_IFREG 101 # define S_IFREG `0100000` 102 #endif 103 #ifndef S_IFLNK 104 # define S_IFLNK `0120000` 105 #endif 106 107 static const char ZIPFILE_SCHEMA[] = 108 "CREATE TABLE y(" 109 "name PRIMARY KEY," /* 0: Name of file in zip archive */ 110 "mode," /* 1: POSIX mode for file */ 111 "mtime," /* 2: Last modification time (secs since 1970)*/ 112 "sz," /* 3: Size of object */ 113 "rawdata," /* 4: Raw data */ 114 "data," /* 5: Uncompressed data */ 115 "method," /* 6: Compression method (integer) */ 116 "z HIDDEN" /* 7: Name of zip file */ 117 ") WITHOUT ROWID;"; 118 119 #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ 120 #define ZIPFILE_MX_NAME (250) /* Windows limitation on filename size */ 121 #define ZIPFILE_MX_ENTRY (65535) /* Max entries without zip64 extensions */ 122 123 /* 124 ** The buffer should be large enough to contain 3 65536 byte strings - the 125 ** filename, the extra field and the file comment. 126 */ 127 #define ZIPFILE_BUFFER_SIZE (200*1024) 128 129 130 /* 131 ** Magic numbers used to read and write zip files. 132 ** 133 ** ZIPFILE_NEWENTRY_MADEBY: 134 ** Use this value for the "version-made-by" field in new zip file 135 ** entries. The upper byte indicates "unix", and the lower byte 136 ** indicates that the zip file matches pkzip specification 3.0. 137 ** This is what info-zip seems to do. 138 ** 139 ** ZIPFILE_NEWENTRY_REQUIRED: 140 ** Value for "version-required-to-extract" field of new entries. 141 ** Version 2.0 is required to support folders and deflate compression. 142 ** 143 ** ZIPFILE_NEWENTRY_FLAGS: 144 ** Value for "general-purpose-bit-flags" field of new entries. Bit 145 ** 11 means "utf-8 filename and comment". 146 ** 147 ** ZIPFILE_SIGNATURE_CDS: 148 ** First 4 bytes of a valid CDS record. 149 ** 150 ** ZIPFILE_SIGNATURE_LFH: 151 ** First 4 bytes of a valid LFH record. 152 ** 153 ** ZIPFILE_SIGNATURE_EOCD 154 ** First 4 bytes of a valid EOCD record. 155 */ 156 #define ZIPFILE_EXTRA_TIMESTAMP 0x5455 157 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) 158 #define ZIPFILE_NEWENTRY_REQUIRED 20 159 #define ZIPFILE_NEWENTRY_FLAGS 0x800 160 #define ZIPFILE_SIGNATURE_CDS 0x02014b50 161 #define ZIPFILE_SIGNATURE_LFH 0x04034b50 162 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50 163 164 /* 165 ** The sizes of the fixed-size part of each of the three main data 166 ** structures in a zip archive. 167 */ 168 #define ZIPFILE_LFH_FIXED_SZ 30 169 #define ZIPFILE_EOCD_FIXED_SZ 22 170 #define ZIPFILE_CDS_FIXED_SZ 46 171 172 /* 173 *** 4.3.16 End of central directory record: 174 *** 175 *** end of central dir signature 4 bytes (0x06054b50) 176 *** number of this disk 2 bytes 177 *** number of the disk with the 178 *** start of the central directory 2 bytes 179 *** total number of entries in the 180 *** central directory on this disk 2 bytes 181 *** total number of entries in 182 *** the central directory 2 bytes 183 *** size of the central directory 4 bytes 184 *** offset of start of central 185 *** directory with respect to 186 *** the starting disk number 4 bytes 187 *** .ZIP file comment length 2 bytes 188 *** .ZIP file comment (variable size) 189 */ 190 typedef struct ZipfileEOCD ZipfileEOCD; 191 struct ZipfileEOCD { 192 u16 iDisk; 193 u16 iFirstDisk; 194 u16 nEntry; 195 u16 nEntryTotal; 196 u32 nSize; 197 u32 iOffset; 198 }; 199 200 /* 201 *** 4.3.12 Central directory structure: 202 *** 203 *** ... 204 *** 205 *** central file header signature 4 bytes (0x02014b50) 206 *** version made by 2 bytes 207 *** version needed to extract 2 bytes 208 *** general purpose bit flag 2 bytes 209 *** compression method 2 bytes 210 *** last mod file time 2 bytes 211 *** last mod file date 2 bytes 212 *** crc-32 4 bytes 213 *** compressed size 4 bytes 214 *** uncompressed size 4 bytes 215 *** file name length 2 bytes 216 *** extra field length 2 bytes 217 *** file comment length 2 bytes 218 *** disk number start 2 bytes 219 *** internal file attributes 2 bytes 220 *** external file attributes 4 bytes 221 *** relative offset of local header 4 bytes 222 */ 223 typedef struct ZipfileCDS ZipfileCDS; 224 struct ZipfileCDS { 225 u16 iVersionMadeBy; 226 u16 iVersionExtract; 227 u16 flags; 228 u16 iCompression; 229 u16 mTime; 230 u16 mDate; 231 u32 crc32; 232 u32 szCompressed; 233 u32 szUncompressed; 234 u16 nFile; 235 u16 nExtra; 236 u16 nComment; 237 u16 iDiskStart; 238 u16 iInternalAttr; 239 u32 iExternalAttr; 240 u32 iOffset; 241 char *zFile; /* Filename (sqlite3_malloc()) */ 242 }; 243 244 /* 245 *** 4.3.7 Local file header: 246 *** 247 *** local file header signature 4 bytes (0x04034b50) 248 *** version needed to extract 2 bytes 249 *** general purpose bit flag 2 bytes 250 *** compression method 2 bytes 251 *** last mod file time 2 bytes 252 *** last mod file date 2 bytes 253 *** crc-32 4 bytes 254 *** compressed size 4 bytes 255 *** uncompressed size 4 bytes 256 *** file name length 2 bytes 257 *** extra field length 2 bytes 258 *** 259 */ 260 typedef struct ZipfileLFH ZipfileLFH; 261 struct ZipfileLFH { 262 u16 iVersionExtract; 263 u16 flags; 264 u16 iCompression; 265 u16 mTime; 266 u16 mDate; 267 u32 crc32; 268 u32 szCompressed; 269 u32 szUncompressed; 270 u16 nFile; 271 u16 nExtra; 272 }; 273 274 typedef struct ZipfileEntry ZipfileEntry; 275 struct ZipfileEntry { 276 ZipfileCDS cds; /* Parsed CDS record */ 277 u32 mUnixTime; /* Modification time, in UNIX format */ 278 u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ 279 i64 iDataOff; /* Offset to data in file (if aData==0) */ 280 u8 *aData; /* cds.szCompressed bytes of compressed data */ 281 ZipfileEntry *pNext; /* Next element in in-memory CDS */ 282 }; 283 284 /* 285 ** Cursor type for zipfile tables. 286 */ 287 typedef struct ZipfileCsr ZipfileCsr; 288 struct ZipfileCsr { 289 sqlite3_vtab_cursor base; /* Base class - must be first */ 290 i64 iId; /* Cursor ID */ 291 u8 bEof; /* True when at EOF */ 292 u8 bNoop; /* If next xNext() call is no-op */ 293 294 /* Used outside of write transactions */ 295 FILE *pFile; /* Zip file */ 296 i64 iNextOff; /* Offset of next record in central directory */ 297 ZipfileEOCD eocd; /* Parse of central directory record */ 298 299 ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ 300 ZipfileEntry *pCurrent; /* Current entry */ 301 ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ 302 }; 303 304 typedef struct ZipfileTab ZipfileTab; 305 struct ZipfileTab { 306 sqlite3_vtab base; /* Base class - must be first */ 307 char *zFile; /* Zip file this table accesses (may be NULL) */ 308 sqlite3 *db; /* Host database connection */ 309 u8 *aBuffer; /* Temporary buffer used for various tasks */ 310 311 ZipfileCsr *pCsrList; /* List of cursors */ 312 i64 iNextCsrid; 313 314 /* The following are used by write transactions only */ 315 ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ 316 ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ 317 FILE *pWriteFd; /* File handle open on zip archive */ 318 i64 szCurrent; /* Current size of zip archive */ 319 i64 szOrig; /* Size of archive at start of transaction */ 320 }; 321 322 /* 323 ** Set the error message contained in context ctx to the results of 324 ** vprintf(zFmt, ...). 325 */ 326 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ 327 char *zMsg = 0; 328 va_list ap; 329 va_start(ap, zFmt); 330 zMsg = sqlite3_vmprintf(zFmt, ap); 331 sqlite3_result_error(ctx, zMsg, -1); 332 sqlite3_free(zMsg); 333 va_end(ap); 334 } 335 336 /* 337 ** If string zIn is quoted, dequote it in place. Otherwise, if the string 338 ** is not quoted, do nothing. 339 */ 340 static void zipfileDequote(char *zIn){ 341 char q = zIn[0]; 342 if( q=='"' || q=='\'' || q=='`' || q=='[' ){ 343 int iIn = 1; 344 int iOut = 0; 345 if( q=='[' ) q = ']'; 346 while( ALWAYS(zIn[iIn]) ){ 347 char c = zIn[iIn++]; 348 if( c==q && zIn[iIn++]!=q ) break; 349 zIn[iOut++] = c; 350 } 351 zIn[iOut] = '\0'; 352 } 353 } 354 355 /* 356 ** Construct a new ZipfileTab virtual table object. 357 ** 358 ** argv[0] -> module name ("zipfile") 359 ** argv[1] -> database name 360 ** argv[2] -> table name 361 ** argv[...] -> "column name" and other module argument fields. 362 */ 363 static int zipfileConnect( 364 sqlite3 *db, 365 void *pAux, 366 int argc, const char *const*argv, 367 sqlite3_vtab **ppVtab, 368 char **pzErr 369 ){ 370 int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; 371 int nFile = 0; 372 const char *zFile = 0; 373 ZipfileTab *pNew = 0; 374 int rc; 375 (void)pAux; 376 377 /* If the table name is not "zipfile", require that the argument be 378 ** specified. This stops zipfile tables from being created as: 379 ** 380 ** CREATE VIRTUAL TABLE zzz USING zipfile(); 381 ** 382 ** It does not prevent: 383 ** 384 ** CREATE VIRTUAL TABLE zipfile USING zipfile(); 385 */ 386 assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); 387 if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ 388 *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); 389 return SQLITE_ERROR; 390 } 391 392 if( argc>3 ){ 393 zFile = argv[3]; 394 nFile = (int)strlen(zFile)+1; 395 } 396 397 rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); 398 if( rc==SQLITE_OK ){ 399 pNew = (ZipfileTab*)sqlite3_malloc64((i64)nByte+nFile); 400 if( pNew==0 ) return SQLITE_NOMEM; 401 memset(pNew, 0, nByte+nFile); 402 pNew->db = db; 403 pNew->aBuffer = (u8*)&pNew[1]; 404 if( zFile ){ 405 pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; 406 memcpy(pNew->zFile, zFile, nFile); 407 zipfileDequote(pNew->zFile); 408 } 409 } 410 sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); 411 *ppVtab = (sqlite3_vtab*)pNew; 412 return rc; 413 } 414 415 /* 416 ** Free the ZipfileEntry structure indicated by the only argument. 417 */ 418 static void zipfileEntryFree(ZipfileEntry *p){ 419 if( p ){ 420 sqlite3_free(p->cds.zFile); 421 sqlite3_free(p); 422 } 423 } 424 425 /* 426 ** Release resources that should be freed at the end of a write 427 ** transaction. 428 */ 429 static void zipfileCleanupTransaction(ZipfileTab *pTab){ 430 ZipfileEntry *pEntry; 431 ZipfileEntry *pNext; 432 433 if( pTab->pWriteFd ){ 434 fclose(pTab->pWriteFd); 435 pTab->pWriteFd = 0; 436 } 437 for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ 438 pNext = pEntry->pNext; 439 zipfileEntryFree(pEntry); 440 } 441 pTab->pFirstEntry = 0; 442 pTab->pLastEntry = 0; 443 pTab->szCurrent = 0; 444 pTab->szOrig = 0; 445 } 446 447 /* 448 ** This method is the destructor for zipfile vtab objects. 449 */ 450 static int zipfileDisconnect(sqlite3_vtab *pVtab){ 451 zipfileCleanupTransaction((ZipfileTab*)pVtab); 452 sqlite3_free(pVtab); 453 return SQLITE_OK; 454 } 455 456 /* 457 ** Constructor for a new ZipfileCsr object. 458 */ 459 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ 460 ZipfileTab *pTab = (ZipfileTab*)p; 461 ZipfileCsr *pCsr; 462 pCsr = sqlite3_malloc64(sizeof(*pCsr)); 463 *ppCsr = (sqlite3_vtab_cursor*)pCsr; 464 if( pCsr==0 ){ 465 return SQLITE_NOMEM; 466 } 467 memset(pCsr, 0, sizeof(*pCsr)); 468 pCsr->iId = ++pTab->iNextCsrid; 469 pCsr->pCsrNext = pTab->pCsrList; 470 pTab->pCsrList = pCsr; 471 return SQLITE_OK; 472 } 473 474 /* 475 ** Reset a cursor back to the state it was in when first returned 476 ** by zipfileOpen(). 477 */ 478 static void zipfileResetCursor(ZipfileCsr *pCsr){ 479 ZipfileEntry *p; 480 ZipfileEntry *pNext; 481 482 pCsr->bEof = 0; 483 if( pCsr->pFile ){ 484 fclose(pCsr->pFile); 485 pCsr->pFile = 0; 486 zipfileEntryFree(pCsr->pCurrent); 487 pCsr->pCurrent = 0; 488 } 489 490 for(p=pCsr->pFreeEntry; p; p=pNext){ 491 pNext = p->pNext; 492 zipfileEntryFree(p); 493 } 494 pCsr->pFreeEntry = 0; 495 } 496 497 /* 498 ** Destructor for an ZipfileCsr. 499 */ 500 static int zipfileClose(sqlite3_vtab_cursor *cur){ 501 ZipfileCsr *pCsr = (ZipfileCsr*)cur; 502 ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); 503 ZipfileCsr **pp; 504 zipfileResetCursor(pCsr); 505 506 /* Remove this cursor from the ZipfileTab.pCsrList list. */ 507 for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); 508 *pp = pCsr->pCsrNext; 509 510 sqlite3_free(pCsr); 511 return SQLITE_OK; 512 } 513 514 /* 515 ** Set the error message for the virtual table associated with cursor 516 ** pCsr to the results of vprintf(zFmt, ...). 517 */ 518 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ 519 va_list ap; 520 va_start(ap, zFmt); 521 sqlite3_free(pTab->base.zErrMsg); 522 pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); 523 va_end(ap); 524 } 525 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ 526 va_list ap; 527 va_start(ap, zFmt); 528 sqlite3_free(pCsr->base.pVtab->zErrMsg); 529 pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); 530 va_end(ap); 531 } 532 533 /* 534 ** Read nRead bytes of data from offset iOff of file pFile into buffer 535 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code 536 ** otherwise. 537 ** 538 ** If an error does occur, output variable (*pzErrmsg) may be set to point 539 ** to an English language error message. It is the responsibility of the 540 ** caller to eventually free this buffer using 541 ** sqlite3_free(). 542 */ 543 static int zipfileReadData( 544 FILE *pFile, /* Read from this file */ 545 u8 *aRead, /* Read into this buffer */ 546 i64 nRead, /* Number of bytes to read */ 547 i64 iOff, /* Offset to read from */ 548 char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ 549 ){ 550 size_t n; 551 fseek(pFile, (long)iOff, SEEK_SET); 552 n = fread(aRead, 1, (long)nRead, pFile); 553 if( n!=(size_t)nRead ){ 554 sqlite3_free(*pzErrmsg); 555 *pzErrmsg = sqlite3_mprintf("error in fread()"); 556 return SQLITE_ERROR; 557 } 558 return SQLITE_OK; 559 } 560 561 static int zipfileAppendData( 562 ZipfileTab *pTab, 563 const u8 *aWrite, 564 int nWrite 565 ){ 566 if( nWrite>0 ){ 567 size_t n = nWrite; 568 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); 569 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); 570 if( (int)n!=nWrite ){ 571 zipfileTableErr(pTab,"error in fwrite()"); 572 return SQLITE_ERROR; 573 } 574 pTab->szCurrent += nWrite; 575 } 576 return SQLITE_OK; 577 } 578 579 /* 580 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. 581 */ 582 static u16 zipfileGetU16(const u8 *aBuf){ 583 return (aBuf[1] << 8) + aBuf[0]; 584 } 585 586 /* 587 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. 588 */ 589 static u32 zipfileGetU32(const u8 *aBuf){ 590 if( aBuf==0 ) return 0; 591 return ((u32)(aBuf[3]) << 24) 592 + ((u32)(aBuf[2]) << 16) 593 + ((u32)(aBuf[1]) << 8) 594 + ((u32)(aBuf[0]) << 0); 595 } 596 597 /* 598 ** Write a 16-bit little endiate integer into buffer aBuf. 599 */ 600 static void zipfilePutU16(u8 *aBuf, u16 val){ 601 aBuf[0] = val & 0xFF; 602 aBuf[1] = (val>>8) & 0xFF; 603 } 604 605 /* 606 ** Write a 32-bit little endiate integer into buffer aBuf. 607 */ 608 static void zipfilePutU32(u8 *aBuf, u32 val){ 609 aBuf[0] = val & 0xFF; 610 aBuf[1] = (val>>8) & 0xFF; 611 aBuf[2] = (val>>16) & 0xFF; 612 aBuf[3] = (val>>24) & 0xFF; 613 } 614 615 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) 616 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) 617 618 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } 619 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } 620 621 /* 622 ** Magic numbers used to read CDS records. 623 */ 624 #define ZIPFILE_CDS_NFILE_OFF 28 625 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 626 627 /* 628 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR 629 ** if the record is not well-formed, or SQLITE_OK otherwise. 630 */ 631 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ 632 u8 *aRead = aBuf; 633 u32 sig = zipfileRead32(aRead); 634 int rc = SQLITE_OK; 635 if( sig!=ZIPFILE_SIGNATURE_CDS ){ 636 rc = SQLITE_ERROR; 637 }else{ 638 pCDS->iVersionMadeBy = zipfileRead16(aRead); 639 pCDS->iVersionExtract = zipfileRead16(aRead); 640 pCDS->flags = zipfileRead16(aRead); 641 pCDS->iCompression = zipfileRead16(aRead); 642 pCDS->mTime = zipfileRead16(aRead); 643 pCDS->mDate = zipfileRead16(aRead); 644 pCDS->crc32 = zipfileRead32(aRead); 645 pCDS->szCompressed = zipfileRead32(aRead); 646 pCDS->szUncompressed = zipfileRead32(aRead); 647 assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); 648 pCDS->nFile = zipfileRead16(aRead); 649 pCDS->nExtra = zipfileRead16(aRead); 650 pCDS->nComment = zipfileRead16(aRead); 651 pCDS->iDiskStart = zipfileRead16(aRead); 652 pCDS->iInternalAttr = zipfileRead16(aRead); 653 pCDS->iExternalAttr = zipfileRead32(aRead); 654 pCDS->iOffset = zipfileRead32(aRead); 655 assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); 656 } 657 658 return rc; 659 } 660 661 /* 662 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR 663 ** if the record is not well-formed, or SQLITE_OK otherwise. 664 */ 665 static int zipfileReadLFH( 666 u8 *aBuffer, 667 ZipfileLFH *pLFH 668 ){ 669 u8 *aRead = aBuffer; 670 int rc = SQLITE_OK; 671 672 u32 sig = zipfileRead32(aRead); 673 if( sig!=ZIPFILE_SIGNATURE_LFH ){ 674 rc = SQLITE_ERROR; 675 }else{ 676 pLFH->iVersionExtract = zipfileRead16(aRead); 677 pLFH->flags = zipfileRead16(aRead); 678 pLFH->iCompression = zipfileRead16(aRead); 679 pLFH->mTime = zipfileRead16(aRead); 680 pLFH->mDate = zipfileRead16(aRead); 681 pLFH->crc32 = zipfileRead32(aRead); 682 pLFH->szCompressed = zipfileRead32(aRead); 683 pLFH->szUncompressed = zipfileRead32(aRead); 684 pLFH->nFile = zipfileRead16(aRead); 685 pLFH->nExtra = zipfileRead16(aRead); 686 if( pLFH->nFile>ZIPFILE_MX_NAME ) rc = SQLITE_ERROR; 687 } 688 return rc; 689 } 690 691 692 /* 693 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. 694 ** Scan through this buffer to find an "extra-timestamp" field. If one 695 ** exists, extract the 32-bit modification-timestamp from it and store 696 ** the value in output parameter *pmTime. 697 ** 698 ** Zero is returned if no extra-timestamp record could be found (and so 699 ** *pmTime is left unchanged), or non-zero otherwise. 700 ** 701 ** The general format of an extra field is: 702 ** 703 ** Header ID 2 bytes 704 ** Data Size 2 bytes 705 ** Data N bytes 706 */ 707 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ 708 int ret = 0; 709 u8 *p = aExtra; 710 u8 *pEnd = &aExtra[nExtra]; 711 712 /* Stop when there are less than 9 bytes left to scan in the buffer. This 713 ** is because the timestamp field requires exactly 9 bytes - 4 bytes of 714 ** header fields and 5 bytes of data. If there are less than 9 bytes 715 ** remaining, either it is some other field or else the extra data 716 ** is corrupt. Either way, do not process it. */ 717 while( p+(2*sizeof(u16) + 1 + sizeof(u32))<=pEnd ){ 718 u16 id = zipfileRead16(p); 719 u16 nByte = zipfileRead16(p); 720 721 switch( id ){ 722 case ZIPFILE_EXTRA_TIMESTAMP: { 723 u8 b = p[0]; 724 if( b & 0x01 ){ /* 0x01 -> modtime is present */ 725 *pmTime = zipfileGetU32(&p[1]); 726 ret = 1; 727 } 728 break; 729 } 730 } 731 732 p += nByte; 733 } 734 return ret; 735 } 736 737 /* 738 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate 739 ** fields of the CDS structure passed as the only argument to a 32-bit 740 ** UNIX seconds-since-the-epoch timestamp. Return the result. 741 ** 742 ** "Standard" MS-DOS time format: 743 ** 744 ** File modification time: 745 ** Bits 00-04: seconds divided by 2 746 ** Bits 05-10: minute 747 ** Bits 11-15: hour 748 ** File modification date: 749 ** Bits 00-04: day 750 ** Bits 05-08: month (1-12) 751 ** Bits 09-15: years from 1980 752 ** 753 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx 754 */ 755 static u32 zipfileMtime(ZipfileCDS *pCDS){ 756 int Y,M,D,X1,X2,A,B,sec,min,hr; 757 i64 JDsec; 758 Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); 759 M = ((pCDS->mDate >> 5) & 0x0F); 760 D = (pCDS->mDate & 0x1F); 761 sec = (pCDS->mTime & 0x1F)*2; 762 min = (pCDS->mTime >> 5) & 0x3F; 763 hr = (pCDS->mTime >> 11) & 0x1F; 764 if( M<=2 ){ 765 Y--; 766 M += 12; 767 } 768 X1 = 36525*(Y+4716)/100; 769 X2 = 306001*(M+1)/10000; 770 A = Y/100; 771 B = 2 - A + (A/4); 772 JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec; 773 return (u32)(JDsec - (i64)`24405875`*(i64)8640); 774 } 775 776 /* 777 ** The opposite of zipfileMtime(). This function populates the mTime and 778 ** mDate fields of the CDS structure passed as the first argument according 779 ** to the UNIX timestamp value passed as the second. 780 */ 781 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ 782 /* Convert unix timestamp to JD (`2440588` is noon on 1/1/1970) */ 783 i64 JD = (i64)`2440588` + mUnixTime / (24*60*60); 784 785 int A, B, C, D, E; 786 int yr, mon, day; 787 int hr, min, sec; 788 789 if( mUnixTime<=`315532800` ){ 790 /* Experimentally, I find that Win11 will not report the modification 791 ** time for any ZIP file entry with a date before 1980-01-01 00:00:01. 792 ** So make that the minimum date-time value. */ 793 pCds->mDate = 0x0021; 794 pCds->mTime = 0x0001; 795 return; 796 } 797 798 A = (int)((JD - `1867216`.25)/36524.25); 799 A = (int)(JD + 1 + A - (A/4)); 800 B = A + 1524; 801 C = (int)((B - 122.1)/365.25); 802 D = (36525*(C&32767))/100; 803 E = (int)((B-D)/30.6001); 804 805 day = B - D - (int)(30.6001*E); 806 mon = (E<14 ? E-1 : E-13); 807 yr = mon>2 ? C-4716 : C-4715; 808 809 hr = (mUnixTime % (24*60*60)) / (60*60); 810 min = (mUnixTime % (60*60)) / 60; 811 sec = (mUnixTime % 60); 812 813 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); 814 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); 815 816 assert( mUnixTime==zipfileMtime(pCds) 817 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) 818 ); 819 } 820 821 /* 822 ** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a 823 ** generic corruption message and return SQLITE_CORRUPT; 824 */ 825 static int zipfileCorrupt(char **pzErr){ 826 sqlite3_free(*pzErr); 827 *pzErr = sqlite3_mprintf("zip archive is corrupt"); 828 return SQLITE_CORRUPT; 829 } 830 831 /* 832 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in 833 ** size) containing an entire zip archive image. Or, if aBlob is NULL, 834 ** then pFile is a file-handle open on a zip file. In either case, this 835 ** function creates a ZipfileEntry object based on the zip archive entry 836 ** for which the CDS record is at offset iOff. 837 ** 838 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to 839 ** the new object. Otherwise, an SQLite error code is returned and the 840 ** final value of (*ppEntry) undefined. 841 */ 842 static int zipfileGetEntry( 843 ZipfileTab *pTab, /* Store any error message here */ 844 const u8 *aBlob, /* Pointer to in-memory file image */ 845 i64 nBlob, /* Size of aBlob[] in bytes */ 846 FILE *pFile, /* If aBlob==0, read from this file */ 847 i64 iOff, /* Offset of CDS record */ 848 ZipfileEntry **ppEntry /* OUT: Pointer to new object */ 849 ){ 850 u8 *aRead; 851 char **pzErr = &pTab->base.zErrMsg; 852 int rc = SQLITE_OK; 853 854 if( aBlob==0 ){ 855 aRead = pTab->aBuffer; 856 rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); 857 }else{ 858 if( (iOff+ZIPFILE_CDS_FIXED_SZ)>nBlob ){ 859 /* Not enough data for the CDS structure. Corruption. */ 860 return zipfileCorrupt(pzErr); 861 } 862 aRead = (u8*)&aBlob[iOff]; 863 } 864 865 if( rc==SQLITE_OK ){ 866 sqlite3_int64 nAlloc; 867 ZipfileEntry *pNew; 868 869 int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); 870 int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); 871 nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); 872 873 nAlloc = sizeof(ZipfileEntry) + nExtra; 874 if( aBlob ){ 875 nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); 876 } 877 878 pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); 879 if( pNew==0 ){ 880 rc = SQLITE_NOMEM; 881 }else{ 882 memset(pNew, 0, sizeof(ZipfileEntry)); 883 rc = zipfileReadCDS(aRead, &pNew->cds); 884 if( rc!=SQLITE_OK ){ 885 zipfileTableErr(pTab, "failed to read CDS at offset %lld", iOff); 886 }else if( aBlob==0 ){ 887 rc = zipfileReadData( 888 pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr 889 ); 890 }else{ 891 aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; 892 if( (iOff + ZIPFILE_CDS_FIXED_SZ + nFile + nExtra)>nBlob ){ 893 rc = zipfileCorrupt(pzErr); 894 } 895 } 896 } 897 898 if( rc==SQLITE_OK ){ 899 u32 *pt = &pNew->mUnixTime; 900 /* aRead[0..nFile-1] might contain embedded \000 characters 901 ** See Bug 2026-05-31T11:43:05Z */ 902 pNew->cds.zFile = sqlite3_malloc64(nFile+1); 903 if( pNew->cds.zFile!=0 ){ 904 memcpy(pNew->cds.zFile, aRead, nFile); 905 pNew->cds.zFile[nFile] = 0; 906 } 907 pNew->aExtra = (u8*)&pNew[1]; 908 memcpy(pNew->aExtra, &aRead[nFile], nExtra); 909 if( pNew->cds.zFile==0 ){ 910 rc = SQLITE_NOMEM; 911 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ 912 pNew->mUnixTime = zipfileMtime(&pNew->cds); 913 } 914 } 915 916 if( rc==SQLITE_OK ){ 917 static const int szFix = ZIPFILE_LFH_FIXED_SZ; 918 ZipfileLFH lfh; 919 if( pFile ){ 920 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); 921 }else{ 922 aRead = (u8*)&aBlob[pNew->cds.iOffset]; 923 if( ((i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ)>nBlob ){ 924 rc = zipfileCorrupt(pzErr); 925 } 926 } 927 928 memset(&lfh, 0, sizeof(lfh)); 929 if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh); 930 if( rc==SQLITE_OK ){ 931 pNew->iDataOff = (i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; 932 pNew->iDataOff += lfh.nFile + lfh.nExtra; 933 if( aBlob && pNew->cds.szCompressed ){ 934 if( pNew->iDataOff + pNew->cds.szCompressed > nBlob ){ 935 rc = zipfileCorrupt(pzErr); 936 }else{ 937 pNew->aData = &pNew->aExtra[nExtra]; 938 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); 939 } 940 } 941 }else{ 942 zipfileTableErr(pTab, "failed to read LFH at offset %d", 943 (int)pNew->cds.iOffset 944 ); 945 } 946 } 947 948 if( rc!=SQLITE_OK ){ 949 zipfileEntryFree(pNew); 950 }else{ 951 *ppEntry = pNew; 952 } 953 } 954 955 return rc; 956 } 957 958 /* 959 ** Advance an ZipfileCsr to its next row of output. 960 */ 961 static int zipfileNext(sqlite3_vtab_cursor *cur){ 962 ZipfileCsr *pCsr = (ZipfileCsr*)cur; 963 int rc = SQLITE_OK; 964 965 if( pCsr->pFile ){ 966 i64 iEof = (i64)pCsr->eocd.iOffset + (i64)pCsr->eocd.nSize; 967 zipfileEntryFree(pCsr->pCurrent); 968 pCsr->pCurrent = 0; 969 if( pCsr->iNextOff>=iEof ){ 970 pCsr->bEof = 1; 971 }else{ 972 ZipfileEntry *p = 0; 973 ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); 974 rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); 975 if( rc==SQLITE_OK ){ 976 pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; 977 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; 978 } 979 pCsr->pCurrent = p; 980 } 981 }else{ 982 if( !pCsr->bNoop ){ 983 pCsr->pCurrent = pCsr->pCurrent->pNext; 984 } 985 if( pCsr->pCurrent==0 ){ 986 pCsr->bEof = 1; 987 } 988 } 989 990 pCsr->bNoop = 0; 991 return rc; 992 } 993 994 static void zipfileFree(void *p) { 995 sqlite3_free(p); 996 } 997 998 /* 999 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the 1000 ** size is nOut bytes. This function uncompresses the data and sets the 1001 ** return value in context pCtx to the result (a blob). 1002 ** 1003 ** If an error occurs, an error code is left in pCtx instead. 1004 */ 1005 static void zipfileInflate( 1006 sqlite3_context *pCtx, /* Store result here */ 1007 const u8 *aIn, /* Compressed data */ 1008 int nIn, /* Size of buffer aIn[] in bytes */ 1009 int nOut /* Expected output size */ 1010 ){ 1011 u8 *aRes = sqlite3_malloc64(nOut); 1012 if( aRes==0 ){ 1013 sqlite3_result_error_nomem(pCtx); 1014 }else{ 1015 int err; 1016 z_stream str; 1017 memset(&str, 0, sizeof(str)); 1018 1019 str.next_in = (Byte*)aIn; 1020 str.avail_in = nIn; 1021 str.next_out = (Byte*)aRes; 1022 str.avail_out = nOut; 1023 1024 err = inflateInit2(&str, -15); 1025 if( err!=Z_OK ){ 1026 zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); 1027 }else{ 1028 err = inflate(&str, Z_NO_FLUSH); 1029 if( err!=Z_STREAM_END ){ 1030 zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); 1031 }else{ 1032 sqlite3_result_blob(pCtx, aRes, (int)str.total_out, zipfileFree); 1033 aRes = 0; 1034 } 1035 } 1036 sqlite3_free(aRes); 1037 inflateEnd(&str); 1038 } 1039 } 1040 1041 /* 1042 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function 1043 ** compresses it and sets (*ppOut) to point to a buffer containing the 1044 ** compressed data. The caller is responsible for eventually calling 1045 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) 1046 ** is set to the size of buffer (*ppOut) in bytes. 1047 ** 1048 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error 1049 ** code is returned and an error message left in virtual-table handle 1050 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this 1051 ** case. 1052 */ 1053 static int zipfileDeflate( 1054 const u8 *aIn, int nIn, /* Input */ 1055 u8 **ppOut, int *pnOut, /* Output */ 1056 char **pzErr /* OUT: Error message */ 1057 ){ 1058 int rc = SQLITE_OK; 1059 sqlite3_int64 nAlloc; 1060 z_stream str; 1061 u8 *aOut; 1062 1063 memset(&str, 0, sizeof(str)); 1064 str.next_in = (Bytef*)aIn; 1065 str.avail_in = nIn; 1066 deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); 1067 1068 nAlloc = deflateBound(&str, nIn); 1069 aOut = (u8*)sqlite3_malloc64(nAlloc); 1070 if( aOut==0 ){ 1071 rc = SQLITE_NOMEM; 1072 }else{ 1073 int res; 1074 str.next_out = aOut; 1075 str.avail_out = nAlloc; 1076 res = deflate(&str, Z_FINISH); 1077 if( res==Z_STREAM_END ){ 1078 *ppOut = aOut; 1079 *pnOut = (int)str.total_out; 1080 }else{ 1081 sqlite3_free(aOut); 1082 *pzErr = sqlite3_mprintf("zipfile: deflate() error"); 1083 rc = SQLITE_ERROR; 1084 } 1085 deflateEnd(&str); 1086 } 1087 1088 return rc; 1089 } 1090 1091 1092 /* 1093 ** Return values of columns for the row at which the series_cursor 1094 ** is currently pointing. 1095 */ 1096 static int zipfileColumn( 1097 sqlite3_vtab_cursor *cur, /* The cursor */ 1098 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ 1099 int i /* Which column to return */ 1100 ){ 1101 ZipfileCsr *pCsr = (ZipfileCsr*)cur; 1102 ZipfileCDS *pCDS = &pCsr->pCurrent->cds; 1103 int rc = SQLITE_OK; 1104 switch( i ){ 1105 case 0: /* name */ 1106 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); 1107 break; 1108 case 1: /* mode */ 1109 /* TODO: Whether or not the following is correct surely depends on 1110 ** the platform on which the archive was created. */ 1111 sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); 1112 break; 1113 case 2: { /* mtime */ 1114 sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); 1115 break; 1116 } 1117 case 3: { /* sz */ 1118 if( sqlite3_vtab_nochange(ctx)==0 ){ 1119 sqlite3_result_int64(ctx, pCDS->szUncompressed); 1120 } 1121 break; 1122 } 1123 case 4: /* rawdata */ 1124 if( sqlite3_vtab_nochange(ctx) ) break; 1125 case 5: { /* data */ 1126 if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ 1127 int sz = pCDS->szCompressed; 1128 int szFinal = pCDS->szUncompressed; 1129 if( szFinal>0 ){ 1130 u8 *aBuf; 1131 u8 *aFree = 0; 1132 if( pCsr->pCurrent->aData ){ 1133 aBuf = pCsr->pCurrent->aData; 1134 }else{ 1135 aBuf = aFree = sqlite3_malloc64(sz); 1136 if( aBuf==0 ){ 1137 rc = SQLITE_NOMEM; 1138 }else{ 1139 FILE *pFile = pCsr->pFile; 1140 if( pFile==0 ){ 1141 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; 1142 } 1143 rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, 1144 &pCsr->base.pVtab->zErrMsg 1145 ); 1146 } 1147 } 1148 if( rc==SQLITE_OK ){ 1149 if( i==5 && pCDS->iCompression ){ 1150 zipfileInflate(ctx, aBuf, sz, szFinal); 1151 }else{ 1152 sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); 1153 } 1154 } 1155 sqlite3_free(aFree); 1156 }else{ 1157 /* Figure out if this is a directory or a zero-sized file. Consider 1158 ** it to be a directory either if the mode suggests so, or if 1159 ** the final character in the name is '/'. */ 1160 u32 mode = pCDS->iExternalAttr >> 16; 1161 if( !(mode & S_IFDIR) 1162 && pCDS->nFile>=1 1163 && pCDS->zFile[pCDS->nFile-1]!='/' 1164 ){ 1165 sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); 1166 } 1167 } 1168 } 1169 break; 1170 } 1171 case 6: /* method */ 1172 sqlite3_result_int(ctx, pCDS->iCompression); 1173 break; 1174 default: /* z */ 1175 assert( i==7 ); 1176 sqlite3_result_int64(ctx, pCsr->iId); 1177 break; 1178 } 1179 1180 return rc; 1181 } 1182 1183 /* 1184 ** Return TRUE if the cursor is at EOF. 1185 */ 1186 static int zipfileEof(sqlite3_vtab_cursor *cur){ 1187 ZipfileCsr *pCsr = (ZipfileCsr*)cur; 1188 return pCsr->bEof; 1189 } 1190 1191 /* 1192 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size 1193 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile 1194 ** is guaranteed to be a file-handle open on a zip file. 1195 ** 1196 ** This function attempts to locate the EOCD record within the zip archive 1197 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is 1198 ** returned if successful. Otherwise, an SQLite error code is returned and 1199 ** an English language error message may be left in virtual-table pTab. 1200 */ 1201 static int zipfileReadEOCD( 1202 ZipfileTab *pTab, /* Return errors here */ 1203 const u8 *aBlob, /* Pointer to in-memory file image */ 1204 i64 nBlob, /* Size of aBlob[] in bytes */ 1205 FILE *pFile, /* Read from this file if aBlob==0 */ 1206 ZipfileEOCD *pEOCD /* Object to populate */ 1207 ){ 1208 u8 *aRead = pTab->aBuffer; /* Temporary buffer */ 1209 i64 nRead; /* Bytes to read from file */ 1210 int rc = SQLITE_OK; 1211 1212 memset(pEOCD, 0, sizeof(ZipfileEOCD)); 1213 if( aBlob==0 ){ 1214 i64 iOff; /* Offset to read from */ 1215 i64 szFile; /* Total size of file in bytes */ 1216 fseek(pFile, 0, SEEK_END); 1217 szFile = (i64)ftell(pFile); 1218 if( szFile==0 ){ 1219 return SQLITE_OK; 1220 } 1221 nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); 1222 iOff = szFile - nRead; 1223 rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); 1224 }else{ 1225 nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); 1226 aRead = (u8*)&aBlob[nBlob-nRead]; 1227 } 1228 1229 if( rc==SQLITE_OK ){ 1230 i64 i; 1231 1232 /* Scan backwards looking for the signature bytes */ 1233 for(i=nRead-20; i>=0; i--){ 1234 if( aRead[i]==0x50 && aRead[i+1]==0x4b 1235 && aRead[i+2]==0x05 && aRead[i+3]==0x06 1236 ){ 1237 break; 1238 } 1239 } 1240 if( i<0 ){ 1241 zipfileTableErr(pTab, "cannot find end of central directory record"); 1242 return SQLITE_ERROR; 1243 } 1244 1245 aRead += i+4; 1246 pEOCD->iDisk = zipfileRead16(aRead); 1247 pEOCD->iFirstDisk = zipfileRead16(aRead); 1248 pEOCD->nEntry = zipfileRead16(aRead); 1249 pEOCD->nEntryTotal = zipfileRead16(aRead); 1250 pEOCD->nSize = zipfileRead32(aRead); 1251 pEOCD->iOffset = zipfileRead32(aRead); 1252 } 1253 1254 return rc; 1255 } 1256 1257 /* 1258 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry 1259 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added 1260 ** to the end of the list. Otherwise, it is added to the list immediately 1261 ** before pBefore (which is guaranteed to be a part of said list). 1262 */ 1263 static void zipfileAddEntry( 1264 ZipfileTab *pTab, 1265 ZipfileEntry *pBefore, 1266 ZipfileEntry *pNew 1267 ){ 1268 assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); 1269 assert( pNew->pNext==0 ); 1270 if( pBefore==0 ){ 1271 if( pTab->pFirstEntry==0 ){ 1272 pTab->pFirstEntry = pTab->pLastEntry = pNew; 1273 }else{ 1274 assert( pTab->pLastEntry->pNext==0 ); 1275 pTab->pLastEntry->pNext = pNew; 1276 pTab->pLastEntry = pNew; 1277 } 1278 }else{ 1279 ZipfileEntry **pp; 1280 for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); 1281 pNew->pNext = pBefore; 1282 *pp = pNew; 1283 } 1284 } 1285 1286 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, i64 nBlob){ 1287 ZipfileEOCD eocd; 1288 int rc; 1289 int i; 1290 i64 iOff; 1291 1292 rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); 1293 iOff = eocd.iOffset; 1294 for(i=0; rc==SQLITE_OK && ipWriteFd, iOff, &pNew); 1297 1298 if( rc==SQLITE_OK ){ 1299 zipfileAddEntry(pTab, 0, pNew); 1300 iOff += ZIPFILE_CDS_FIXED_SZ; 1301 iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; 1302 } 1303 } 1304 return rc; 1305 } 1306 1307 /* 1308 ** xFilter callback. 1309 */ 1310 static int zipfileFilter( 1311 sqlite3_vtab_cursor *cur, 1312 int idxNum, const char *idxStr, 1313 int argc, sqlite3_value **argv 1314 ){ 1315 ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; 1316 ZipfileCsr *pCsr = (ZipfileCsr*)cur; 1317 const char *zFile = 0; /* Zip file to scan */ 1318 int rc = SQLITE_OK; /* Return Code */ 1319 int bInMemory = 0; /* True for an in-memory zipfile */ 1320 1321 (void)idxStr; 1322 (void)argc; 1323 1324 zipfileResetCursor(pCsr); 1325 1326 if( pTab->zFile ){ 1327 zFile = pTab->zFile; 1328 }else if( idxNum==0 ){ 1329 zipfileCursorErr(pCsr, "zipfile() function requires an argument"); 1330 return SQLITE_ERROR; 1331 }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ 1332 static const u8 aEmptyBlob = 0; 1333 const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); 1334 i64 nBlob = sqlite3_value_bytes(argv[0]); 1335 assert( pTab->pFirstEntry==0 ); 1336 if( aBlob==0 ){ 1337 aBlob = &aEmptyBlob; 1338 nBlob = 0; 1339 } 1340 rc = zipfileLoadDirectory(pTab, aBlob, nBlob); 1341 pCsr->pFreeEntry = pTab->pFirstEntry; 1342 pTab->pFirstEntry = pTab->pLastEntry = 0; 1343 if( rc!=SQLITE_OK ) return rc; 1344 bInMemory = 1; 1345 }else{ 1346 zFile = (const char*)sqlite3_value_text(argv[0]); 1347 } 1348 1349 if( 0==pTab->pWriteFd && 0==bInMemory ){ 1350 pCsr->pFile = zFile ? sqlite3_fopen(zFile, "rb") : 0; 1351 if( pCsr->pFile==0 ){ 1352 zipfileCursorErr(pCsr, "cannot open file: %s", zFile); 1353 rc = SQLITE_ERROR; 1354 }else{ 1355 rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); 1356 if( rc==SQLITE_OK ){ 1357 if( pCsr->eocd.nEntry==0 ){ 1358 pCsr->bEof = 1; 1359 }else{ 1360 pCsr->iNextOff = pCsr->eocd.iOffset; 1361 rc = zipfileNext(cur); 1362 } 1363 } 1364 } 1365 }else{ 1366 pCsr->bNoop = 1; 1367 pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; 1368 rc = zipfileNext(cur); 1369 } 1370 1371 return rc; 1372 } 1373 1374 /* 1375 ** xBestIndex callback. 1376 */ 1377 static int zipfileBestIndex( 1378 sqlite3_vtab *tab, 1379 sqlite3_index_info *pIdxInfo 1380 ){ 1381 int i; 1382 int idx = -1; 1383 int unusable = 0; 1384 (void)tab; 1385 1386 for(i=0; inConstraint; i++){ 1387 const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; 1388 if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; 1389 if( pCons->usable==0 ){ 1390 unusable = 1; 1391 }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ 1392 idx = i; 1393 } 1394 } 1395 pIdxInfo->estimatedCost = 1000.0; 1396 if( idx>=0 ){ 1397 pIdxInfo->aConstraintUsage[idx].argvIndex = 1; 1398 pIdxInfo->aConstraintUsage[idx].omit = 1; 1399 pIdxInfo->idxNum = 1; 1400 }else if( unusable ){ 1401 return SQLITE_CONSTRAINT; 1402 } 1403 return SQLITE_OK; 1404 } 1405 1406 static ZipfileEntry *zipfileNewEntry(const char *zPath){ 1407 ZipfileEntry *pNew; 1408 pNew = sqlite3_malloc64(sizeof(ZipfileEntry)); 1409 if( pNew ){ 1410 memset(pNew, 0, sizeof(ZipfileEntry)); 1411 pNew->cds.zFile = sqlite3_mprintf("%s", zPath); 1412 if( pNew->cds.zFile==0 ){ 1413 sqlite3_free(pNew); 1414 pNew = 0; 1415 } 1416 } 1417 return pNew; 1418 } 1419 1420 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ 1421 ZipfileCDS *pCds = &pEntry->cds; 1422 u8 *a = aBuf; 1423 1424 pCds->nExtra = 9; 1425 1426 /* Write the LFH itself */ 1427 zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); 1428 zipfileWrite16(a, pCds->iVersionExtract); 1429 zipfileWrite16(a, pCds->flags); 1430 zipfileWrite16(a, pCds->iCompression); 1431 zipfileWrite16(a, pCds->mTime); 1432 zipfileWrite16(a, pCds->mDate); 1433 zipfileWrite32(a, pCds->crc32); 1434 zipfileWrite32(a, pCds->szCompressed); 1435 zipfileWrite32(a, pCds->szUncompressed); 1436 zipfileWrite16(a, (u16)pCds->nFile); 1437 zipfileWrite16(a, pCds->nExtra); 1438 assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); 1439 1440 /* Add the file name */ 1441 memcpy(a, pCds->zFile, (int)pCds->nFile); 1442 a += (int)pCds->nFile; 1443 1444 /* The "extra" data */ 1445 zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); 1446 zipfileWrite16(a, 5); 1447 *a++ = 0x01; 1448 zipfileWrite32(a, pEntry->mUnixTime); 1449 1450 return a-aBuf; 1451 } 1452 1453 static int zipfileAppendEntry( 1454 ZipfileTab *pTab, 1455 ZipfileEntry *pEntry, 1456 const u8 *pData, 1457 int nData 1458 ){ 1459 u8 *aBuf = pTab->aBuffer; 1460 int nBuf; 1461 int rc; 1462 1463 nBuf = zipfileSerializeLFH(pEntry, aBuf); 1464 rc = zipfileAppendData(pTab, aBuf, nBuf); 1465 if( rc==SQLITE_OK ){ 1466 pEntry->iDataOff = pTab->szCurrent; 1467 rc = zipfileAppendData(pTab, pData, nData); 1468 } 1469 1470 return rc; 1471 } 1472 1473 static int zipfileGetMode( 1474 sqlite3_value *pVal, 1475 int bIsDir, /* If true, default to directory */ 1476 u32 *pMode, /* OUT: Mode value */ 1477 char **pzErr /* OUT: Error message */ 1478 ){ 1479 const char *z = (const char*)sqlite3_value_text(pVal); 1480 u32 mode = 0; 1481 if( z==0 ){ 1482 mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); 1483 }else if( z[0]>='0' && z[0]<='9' ){ 1484 mode = (unsigned int)sqlite3_value_int(pVal); 1485 }else{ 1486 const char zTemplate[11] = "-rwxrwxrwx"; 1487 int i; 1488 if( strlen(z)!=10 ) goto parse_error; 1489 switch( z[0] ){ 1490 case '-': mode |= S_IFREG; break; 1491 case 'd': mode |= S_IFDIR; break; 1492 case 'l': mode |= S_IFLNK; break; 1493 default: goto parse_error; 1494 } 1495 for(i=1; i<10; i++){ 1496 if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); 1497 else if( z[i]!='-' ) goto parse_error; 1498 } 1499 } 1500 if( ((mode & S_IFDIR)==0)==bIsDir ){ 1501 /* The "mode" attribute is a directory, but data has been specified. 1502 ** Or vice-versa - no data but "mode" is a file or symlink. */ 1503 *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); 1504 return SQLITE_CONSTRAINT; 1505 } 1506 *pMode = mode; 1507 return SQLITE_OK; 1508 1509 parse_error: 1510 *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); 1511 return SQLITE_ERROR; 1512 } 1513 1514 /* 1515 ** Both (const char*) arguments point to nul-terminated strings. Argument 1516 ** nB is the value of strlen(zB). This function returns 0 if the strings are 1517 ** identical, ignoring any trailing '/' character in either path. */ 1518 static int zipfileComparePath(const char *zA, const char *zB, int nB){ 1519 int nA = (int)strlen(zA); 1520 if( nA>0 && zA[nA-1]=='/' ) nA--; 1521 if( nB>0 && zB[nB-1]=='/' ) nB--; 1522 if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; 1523 return 1; 1524 } 1525 1526 static int zipfileBegin(sqlite3_vtab *pVtab){ 1527 ZipfileTab *pTab = (ZipfileTab*)pVtab; 1528 int rc = SQLITE_OK; 1529 1530 assert( pTab->pWriteFd==0 ); 1531 if( pTab->zFile==0 || pTab->zFile[0]==0 ){ 1532 zipfileTableErr(pTab, "zipfile: missing filename"); 1533 return SQLITE_ERROR; 1534 } 1535 1536 /* Open a write fd on the file. Also load the entire central directory 1537 ** structure into memory. During the transaction any new file data is 1538 ** appended to the archive file, but the central directory is accumulated 1539 ** in main-memory until the transaction is committed. */ 1540 pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+"); 1541 if( pTab->pWriteFd==0 ){ 1542 zipfileTableErr(pTab, 1543 "zipfile: failed to open file %s for writing", pTab->zFile 1544 ); 1545 rc = SQLITE_ERROR; 1546 }else{ 1547 fseek(pTab->pWriteFd, 0, SEEK_END); 1548 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); 1549 rc = zipfileLoadDirectory(pTab, 0, 0); 1550 } 1551 1552 if( rc!=SQLITE_OK ){ 1553 zipfileCleanupTransaction(pTab); 1554 } 1555 1556 return rc; 1557 } 1558 1559 /* 1560 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like 1561 ** time(2)). 1562 */ 1563 static u32 zipfileTime(void){ 1564 sqlite3_vfs *pVfs = sqlite3_vfs_find(0); 1565 u32 ret; 1566 if( pVfs==0 ) return 0; 1567 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ 1568 i64 ms; 1569 pVfs->xCurrentTimeInt64(pVfs, &ms); 1570 ret = (u32)((ms/1000) - ((i64)`24405875` * 8640)); 1571 }else{ 1572 double day; 1573 pVfs->xCurrentTime(pVfs, &day); 1574 ret = (u32)((day - `2440587`.5) * 86400); 1575 } 1576 return ret; 1577 } 1578 1579 /* 1580 ** Return a 32-bit timestamp in UNIX epoch format. 1581 ** 1582 ** If the value passed as the only argument is either NULL or an SQL NULL, 1583 ** return the current time. Otherwise, return the value stored in (*pVal) 1584 ** cast to a 32-bit unsigned integer. 1585 */ 1586 static u32 zipfileGetTime(sqlite3_value *pVal){ 1587 if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ 1588 return zipfileTime(); 1589 } 1590 return (u32)sqlite3_value_int64(pVal); 1591 } 1592 1593 /* 1594 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry 1595 ** linked list. Remove it from the list and free the object. 1596 */ 1597 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ 1598 if( pOld ){ 1599 if( pTab->pFirstEntry==pOld ){ 1600 pTab->pFirstEntry = pOld->pNext; 1601 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0; 1602 }else{ 1603 ZipfileEntry *p; 1604 for(p=pTab->pFirstEntry; p; p=p->pNext){ 1605 if( p->pNext==pOld ){ 1606 p->pNext = pOld->pNext; 1607 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p; 1608 break; 1609 } 1610 } 1611 } 1612 zipfileEntryFree(pOld); 1613 } 1614 } 1615 1616 /* 1617 ** xUpdate method. 1618 */ 1619 static int zipfileUpdate( 1620 sqlite3_vtab *pVtab, 1621 int nVal, 1622 sqlite3_value **apVal, 1623 sqlite_int64 *pRowid 1624 ){ 1625 ZipfileTab *pTab = (ZipfileTab*)pVtab; 1626 int rc = SQLITE_OK; /* Return Code */ 1627 ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ 1628 1629 u32 mode = 0; /* Mode for new entry */ 1630 u32 mTime = 0; /* Modification time for new entry */ 1631 i64 sz = 0; /* Uncompressed size */ 1632 const char *zPath = 0; /* Path for new entry */ 1633 int nPath = 0; /* strlen(zPath) */ 1634 const u8 *pData = 0; /* Pointer to buffer containing content */ 1635 int nData = 0; /* Size of pData buffer in bytes */ 1636 int iMethod = 0; /* Compression method for new entry */ 1637 u8 *pFree = 0; /* Free this */ 1638 char *zFree = 0; /* Also free this */ 1639 ZipfileEntry *pOld = 0; 1640 ZipfileEntry *pOld2 = 0; 1641 int bUpdate = 0; /* True for an update that modifies "name" */ 1642 int bIsDir = 0; 1643 u32 iCrc32 = 0; 1644 1645 (void)pRowid; 1646 1647 if( pTab->pWriteFd==0 ){ 1648 rc = zipfileBegin(pVtab); 1649 if( rc!=SQLITE_OK ) return rc; 1650 } 1651 1652 /* If this is a DELETE or UPDATE, find the archive entry to delete. */ 1653 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ 1654 const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); 1655 int nDelete = (int)strlen(zDelete); 1656 if( nVal>1 ){ 1657 const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); 1658 if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ 1659 bUpdate = 1; 1660 } 1661 } 1662 for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ 1663 if( pOld==0 ) return SQLITE_OK; 1664 if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ 1665 break; 1666 } 1667 } 1668 } 1669 1670 if( nVal>1 ){ 1671 /* Check that "sz" and "rawdata" are both NULL: */ 1672 if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ 1673 zipfileTableErr(pTab, "sz must be NULL"); 1674 rc = SQLITE_CONSTRAINT; 1675 } 1676 if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ 1677 zipfileTableErr(pTab, "rawdata must be NULL"); 1678 rc = SQLITE_CONSTRAINT; 1679 } 1680 1681 if( rc==SQLITE_OK ){ 1682 if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ 1683 /* data=NULL. A directory */ 1684 bIsDir = 1; 1685 }else{ 1686 /* Value specified for "data", and possibly "method". This must be 1687 ** a regular file or a symlink. */ 1688 const u8 *aIn = sqlite3_value_blob(apVal[7]); 1689 int nIn = sqlite3_value_bytes(apVal[7]); 1690 int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; 1691 1692 iMethod = sqlite3_value_int(apVal[8]); 1693 sz = nIn; 1694 pData = aIn; 1695 nData = nIn; 1696 if( iMethod!=0 && iMethod!=8 ){ 1697 zipfileTableErr(pTab, "unknown compression method: %d", iMethod); 1698 rc = SQLITE_CONSTRAINT; 1699 }else{ 1700 if( bAuto || iMethod ){ 1701 int nCmp; 1702 rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); 1703 if( rc==SQLITE_OK ){ 1704 if( iMethod || nCmpbase.zErrMsg); 1718 } 1719 1720 if( rc==SQLITE_OK ){ 1721 zPath = (const char*)sqlite3_value_text(apVal[2]); 1722 if( zPath==0 ) zPath = ""; 1723 nPath = (int)strlen(zPath); 1724 if( nPath>ZIPFILE_MX_NAME ){ 1725 zipfileTableErr(pTab, "filename too long; max: %d bytes", 1726 ZIPFILE_MX_NAME); 1727 rc = SQLITE_CONSTRAINT; 1728 } 1729 mTime = zipfileGetTime(apVal[4]); 1730 } 1731 1732 if( rc==SQLITE_OK && bIsDir ){ 1733 /* For a directory, check that the last character in the path is a 1734 ** '/'. This appears to be required for compatibility with info-zip 1735 ** (the unzip command on unix). It does not create directories 1736 ** otherwise. */ 1737 if( nPath<=0 || zPath[nPath-1]!='/' ){ 1738 zFree = sqlite3_mprintf("%s/", zPath); 1739 zPath = (const char*)zFree; 1740 if( zFree==0 ){ 1741 rc = SQLITE_NOMEM; 1742 nPath = 0; 1743 }else{ 1744 nPath = (int)strlen(zPath); 1745 } 1746 } 1747 } 1748 1749 /* Check that we're not inserting a duplicate entry -OR- updating an 1750 ** entry with a path, thereby making it into a duplicate. */ 1751 if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ 1752 ZipfileEntry *p; 1753 int nEntry = 0; 1754 for(p=pTab->pFirstEntry; p; p=p->pNext){ 1755 nEntry++; 1756 if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ 1757 switch( sqlite3_vtab_on_conflict(pTab->db) ){ 1758 case SQLITE_IGNORE: { 1759 goto zipfile_update_done; 1760 } 1761 case SQLITE_REPLACE: { 1762 pOld2 = p; 1763 break; 1764 } 1765 default: { 1766 zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); 1767 rc = SQLITE_CONSTRAINT; 1768 break; 1769 } 1770 } 1771 break; 1772 } 1773 } 1774 1775 /* The EOCD record stores the number of entries as a 16-bit value. 1776 ** Refuse to add an entry that would cause it to overflow. */ 1777 if( p==0 && pOld==0 && nEntry>=ZIPFILE_MX_ENTRY ){ 1778 zipfileTableErr(pTab, "too many entries; max: %d", ZIPFILE_MX_ENTRY); 1779 rc = SQLITE_CONSTRAINT; 1780 } 1781 } 1782 1783 if( rc==SQLITE_OK ){ 1784 /* Create the new CDS record. */ 1785 pNew = zipfileNewEntry(zPath); 1786 if( pNew==0 ){ 1787 rc = SQLITE_NOMEM; 1788 }else{ 1789 pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; 1790 pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; 1791 pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; 1792 pNew->cds.iCompression = (u16)iMethod; 1793 zipfileMtimeToDos(&pNew->cds, mTime); 1794 pNew->cds.crc32 = iCrc32; 1795 pNew->cds.szCompressed = nData; 1796 pNew->cds.szUncompressed = (u32)sz; 1797 pNew->cds.iExternalAttr = (mode<<16); 1798 pNew->cds.iOffset = (u32)pTab->szCurrent; 1799 pNew->cds.nFile = (u16)nPath; 1800 pNew->mUnixTime = (u32)mTime; 1801 rc = zipfileAppendEntry(pTab, pNew, pData, nData); 1802 zipfileAddEntry(pTab, pOld, pNew); 1803 } 1804 } 1805 } 1806 1807 if( rc==SQLITE_OK && (pOld || pOld2) ){ 1808 ZipfileCsr *pCsr; 1809 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ 1810 if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ 1811 pCsr->pCurrent = pCsr->pCurrent->pNext; 1812 pCsr->bNoop = 1; 1813 } 1814 } 1815 1816 zipfileRemoveEntryFromList(pTab, pOld); 1817 zipfileRemoveEntryFromList(pTab, pOld2); 1818 } 1819 1820 zipfile_update_done: 1821 sqlite3_free(pFree); 1822 sqlite3_free(zFree); 1823 return rc; 1824 } 1825 1826 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ 1827 u8 *a = aBuf; 1828 zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); 1829 zipfileWrite16(a, p->iDisk); 1830 zipfileWrite16(a, p->iFirstDisk); 1831 zipfileWrite16(a, p->nEntry); 1832 zipfileWrite16(a, p->nEntryTotal); 1833 zipfileWrite32(a, p->nSize); 1834 zipfileWrite32(a, p->iOffset); 1835 zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ 1836 1837 return a-aBuf; 1838 } 1839 1840 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ 1841 int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); 1842 assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); 1843 return zipfileAppendData(pTab, pTab->aBuffer, nBuf); 1844 } 1845 1846 /* 1847 ** Serialize the CDS structure into buffer aBuf[]. Return the number 1848 ** of bytes written. 1849 */ 1850 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ 1851 u8 *a = aBuf; 1852 ZipfileCDS *pCDS = &pEntry->cds; 1853 1854 if( pEntry->aExtra==0 ){ 1855 pCDS->nExtra = 9; 1856 } 1857 1858 zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); 1859 zipfileWrite16(a, pCDS->iVersionMadeBy); 1860 zipfileWrite16(a, pCDS->iVersionExtract); 1861 zipfileWrite16(a, pCDS->flags); 1862 zipfileWrite16(a, pCDS->iCompression); 1863 zipfileWrite16(a, pCDS->mTime); 1864 zipfileWrite16(a, pCDS->mDate); 1865 zipfileWrite32(a, pCDS->crc32); 1866 zipfileWrite32(a, pCDS->szCompressed); 1867 zipfileWrite32(a, pCDS->szUncompressed); 1868 assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); 1869 zipfileWrite16(a, pCDS->nFile); 1870 zipfileWrite16(a, pCDS->nExtra); 1871 zipfileWrite16(a, pCDS->nComment); 1872 zipfileWrite16(a, pCDS->iDiskStart); 1873 zipfileWrite16(a, pCDS->iInternalAttr); 1874 zipfileWrite32(a, pCDS->iExternalAttr); 1875 zipfileWrite32(a, pCDS->iOffset); 1876 1877 memcpy(a, pCDS->zFile, pCDS->nFile); 1878 a += pCDS->nFile; 1879 1880 if( pEntry->aExtra ){ 1881 int n = (int)pCDS->nExtra + (int)pCDS->nComment; 1882 memcpy(a, pEntry->aExtra, n); 1883 a += n; 1884 }else{ 1885 assert( pCDS->nExtra==9 ); 1886 zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); 1887 zipfileWrite16(a, 5); 1888 *a++ = 0x01; 1889 zipfileWrite32(a, pEntry->mUnixTime); 1890 } 1891 1892 return a-aBuf; 1893 } 1894 1895 static int zipfileCommit(sqlite3_vtab *pVtab){ 1896 ZipfileTab *pTab = (ZipfileTab*)pVtab; 1897 int rc = SQLITE_OK; 1898 if( pTab->pWriteFd ){ 1899 i64 iOffset = pTab->szCurrent; 1900 ZipfileEntry *p; 1901 ZipfileEOCD eocd; 1902 int nEntry = 0; 1903 1904 /* Write out all entries */ 1905 for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ 1906 int n = zipfileSerializeCDS(p, pTab->aBuffer); 1907 rc = zipfileAppendData(pTab, pTab->aBuffer, n); 1908 nEntry++; 1909 } 1910 1911 /* Write out the EOCD record */ 1912 eocd.iDisk = 0; 1913 eocd.iFirstDisk = 0; 1914 assert( nEntry<=ZIPFILE_MX_ENTRY ); 1915 eocd.nEntry = (u16)nEntry; 1916 eocd.nEntryTotal = (u16)nEntry; 1917 eocd.nSize = (u32)(pTab->szCurrent - iOffset); 1918 eocd.iOffset = (u32)iOffset; 1919 rc = zipfileAppendEOCD(pTab, &eocd); 1920 1921 zipfileCleanupTransaction(pTab); 1922 } 1923 return rc; 1924 } 1925 1926 static int zipfileRollback(sqlite3_vtab *pVtab){ 1927 return zipfileCommit(pVtab); 1928 } 1929 1930 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ 1931 ZipfileCsr *pCsr; 1932 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ 1933 if( iId==pCsr->iId ) break; 1934 } 1935 return pCsr; 1936 } 1937 1938 static void zipfileFunctionCds( 1939 sqlite3_context *context, 1940 int argc, 1941 sqlite3_value **argv 1942 ){ 1943 ZipfileCsr *pCsr; 1944 ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); 1945 assert( argc>0 ); 1946 1947 pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); 1948 if( pCsr ){ 1949 ZipfileCDS *p = &pCsr->pCurrent->cds; 1950 char *zRes = sqlite3_mprintf("{" 1951 "\"version-made-by\" : %u, " 1952 "\"version-to-extract\" : %u, " 1953 "\"flags\" : %u, " 1954 "\"compression\" : %u, " 1955 "\"time\" : %u, " 1956 "\"date\" : %u, " 1957 "\"crc32\" : %u, " 1958 "\"compressed-size\" : %u, " 1959 "\"uncompressed-size\" : %u, " 1960 "\"file-name-length\" : %u, " 1961 "\"extra-field-length\" : %u, " 1962 "\"file-comment-length\" : %u, " 1963 "\"disk-number-start\" : %u, " 1964 "\"internal-attr\" : %u, " 1965 "\"external-attr\" : %u, " 1966 "\"offset\" : %u }", 1967 (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, 1968 (u32)p->flags, (u32)p->iCompression, 1969 (u32)p->mTime, (u32)p->mDate, 1970 (u32)p->crc32, (u32)p->szCompressed, 1971 (u32)p->szUncompressed, (u32)p->nFile, 1972 (u32)p->nExtra, (u32)p->nComment, 1973 (u32)p->iDiskStart, (u32)p->iInternalAttr, 1974 (u32)p->iExternalAttr, (u32)p->iOffset 1975 ); 1976 1977 if( zRes==0 ){ 1978 sqlite3_result_error_nomem(context); 1979 }else{ 1980 sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); 1981 sqlite3_free(zRes); 1982 } 1983 } 1984 } 1985 1986 /* 1987 ** xFindFunction method. 1988 */ 1989 static int zipfileFindFunction( 1990 sqlite3_vtab *pVtab, /* Virtual table handle */ 1991 int nArg, /* Number of SQL function arguments */ 1992 const char *zName, /* Name of SQL function */ 1993 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ 1994 void **ppArg /* OUT: User data for *pxFunc */ 1995 ){ 1996 (void)nArg; 1997 if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ 1998 *pxFunc = zipfileFunctionCds; 1999 *ppArg = (void*)pVtab; 2000 return 1; 2001 } 2002 return 0; 2003 } 2004 2005 typedef struct ZipfileBuffer ZipfileBuffer; 2006 struct ZipfileBuffer { 2007 u8 *a; /* Pointer to buffer */ 2008 int n; /* Size of buffer in bytes */ 2009 int nAlloc; /* Byte allocated at a[] */ 2010 }; 2011 2012 typedef struct ZipfileCtx ZipfileCtx; 2013 struct ZipfileCtx { 2014 int nEntry; 2015 ZipfileBuffer body; 2016 ZipfileBuffer cds; 2017 }; 2018 2019 static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){ 2020 if( (pBuf->nAlloc-pBuf->n)n ? (i64)pBuf->n*2 : 512; 2023 i64 nReq = pBuf->n + nByte; 2024 2025 while( nNewa, nNew); 2027 if( aNew==0 ) return SQLITE_NOMEM; 2028 pBuf->a = aNew; 2029 pBuf->nAlloc = (int)nNew; 2030 } 2031 return SQLITE_OK; 2032 } 2033 2034 /* 2035 ** xStep() callback for the zipfile() aggregate. This can be called in 2036 ** any of the following ways: 2037 ** 2038 ** SELECT zipfile(name,data) ... 2039 ** SELECT zipfile(name,mode,mtime,data) ... 2040 ** SELECT zipfile(name,mode,mtime,data,method) ... 2041 */ 2042 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ 2043 ZipfileCtx *p; /* Aggregate function context */ 2044 ZipfileEntry e; /* New entry to add to zip archive */ 2045 2046 sqlite3_value *pName = 0; 2047 sqlite3_value *pMode = 0; 2048 sqlite3_value *pMtime = 0; 2049 sqlite3_value *pData = 0; 2050 sqlite3_value *pMethod = 0; 2051 2052 int bIsDir = 0; 2053 u32 mode; 2054 int rc = SQLITE_OK; 2055 char *zErr = 0; 2056 2057 int iMethod = -1; /* Compression method to use (0 or 8) */ 2058 2059 const u8 *aData = 0; /* Possibly compressed data for new entry */ 2060 int nData = 0; /* Size of aData[] in bytes */ 2061 int szUncompressed = 0; /* Size of data before compression */ 2062 u8 *aFree = 0; /* Free this before returning */ 2063 u32 iCrc32 = 0; /* crc32 of uncompressed data */ 2064 2065 char *zName = 0; /* Path (name) of new entry */ 2066 int nName = 0; /* Size of zName in bytes */ 2067 char *zFree = 0; /* Free this before returning */ 2068 i64 nByte; 2069 2070 memset(&e, 0, sizeof(e)); 2071 p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); 2072 if( p==0 ) return; 2073 2074 /* Martial the arguments into stack variables */ 2075 if( nVal!=2 && nVal!=4 && nVal!=5 ){ 2076 zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); 2077 rc = SQLITE_ERROR; 2078 goto zipfile_step_out; 2079 } 2080 pName = apVal[0]; 2081 if( nVal==2 ){ 2082 pData = apVal[1]; 2083 }else{ 2084 pMode = apVal[1]; 2085 pMtime = apVal[2]; 2086 pData = apVal[3]; 2087 if( nVal==5 ){ 2088 pMethod = apVal[4]; 2089 } 2090 } 2091 2092 /* Check that the 'name' parameter looks ok. */ 2093 zName = (char*)sqlite3_value_text(pName); 2094 nName = sqlite3_value_bytes(pName); 2095 if( zName==0 ){ 2096 zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); 2097 rc = SQLITE_ERROR; 2098 goto zipfile_step_out; 2099 } 2100 if( nName>ZIPFILE_MX_NAME ){ 2101 zErr = sqlite3_mprintf( 2102 "filename argument to zipfile() too big; max: %d bytes", 2103 ZIPFILE_MX_NAME); 2104 rc = SQLITE_ERROR; 2105 goto zipfile_step_out; 2106 } 2107 if( p->nEntry>=ZIPFILE_MX_ENTRY ){ 2108 zErr = sqlite3_mprintf("too many entries for zipfile(); max: %d", 2109 ZIPFILE_MX_ENTRY); 2110 rc = SQLITE_ERROR; 2111 goto zipfile_step_out; 2112 } 2113 2114 /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use 2115 ** deflate compression) or NULL (choose automatically). */ 2116 if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ 2117 iMethod = (int)sqlite3_value_int64(pMethod); 2118 if( iMethod!=0 && iMethod!=8 ){ 2119 zErr = sqlite3_mprintf("illegal method value: %d", iMethod); 2120 rc = SQLITE_ERROR; 2121 goto zipfile_step_out; 2122 } 2123 } 2124 2125 /* Now inspect the data. If this is NULL, then the new entry must be a 2126 ** directory. Otherwise, figure out whether or not the data should 2127 ** be deflated or simply stored in the zip archive. */ 2128 if( sqlite3_value_type(pData)==SQLITE_NULL ){ 2129 bIsDir = 1; 2130 iMethod = 0; 2131 }else{ 2132 aData = sqlite3_value_blob(pData); 2133 szUncompressed = nData = sqlite3_value_bytes(pData); 2134 iCrc32 = crc32(0, aData, nData); 2135 if( iMethod<0 || iMethod==8 ){ 2136 int nOut = 0; 2137 rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); 2138 if( rc!=SQLITE_OK ){ 2139 goto zipfile_step_out; 2140 } 2141 if( iMethod==8 || nOut0 && zName[nName-1]=='/' ){ 2163 zErr = sqlite3_mprintf("non-directory name must not end with /"); 2164 rc = SQLITE_ERROR; 2165 goto zipfile_step_out; 2166 } 2167 }else{ 2168 if( nName==0 || zName[nName-1]!='/' ){ 2169 zName = zFree = sqlite3_mprintf("%s/", zName); 2170 if( zName==0 ){ 2171 rc = SQLITE_NOMEM; 2172 goto zipfile_step_out; 2173 } 2174 nName = (int)strlen(zName); 2175 }else{ 2176 while( nName>1 && zName[nName-2]=='/' ) nName--; 2177 } 2178 } 2179 2180 /* Assemble the ZipfileEntry object for the new zip archive entry */ 2181 e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; 2182 e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; 2183 e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; 2184 e.cds.iCompression = (u16)iMethod; 2185 zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); 2186 e.cds.crc32 = iCrc32; 2187 e.cds.szCompressed = nData; 2188 e.cds.szUncompressed = szUncompressed; 2189 e.cds.iExternalAttr = (mode<<16); 2190 e.cds.iOffset = p->body.n; 2191 e.cds.nFile = (u16)nName; 2192 e.cds.zFile = zName; 2193 2194 /* Append the LFH to the body of the new archive */ 2195 nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; 2196 if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; 2197 p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); 2198 2199 /* Append the data to the body of the new archive */ 2200 if( nData>0 ){ 2201 if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; 2202 memcpy(&p->body.a[p->body.n], aData, nData); 2203 p->body.n += nData; 2204 } 2205 2206 /* Append the CDS record to the directory of the new archive */ 2207 nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; 2208 if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; 2209 p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); 2210 2211 /* Increment the count of entries in the archive */ 2212 p->nEntry++; 2213 2214 zipfile_step_out: 2215 sqlite3_free(aFree); 2216 sqlite3_free(zFree); 2217 if( rc ){ 2218 if( zErr ){ 2219 sqlite3_result_error(pCtx, zErr, -1); 2220 }else{ 2221 sqlite3_result_error_code(pCtx, rc); 2222 } 2223 } 2224 sqlite3_free(zErr); 2225 } 2226 2227 /* 2228 ** xFinalize() callback for zipfile aggregate function. 2229 */ 2230 static void zipfileFinal(sqlite3_context *pCtx){ 2231 ZipfileCtx *p; 2232 ZipfileEOCD eocd; 2233 sqlite3_int64 nZip; 2234 u8 *aZip; 2235 2236 p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); 2237 if( p==0 ) return; 2238 if( p->nEntry>0 ){ 2239 memset(&eocd, 0, sizeof(eocd)); 2240 assert( p->nEntry<=ZIPFILE_MX_ENTRY ); 2241 eocd.nEntry = (u16)p->nEntry; 2242 eocd.nEntryTotal = (u16)p->nEntry; 2243 eocd.nSize = p->cds.n; 2244 eocd.iOffset = p->body.n; 2245 2246 nZip = (i64)p->body.n + (i64)p->cds.n + ZIPFILE_EOCD_FIXED_SZ; 2247 aZip = (u8*)sqlite3_malloc64(nZip); 2248 if( aZip==0 ){ 2249 sqlite3_result_error_nomem(pCtx); 2250 }else{ 2251 memcpy(aZip, p->body.a, p->body.n); 2252 memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); 2253 zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); 2254 sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); 2255 } 2256 } 2257 2258 sqlite3_free(p->body.a); 2259 sqlite3_free(p->cds.a); 2260 } 2261 2262 2263 /* 2264 ** Register the "zipfile" virtual table. 2265 */ 2266 static int zipfileRegister(sqlite3 *db){ 2267 static sqlite3_module zipfileModule = { 2268 1, /* iVersion */ 2269 zipfileConnect, /* xCreate */ 2270 zipfileConnect, /* xConnect */ 2271 zipfileBestIndex, /* xBestIndex */ 2272 zipfileDisconnect, /* xDisconnect */ 2273 zipfileDisconnect, /* xDestroy */ 2274 zipfileOpen, /* xOpen - open a cursor */ 2275 zipfileClose, /* xClose - close a cursor */ 2276 zipfileFilter, /* xFilter - configure scan constraints */ 2277 zipfileNext, /* xNext - advance a cursor */ 2278 zipfileEof, /* xEof - check for end of scan */ 2279 zipfileColumn, /* xColumn - read data */ 2280 0, /* xRowid - read data */ 2281 zipfileUpdate, /* xUpdate */ 2282 zipfileBegin, /* xBegin */ 2283 0, /* xSync */ 2284 zipfileCommit, /* xCommit */ 2285 zipfileRollback, /* xRollback */ 2286 zipfileFindFunction, /* xFindMethod */ 2287 0, /* xRename */ 2288 0, /* xSavepoint */ 2289 0, /* xRelease */ 2290 0, /* xRollback */ 2291 0, /* xShadowName */ 2292 0 /* xIntegrity */ 2293 }; 2294 2295 /* REMINDER: Changes here should also be reflected in the ".safe" 2296 ** command of the CLI 2297 */ 2298 int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); 2299 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); 2300 if( rc==SQLITE_OK ){ 2301 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, 2302 zipfileStep, zipfileFinal 2303 ); 2304 } 2305 assert( sizeof(i64)==8 ); 2306 assert( sizeof(u32)==4 ); 2307 assert( sizeof(u16)==2 ); 2308 assert( sizeof(u8)==1 ); 2309 return rc; 2310 } 2311 #else /* SQLITE_OMIT_VIRTUALTABLE */ 2312 # define zipfileRegister(x) SQLITE_OK 2313 #endif 2314 2315 #ifdef _WIN32 2316 __declspec(dllexport) 2317 #endif 2318 int sqlite3_zipfile_init( 2319 sqlite3 *db, 2320 char **pzErrMsg, 2321 const sqlite3_api_routines *pApi 2322 ){ 2323 SQLITE_EXTENSION_INIT2(pApi); 2324 (void)pzErrMsg; /* Unused parameter */ 2325 return zipfileRegister(db); 2326 }