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