/ Check-in [55cf920c]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add support for invoking encryption hooks to zonefile. And mock encryption method "xor" for testing.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | zonefile
Files: files | file ages | folders
SHA3-256:55cf920c5a13473d04f0cb885117c04b2bc054bfed6ee549be84cb9485c104d2
User & Date: dan 2018-02-19 21:07:20
Context
2018-02-20
18:47
Instead of just the frame number, store frame sizes and offsets in zonefile shadow table %_shadow_idx. check-in: 56801c46 user: dan tags: zonefile
2018-02-19
21:07
Add support for invoking encryption hooks to zonefile. And mock encryption method "xor" for testing. check-in: 55cf920c user: dan tags: zonefile
16:28
Add support for the ExtendedHeaderSize header field to zonefile. check-in: 78267a09 user: dan tags: zonefile
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to ext/zonefile/zonefile.c.

30
31
32
33
34
35
36
37














































































































38
39
40
41
42
43
44
45
46
...
353
354
355
356
357
358
359
360




361

362
363
364

365
366

367
368
369
370
371
372
373
374
...
401
402
403
404
405
406
407
408
409
410
411
412
413
414

415
416
417
418
419
420
421
...
543
544
545
546
547
548
549

























550
551
552
553
554
555
556
557
558
559
560
561
562
563

564
565
566
567
568
569
570
...
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602


603
604
605
606
607
608
609
610
611
612
613




614
615
616
617
618
619
620
...
698
699
700
701
702
703
704
705
706
707
708

709
710
711
712
713


714
715
716
717
718
719
720
721
722
723
724
725
726
727
728






729
730
731
732
733
734
735
...
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774

775
776
777
778
779
780
781
...
785
786
787
788
789
790
791
792












793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
...
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
...
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
...
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
...
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
...
968
969
970
971
972
973
974
975
976
977
978

979
980
981
982
983
984
985

986
987
988
989
990
991
992
993

994
995
996
997
998
999
1000
....
1005
1006
1007
1008
1009
1010
1011

1012
1013
1014
1015
1016
1017
1018
....
1034
1035
1036
1037
1038
1039
1040

1041
1042
1043
1044
1045
1046
1047
....
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
....
1243
1244
1245
1246
1247
1248
1249



1250
1251
1252
1253
1254
1255
1256
....
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
....
1446
1447
1448
1449
1450
1451
1452












































1453
1454
1455
1456
1457
1458
1459
....
1468
1469
1470
1471
1472
1473
1474





1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498

1499

1500
1501
1502
1503
1504
1505
1506
....
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521





1522
1523
1524
1525
1526
1527
1528
1529
1530
1531

1532
1533
1534
1535
1536
1537
1538
....
1545
1546
1547
1548
1549
1550
1551

1552
1553
1554
1555
1556
1557
1558
....
1567
1568
1569
1570
1571
1572
1573

1574
1575
1576
1577
1578
1579
1580
....
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
....
1864
1865
1866
1867
1868
1869
1870
















1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881

1882
1883

1884
1885
1886
1887
1888
1889
1890
....
1894
1895
1896
1897
1898
1899
1900

1901
1902
1903
1904
1905
1906
1907
1908
....
1937
1938
1939
1940
1941
1942
1943











1944
1945
1946
1947
1948
1949
1950
....
1966
1967
1968
1969
1970
1971
1972
1973
1974









1975
1976
1977
1978
1979
1980



1981

1982
1983



1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005

2006
2007
2008
2009
2010
2011
2012
....
2044
2045
2046
2047
2048
2049
2050











2051
2052
2053
2054
2055
2056
2057
....
2108
2109
2110
2111
2112
2113
2114

2115
2116
2117
2118
2119
2120
2121
2122
2123
2124










2125

2126
2127
2128



2129
2130

2131
2132
2133
2134
2135
2136
2137
# define ALWAYS(X)      ((X)?1:(assert(0),0))
# define NEVER(X)       ((X)?(assert(0),1):0)
#else
# define ALWAYS(X)      (X)
# define NEVER(X)       (X)
#endif
#endif   /* SQLITE_AMALGAMATION */















































































































#define ZONEFILE_DEFAULT_MAXAUTOFRAMESIZE (64*1024)
#define ZONEFILE_DEFAULT_ENCRYPTION       0
#define ZONEFILE_DEFAULT_COMPRESSION      0
#define ZONEFILE_DEFAULT_DICTSIZE         (64*1024)

#define ZONEFILE_MAGIC_NUMBER 0x464B3138

#define ZONEFILE_SZ_HEADER           32
#define ZONEFILE_SZ_KEYOFFSETS_ENTRY 20
................................................................................
    0,
    zfLz4CompressBound, zfLz4hcCompress, 
    zfGenericUncompressSize, zfLz4Uncompress
  },
#endif /* SQLITE_HAVE_LZ4 */
};

static ZonefileCompress *zonefileCompress(const char *zName){




  int i;

  for(i=0; i<sizeof(aZonefileCompress)/sizeof(aZonefileCompress[0]); i++){
    if( sqlite3_stricmp(aZonefileCompress[i].zName, zName)==0 ){
      return &aZonefileCompress[i];

    }
  }

  return 0;
}

static ZonefileCompress *zonefileCompressByValue(int eType){
  int i;
  for(i=0; i<sizeof(aZonefileCompress)/sizeof(aZonefileCompress[0]); i++){
    if( aZonefileCompress[i].eType==eType ){
      return &aZonefileCompress[i];
................................................................................



/*
** A structure to store the parameters for a single zonefile_write()
** invocation. 
*/
typedef struct ZonefileWrite ZonefileWrite;
struct ZonefileWrite {
  ZonefileCompress *pCmpIdx;      /* For compressing the index */
  ZonefileCompress *pCmpData;     /* For compressing each frame */
  int encryptionType;
  int maxAutoFrameSize;
  int debugExtendedHeaderSize;    /* Size of extended header */

};

/*
** A structure to store a deserialized zonefile header in.
*/
typedef struct ZonefileHeader ZonefileHeader;
struct ZonefileHeader {
................................................................................

int zonefileIsAutoFrame(sqlite3_value *pFrame){
  return (
      sqlite3_value_type(pFrame)==SQLITE_INTEGER 
   && sqlite3_value_int64(pFrame)==-1
  );
}


























static int zonefileGetParams(
  sqlite3_context *pCtx,          /* Leave any error message here */
  const char *zJson,              /* JSON configuration parameter (or NULL) */
  ZonefileWrite *p                /* Populate this object before returning */
){
  sqlite3 *db = sqlite3_context_db_handle(pCtx);
  sqlite3_stmt *pStmt = 0;
  char *zErr = 0;
  int rc = SQLITE_OK;
  int rc2;

  memset(p, 0, sizeof(ZonefileWrite));
  p->maxAutoFrameSize = ZONEFILE_DEFAULT_MAXAUTOFRAMESIZE;

  p->pCmpData = p->pCmpIdx = zonefileCompressByValue(0);

  rc = zonefilePrepare(db, &pStmt, &zErr,"SELECT key, value FROM json_each(?)");
  if( rc==SQLITE_OK ){
    sqlite3_bind_text(pStmt, 1, zJson, -1, SQLITE_STATIC);
  }
  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
................................................................................
      p->debugExtendedHeaderSize = iVal;
    }else
    if( sqlite3_stricmp("maxAutoFrameSize", zKey)==0 ){
      p->maxAutoFrameSize = iVal;
    }else
    if( sqlite3_stricmp("compressionTypeIndexData", zKey)==0 ){
      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
      p->pCmpIdx = zonefileCompress(zName);
      if( p->pCmpIdx==0 ){
        rc = SQLITE_ERROR;
        zErr = sqlite3_mprintf("unknown compression scheme: \"%s\"", zName);
      }
    }else
    if( sqlite3_stricmp("compressionTypeContent", zKey)==0 ){
      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
      p->pCmpData = zonefileCompress(zName);
      if( p->pCmpData==0 ){
        rc = SQLITE_ERROR;
        zErr = sqlite3_mprintf("unknown compression scheme: \"%s\"", zName);
      }
    }else
    if( sqlite3_stricmp("encryptionType", zKey)==0 ){
      p->encryptionType = iVal;


    }else{
      rc = SQLITE_ERROR;
      zErr = sqlite3_mprintf("unknown parameter name: \"%s\"", zKey);
    }
  }
  rc2 = sqlite3_finalize(pStmt);
  if( rc==SQLITE_OK ) rc = rc2;

  if( zErr ){
    sqlite3_result_error(pCtx, zErr, -1);
    sqlite3_free(zErr);




  }
  return rc;
}

/*
** Check that there is room in buffer pBuf for at least nByte bytes more 
** data. If not, attempt to allocate more space. If the allocation attempt
................................................................................
  return pFd;
}

static void zonefileFileClose(FILE *pFd){
  if( pFd ) fclose(pFd);
}

static int zonefileAppendCompressed(
  sqlite3_context *pCtx,          /* Leave any error message here */
  ZonefileCompress *pMethod,      /* Compression method object */
  void *pCmp,                     /* Compression handle */

  ZonefileBuffer *pTo,            /* Append new data here */
  ZonefileBuffer *pFrom           /* Input buffer */
){
  int rc = SQLITE_OK;
  if( pFrom->n ){


    if( pMethod->eType==ZONEFILE_COMPRESSION_NONE ){
      if( zonefileBufferGrow(pCtx, pTo, pFrom->n) ){
        rc = SQLITE_ERROR;
      }else{
        zonefileAppendBlob(pTo, pFrom->a, pFrom->n);
      }
    }else{
      int nReq = pMethod->xCompressBound(pCmp, pFrom->n);
      if( zonefileBufferGrow(pCtx, pTo, nReq) ) return SQLITE_ERROR;
      rc = pMethod->xCompress(pCmp, &pTo->a[pTo->n], &nReq, pFrom->a, pFrom->n);
      pTo->n += nReq;
      if( rc!=SQLITE_OK ){
        return rc;
      }
    }






  }
  return SQLITE_OK;
}

/*
** Append nByte bytes of garbage data to the file opened with pFd. Return
** SQLITE_OK if successful, or SQLITE_ERROR if an error occurs.
................................................................................
  sqlite3_context *pCtx,       /* Context object */
  int objc,                       /* Number of SQL arguments */
  sqlite3_value **objv            /* Array of SQL arguments */
){
  const char *zFile = 0;          /* File to write to */
  const char *zTbl = 0;           /* Database object to read from */
  const char *zJson = 0;          /* JSON configuration parameters */
  ZonefileWrite sWrite;           /* Decoded JSON parameters */
  int nKey = 0;                   /* Number of keys in new zonefile */
  int nFrame = 0;                 /* Number of frames in new zonefile */
  sqlite3_stmt *pStmt = 0;        /* SQL used to read data from source table */
  FILE *pFd = 0;
  int rc;
  sqlite3_value *pPrev = 0;
  char *zErr = 0;
  void *pCmp = 0;                 /* Data compressor handle */
  u32 iOff;


  ZonefileBuffer sFrameIdx = {0, 0, 0};     /* Array of frame offsets */
  ZonefileBuffer sKeyIdx = {0, 0, 0};       /* Array of key locations */
  ZonefileBuffer sData = {0, 0, 0};         /* All completed frames so far */
  ZonefileBuffer sFrame = {0, 0, 0};        /* Current frame (uncompressed) */
  ZonefileBuffer sDict = {0, 0, 0};         /* Compression model (if any) */
  ZonefileBuffer sSample = {0,0,0};         /* Sample data for compressor */
................................................................................

  assert( objc==2 || objc==3 );
  zFile = (const char*)sqlite3_value_text(objv[0]);
  zTbl = (const char*)sqlite3_value_text(objv[1]);
  if( objc==3 ){
    zJson = (const char*)sqlite3_value_text(objv[2]);
  }
  if( zonefileGetParams(pCtx, zJson, &sWrite) ) return;













  /* Check that the index-data compressor is not one that uses an external
  ** dictionary. This is not permitted as there is no sense in using a
  ** dictionary to compress a single blob of data, and the index-data
  ** compressor only ever compresses a single frame. Also, there is nowhere
  ** in the file-format to store such a dictionary for the index-data.  */
  if( sWrite.pCmpIdx->xTrain ){
    zonefileCtxError(pCtx, 
        "compressor \"%s\" may not be used to compress the zonefile index", 
        sWrite.pCmpIdx->zName
    );
    goto zone_write_out;
  }

  if( sWrite.pCmpData->xOpen ){
    rc = sWrite.pCmpData->xOpen(&pCmp, 0, 0);
    if( rc!=SQLITE_OK ){
      zonefileCtxError(pCtx, "error in compressor construction");
      goto zone_write_out;
    }
  }

  /* Prepare the SQL statement used to read data from the source table. This
................................................................................
    sqlite3_result_error(pCtx, zErr, -1);
    sqlite3_free(zErr);
    goto zone_write_out;
  }

  /* If the data compressor uses a global dictionary, create the dictionary
  ** and store it in buffer sDict.  */
  if( sWrite.pCmpData->xTrain ){
    int nSample = 0;

    while( SQLITE_ROW==sqlite3_step(pStmt) ){
      int nByte = sqlite3_column_bytes(pStmt, 2);
      const u8 *aByte = (const u8*)sqlite3_column_blob(pStmt, 2);
      if( zonefileBufferGrow(pCtx, &sSample, nByte) ){
        goto zone_write_out;
................................................................................
    }

    if( zonefileBufferGrow(pCtx, &sDict, ZONEFILE_DEFAULT_DICTSIZE) ){
      goto zone_write_out;
    }
    sDict.n = sDict.nAlloc;

    rc = sWrite.pCmpData->xTrain(
        pCmp, sDict.a, &sDict.n, sSample.a, aSample, nSample
    );
    if( rc!=SQLITE_OK ){
      zonefileCtxError(pCtx, "error generating dictionary");
      goto zone_write_out;
    }
  }
................................................................................
    sqlite3_value *pFrame = sqlite3_column_value(pStmt, 1);
    int nBlob = sqlite3_column_bytes(pStmt, 2);
    const u8 *pBlob = (const u8*)sqlite3_column_blob(pStmt, 2);

    int bAuto = zonefileIsAutoFrame(pFrame);
    if( sFrame.n>0 ){
      if( zonefileCompareValue(pFrame, pPrev) 
       || (bAuto && (sFrame.n+nBlob)>sWrite.maxAutoFrameSize)
      ){
        /* Add new entry to sFrame */
        if( zonefileBufferGrow(pCtx, &sFrameIdx, 4) 
         || zonefileAppendCompressed(pCtx, sWrite.pCmpData, pCmp,&sData,&sFrame)
        ){
          goto zone_write_out;
        }
        sFrame.n = 0;
        zonefileAppend32(&sFrameIdx, sData.n);
        sqlite3_value_free(pPrev);
        pPrev = 0;
................................................................................
    if( zonefileBufferGrow(pCtx, &sFrame, nBlob) ) goto zone_write_out;
    zonefileAppendBlob(&sFrame, pBlob, nBlob);
    nKey++;
  }

  if( sFrame.n>0 ){
    if( zonefileBufferGrow(pCtx, &sFrameIdx, 4) 
     || zonefileAppendCompressed(pCtx, sWrite.pCmpData, pCmp, &sData, &sFrame)
    ){
      goto zone_write_out;
    }
    zonefileAppend32(&sFrameIdx, sData.n);
    nFrame++;
  }

  /* If a compression method was specified, compress the key-index here */
  if( sWrite.pCmpIdx->eType!=ZONEFILE_COMPRESSION_NONE ){
    if( zonefileBufferGrow(pCtx, &sFrameIdx, sKeyIdx.n) ) goto zone_write_out;
    zonefileAppendBlob(&sFrameIdx, sKeyIdx.a, sKeyIdx.n);
    zonefileBufferFree(&sKeyIdx);
    rc = zonefileAppendCompressed(pCtx, sWrite.pCmpIdx, 0, &sKeyIdx,&sFrameIdx);
    sFrameIdx.n = 0;
    if( rc ) goto zone_write_out;
  }

  /* Create the zonefile header in the in-memory buffer */
  memset(aHdr, 0, ZONEFILE_SZ_HEADER);
  zonefilePut32(&aHdr[0], ZONEFILE_MAGIC_NUMBER);
  aHdr[4] = sWrite.pCmpIdx->eType;
  aHdr[5] = sWrite.pCmpData->eType;
  iOff = ZONEFILE_SZ_HEADER + sFrameIdx.n + sKeyIdx.n;
  zonefilePut32(&aHdr[6], sDict.n ? iOff+sWrite.debugExtendedHeaderSize : 0);
  zonefilePut32(&aHdr[10], iOff + sWrite.debugExtendedHeaderSize + sDict.n);
  zonefilePut32(&aHdr[14], nFrame);
  zonefilePut32(&aHdr[18], nKey);
  aHdr[22] = sWrite.encryptionType;
  aHdr[23] = 0;                   /* Encryption key index */
  aHdr[24] = 0;                   /* extended header version */
  aHdr[25] = sWrite.debugExtendedHeaderSize;
  assert( ZONEFILE_SZ_HEADER>=26 );

  rc = zonefileFileWrite(pFd, aHdr, ZONEFILE_SZ_HEADER);
  if( rc==SQLITE_OK ) rc = zonefilePad(pFd, sWrite.debugExtendedHeaderSize);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sFrameIdx.a, sFrameIdx.n);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sKeyIdx.a, sKeyIdx.n);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sDict.a, sDict.n);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sData.a, sData.n);
  if( rc ){
    zonefileCtxError(pCtx, "error writing file \"%s\" (fwrite())", zFile);
    goto zone_write_out;
................................................................................

  if( fclose(pFd) ){
    zonefileCtxError(pCtx, "error writing file \"%s\" (fclose())", zFile);
  }
  pFd = 0;

 zone_write_out:
  if( pCmp ) sWrite.pCmpData->xClose(pCmp);
  if( pFd ) fclose(pFd);
  sqlite3_value_free(pPrev);
  sqlite3_finalize(pStmt);

  zonefileBufferFree(&sFrameIdx);
  zonefileBufferFree(&sKeyIdx);
  zonefileBufferFree(&sFrame);
  zonefileBufferFree(&sDict);
  zonefileBufferFree(&sData);
  zonefileBufferFree(&sSample);
  sqlite3_free(aSample);

}

typedef struct ZonefileFilesTab ZonefileFilesTab;
struct ZonefileFilesTab {
  sqlite3_vtab base;              /* Base class - must be first */
  sqlite3 *db;
  char *zBase;                    /* Name of this table */
  char *zDb;                      /* Database containing this table */

  sqlite3_stmt *pInsert;          /* Insert into the %_shadow_file table */
  sqlite3_stmt *pInsertIdx;       /* Insert into the %_shadow_idx table */
  sqlite3_stmt *pDeleteIdx;       /* Delete by fileid from %_shadow_idx table */
  sqlite3_stmt *pDelete;          /* Delete by rowid from %_shadow_file table */
};

typedef struct ZonefileFilesCsr ZonefileFilesCsr;
................................................................................

/*
** This function does the work of xCreate (if bCreate!=0) or xConnect
** (if bCreate==0) for the zonefile_files module.
*/
static int zffCreateConnect(
  int bCreate,

  sqlite3 *db,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  ZonefileFilesTab *p;
  const char *zName = argv[2];
................................................................................
    memset(p, 0, sizeof(ZonefileFilesTab));
    p->zBase = (char*)&p[1];
    memcpy(p->zBase, zName, nName-6);
    p->zBase[nName-6] = '\0';
    p->zDb = &p->zBase[nName+1];
    memcpy(p->zDb, zDb, nDb+1);
    p->db = db;

    rc = sqlite3_declare_vtab(db, ZONEFILE_FILES_SCHEMA);
  }

  if( rc!=SQLITE_OK ){
    sqlite3_free(p);
    p = 0;
  }
................................................................................
static int zffCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zffCreateConnect(1, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile_files virtual table module xConnect method.
*/
static int zffConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zffCreateConnect(0, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile_files virtual table module xDisconnect method.
*/
static int zffDisconnect(sqlite3_vtab *pVtab){
  ZonefileFilesTab *pTab = (ZonefileFilesTab*)pVtab;
................................................................................
}

/* 
** zonefile_files virtual table module xColumn method.
*/
static int zffColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  ZonefileFilesCsr *pCsr = (ZonefileFilesCsr*)cur;



  switch( i ){
    case 0: /* filename */
      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pSelect, 0));
      break;
    case 1: /* ekey */
      break;
    case 2: { /* header */
................................................................................
  }

  if( rc==SQLITE_OK && hdr.numKeys>0 ){
    u8 *aKey;                     /* Entire KeyOffsets array */
    int nKey;                     /* Size of buffer aKey[] in bytes */
    int i;

    assert( hdr.encryptionType==0 );
    rc = zonefileLoadIndex(&hdr, pFd, &aKey, &nKey, &pTab->base.zErrMsg);

    if( rc==SQLITE_OK && pTab->pInsertIdx==0 ){
      rc = zonefilePrepare(pTab->db, &pTab->pInsertIdx, &pTab->base.zErrMsg,
          "INSERT INTO %Q.'%q_shadow_idx'(k, fileid, frame, ofst, sz)"
          "VALUES(?,?,?,?,?)",
          pTab->zDb, pTab->zBase
................................................................................
    }
    sqlite3_free(aKey);
  }

  zonefileFileClose(pFd);
  return rc;
}













































/*
** zonefile_files virtual table module xUpdate method.
**
** A delete specifies a single argument - the rowid of the row to remove.
** 
** Update and insert operations pass:
................................................................................
  sqlite3_value **apVal, 
  sqlite_int64 *pRowid
){
  int rc = SQLITE_OK;
  ZonefileFilesTab *pTab = (ZonefileFilesTab*)pVtab;

  if( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ){





    if( pTab->pDelete==0 ){
      rc = zonefilePrepare(pTab->db, &pTab->pDelete, &pVtab->zErrMsg,
          "DELETE FROM %Q.'%q_shadow_file' WHERE fileid=?",
          pTab->zDb, pTab->zBase
      );
    }
    if( rc==SQLITE_OK && pTab->pDeleteIdx==0 ){
      rc = zonefilePrepare(pTab->db, &pTab->pDeleteIdx, &pVtab->zErrMsg,
          "DELETE FROM %Q.'%q_shadow_idx' WHERE fileid=?",
          pTab->zDb, pTab->zBase
      );
    }

    if( rc==SQLITE_OK ){
      sqlite3_bind_value(pTab->pDelete, 1, apVal[0]);
      sqlite3_step(pTab->pDelete);
      rc = sqlite3_reset(pTab->pDelete);
    }
    if( rc==SQLITE_OK ){
      sqlite3_bind_value(pTab->pDeleteIdx, 1, apVal[0]);
      sqlite3_step(pTab->pDeleteIdx);
      rc = sqlite3_reset(pTab->pDeleteIdx);
    }
  }

  if( nVal>1 ){

    const char *zFile = (const char*)sqlite3_value_text(apVal[2]);

    if( pTab->pInsert==0 ){
      rc = zonefilePrepare(pTab->db, &pTab->pInsert, &pVtab->zErrMsg,
          "INSERT INTO %Q.'%q_shadow_file'(filename) VALUES(?)",
          pTab->zDb, pTab->zBase
      );
................................................................................
      sqlite3_step(pTab->pInsert);
      rc = sqlite3_reset(pTab->pInsert);
    }

    /* Populate the %_shadow_idx table with entries for all keys in
    ** the zonefile just added to %_shadow_file.  */
    if( rc==SQLITE_OK ){
      i64 iFileid = sqlite3_last_insert_rowid(pTab->db);
      rc = zonefilePopulateIndex(pTab, zFile, iFileid);
    }





  }

  return rc;
}

typedef struct ZonefileTab ZonefileTab;
struct ZonefileTab {
  sqlite3_vtab base;         /* Base class - must be first */
  sqlite3 *db;
  sqlite3_stmt *pIdToName;   /* Translate fileid to filename */

  char *zName;               /* Name of this table */
  char *zDb;                 /* Name of db containing this table */
};

typedef struct ZonefileCsr ZonefileCsr;
struct ZonefileCsr {
  sqlite3_vtab_cursor base;  /* Base class - must be first */
................................................................................
**
**   argv[0]   -> module name  ("zonefile")
**   argv[1]   -> database name
**   argv[2]   -> table name
*/
static int zonefileCreateConnect(
  int bCreate,

  sqlite3 *db,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  ZonefileTab *p;
  const char *zName = argv[2];
................................................................................
  }else{
    memset(p, 0, sizeof(ZonefileTab));
    p->zName = (char*)&p[1];
    memcpy(p->zName, zName, nName+1);
    p->zDb = &p->zName[nName+1];
    memcpy(p->zDb, zDb, nDb+1);
    p->db = db;

  
    if( bCreate ){
      char *zSql = sqlite3_mprintf(
          "CREATE TABLE %Q.'%q_shadow_idx'(" 
          "  k INTEGER PRIMARY KEY,"
          "  fileid INTEGER,"
          "  frame INTEGER,"
................................................................................
static int zonefileCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zonefileCreateConnect(1, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile virtual table module xConnect method.
*/
static int zonefileConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zonefileCreateConnect(0, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile virtual table module xDisconnect method.
*/
static int zonefileDisconnect(sqlite3_vtab *pVtab){
  ZonefileTab *pTab = (ZonefileTab*)pVtab;
................................................................................
  }else if( rc==SQLITE_ERROR ){
    zonefileCtxError(pCtx, "failed to uncompress frame");
  }

  sqlite3_free(aUn);
  return rc;
}

















static int zonefileGetValue(sqlite3_context *pCtx, ZonefileCsr *pCsr){
  ZonefileTab *pTab = (ZonefileTab*)pCsr->base.pVtab;
  const char *zFile = 0;
  char *zErr = 0;
  FILE *pFd = 0;
  int rc = SQLITE_OK;
  u32 iOff = 0;                   /* Offset of frame in file */
  u32 szFrame = 0;                /* Size of frame in bytes */
  int iKeyOff = 0;                /* Offset of record within frame */
  int szKey = 0;                  /* Uncompressed size of record in bytes */

  ZonefileHeader hdr;
  ZonefileCompress *pCmpMethod = 0;

  void *pCmp = 0;

  if( pTab->pIdToName==0 ){
    rc = zonefilePrepare(pTab->db, &pTab->pIdToName, &pTab->base.zErrMsg, 
        "SELECT filename FROM %Q.'%q_shadow_file' WHERE fileid=?",
        pTab->zDb, pTab->zName
    );
................................................................................
    }
  }

  iKeyOff = sqlite3_column_int(pCsr->pSelect, 3);
  szKey = sqlite3_column_int(pCsr->pSelect, 4);

  /* Open the file to read the blob from */

  sqlite3_bind_int64(pTab->pIdToName, 1, sqlite3_column_int64(pCsr->pSelect,1));
  if( SQLITE_ROW==sqlite3_step(pTab->pIdToName) ){
    zFile = (const char*)sqlite3_column_text(pTab->pIdToName, 0);
    pFd = zonefileFileOpen(zFile, 0, &zErr);
  }
  if( zFile==0 ){
    rc = sqlite3_reset(pTab->pIdToName);
    if( rc!=SQLITE_OK ){
................................................................................
      }
    }
    if( rc==SQLITE_OK ){
      rc = pCmpMethod->xOpen(&pCmp, aDict, nDict);
    }
    sqlite3_free(aDict);
  }












  /* Find the offset (iOff) and size (szFrame) of the frame that the
  ** record is stored in.  */
  if( rc==SQLITE_OK ){
    int iFrame = sqlite3_column_int(pCsr->pSelect, 2);
    u8 aSpace[8] = {0,0,0,0,0,0,0,0};
    u8 *aOff = aSpace;
................................................................................
    sqlite3_free(aFree);
  }

  /* Read some data into memory. If the data is uncompressed, then just
  ** the required record is read. Otherwise, the entire frame is read
  ** into memory.  */
  if( rc==SQLITE_OK ){
    int sz = (pCmpMethod ? (int)szFrame : szKey);
    i64 ofst = iOff + (pCmpMethod ? 0 : iKeyOff);









    u8 *aBuf = sqlite3_malloc(sz);
    if( aBuf==0 ){
      rc = SQLITE_NOMEM;
    }else{
      rc = zonefileFileRead(pFd, aBuf, sz, hdr.byteOffsetFrames + ofst);
      if( rc==SQLITE_OK ){



        if( pCmpMethod==0 ){

          sqlite3_result_blob(pCtx, aBuf, szKey, zonefileFree);
          aBuf = 0;



        }else{
          rc = zonefileCtxUncompress(
              pCtx, pCmpMethod, pCmp, aBuf, szFrame, iKeyOff, szKey
          );
        }
      }else{
        zErr = sqlite3_mprintf(
            "failed to read %d bytes at offset %d from file \"%s\"", 
            sz, (int)(hdr.byteOffsetFrames+ofst), zFile
        );
      }
      sqlite3_free(aBuf);
    }
  }

  sqlite3_reset(pTab->pIdToName);
  if( zErr ){
    assert( rc!=SQLITE_OK );
    sqlite3_result_error(pCtx, zErr, -1);
    sqlite3_free(zErr);
  }
  zonefileFileClose(pFd);

  if( pCmpMethod ) pCmpMethod->xClose(pCmp);
  return rc;
}

/* 
** zonefile virtual table module xColumn method.
*/
................................................................................
** zonefile virtual table module xRowid method.
*/
static int zonefileRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  ZonefileCsr *pCsr = (ZonefileCsr*)cur;
  *pRowid = sqlite3_column_int64(pCsr->pSelect, 0);
  return SQLITE_OK;
}












/*
** Register the "zonefile" extensions.
*/
static int zonefileRegister(sqlite3 *db){
  static sqlite3_module filesModule = {
    0,                            /* iVersion */
................................................................................
    const char *z;
    int n;
    void (*x)(sqlite3_context*,int,sqlite3_value**);
  } aFunc[] = {
    { "zonefile_write", 2, zonefileWriteFunc },
    { "zonefile_write", 3, zonefileWriteFunc },
  };


  int rc = SQLITE_OK;
  int i;

  for(i=0; rc==SQLITE_OK && i<sizeof(aFunc)/sizeof(aFunc[0]); i++){
    struct Func *p = &aFunc[i];
    rc = sqlite3_create_function(db, p->z, p->n, SQLITE_ANY, 0, p->x, 0, 0);
  }

  if( rc==SQLITE_OK ){










    rc = sqlite3_create_module(db, "zonefile_files", &filesModule, 0);

  }
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_module(db, "zonefile", &zonefileModule, 0);



  }


  return rc;
}

#else         /* SQLITE_OMIT_VIRTUALTABLE */
# define zonefileRegister(x) SQLITE_OK
#endif









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|







 







|
>
>
>
>

>


|
>


>
|







 







|
|





>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|







|

>







 







|
<
<
<
<



|
|
|
|
|
|
|
|
>
>











>
>
>
>







 







|



>





>
>

|






|






>
>
>
>
>
>







 







|









>







 







|
>
>
>
>
>
>
>
>
>
>
>
>






|


|




|
|







 







|







 







|







 







|



|







 







|








|



|







|
|

|
|


|


|



|







 







|



>







>








>







 







>







 







>







 







|












|







 







>
>
>







 







<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
>

>







 







|


>
>
>
>
>










>







 







>







 







>







 







|












|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











>


>







 







>
|







 







>
>
>
>
>
>
>
>
>
>
>







 







|
|
>
>
>
>
>
>
>
>
>
|



|

>
>
>

>
|
|
>
>
>








|













>







 







>
>
>
>
>
>
>
>
>
>
>







 







>










>
>
>
>
>
>
>
>
>
>
|
>


|
>
>
>


>







30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
...
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
...
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
...
724
725
726
727
728
729
730
731




732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
...
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
...
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
...
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
...
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
....
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
....
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
....
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
....
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
....
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
....
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
....
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
....
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
....
1590
1591
1592
1593
1594
1595
1596

1597
1598
1599
1600
1601
1602
1603
....
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
....
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
....
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
....
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
....
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
....
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
....
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
....
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
....
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
....
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
....
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
....
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
# define ALWAYS(X)      ((X)?1:(assert(0),0))
# define NEVER(X)       ((X)?(assert(0),1):0)
#else
# define ALWAYS(X)      (X)
# define NEVER(X)       (X)
#endif
#endif   /* SQLITE_AMALGAMATION */

#ifndef SQLITE_HAVE_ZONEFILE_CODEC
typedef struct ZonefileCodec ZonefileCodec;

struct ZonefileCodec {
  u8 aKey[16];
};

/* Create a new encryption module instance using algorithm iAlg.
**
**   iAlg==1   AES128 CTR
**   iAlg==2   AES128 CBC
**   iAlg==3   AES256 CTR
**   iAlg==4   AES256 CBC
**   iAlg==5   XOR          Testing use only
**
** If the requested algorithm is not available, the routine returns
** a NULL pointer.  NULL is also returned on a OOM error.
**
** Use zonefileCodecDestroy() to reclaim memory.
*/
static int zonefileCodecCreate(
  int iAlg, 
  unsigned char *pKey, int nKey, 
  ZonefileCodec **pp, 
  char **pzErr
){
  ZonefileCodec *pRet;
  int rc = SQLITE_OK;
  
  if( iAlg!=5 ){
    *pzErr = sqlite3_mprintf("unsupported encryption method: %d", iAlg);
    rc = SQLITE_ERROR;
  }else{
    *pp = pRet = (ZonefileCodec*)sqlite3_malloc(sizeof(ZonefileCodec));
    if( pRet==0 ){
      rc = SQLITE_NOMEM;
    }else{
      int i;
      for(i=0; i<sizeof(pRet->aKey); i++){
        pRet->aKey[i] = pKey[i % nKey];
      }
    }
  }

  return rc;
}

/* Return the size of the nonce used for the given encryption module */
static int zonefileCodecNonceSize(ZonefileCodec *pCodec){
  return 16;
}

/* Encrypt in-place.
**
** The size of the content will grow by the nonce size.  Hence, the
** buffer must have at least nonce bytes of extra space available at
** the end to accommodate that growth.  When persisting results, be
** sure to include the extra bytes.
*/
static void zonefileCodecEncode(
  ZonefileCodec *pCodec, 
  unsigned char *pIn, int nIn
){
  int i;
  u8 *aNonce = &pIn[nIn];
  sqlite3_randomness(16, aNonce);
  for(i=0; i<nIn; i++){
    pIn[i] = pIn[i] ^ aNonce[i%16] ^ pCodec->aKey[i%16];
  }
}

/* Decrypt in-place.
**
** The size of the decrypted text will be less than the input buffer
** by nonce-size bytes.
*/
static void zonefileCodecDecode(
  ZonefileCodec *pCodec, 
  unsigned char *pIn, int nIn
){
  int i;
  u8 *aNonce = &pIn[nIn-16];
  for(i=0; i<nIn-16; i++){
    pIn[i] = pIn[i] ^ aNonce[i%16] ^ pCodec->aKey[i%16];
  }
}

/* Destroy an encryption module.
** It is harmless to pass in a NULL pointer.
*/
static void zonefileCodecDestroy(ZonefileCodec *pCodec){
  sqlite3_free(pCodec);
}
#endif                           /* SQLITE_HAVE_ZONEFILE_CODEC */

typedef struct ZonefileGlobal ZonefileGlobal;
typedef struct ZonefileKey ZonefileKey;
struct ZonefileGlobal {
  ZonefileKey *pList;
};
struct ZonefileKey {
  const char *zName;              /* Table name */
  const char *zDb;                /* Database name */
  i64 iFileid;                    /* File id */
  const char *zKey;               /* Key buffer */
  int nKey;                       /* Size of zKey in bytes */
  ZonefileKey *pNext;             /* Next key on same db connection */
};


#define ZONEFILE_DEFAULT_MAXAUTOFRAMESIZE (64*1024)
#define ZONEFILE_DEFAULT_ENCRYPTION       1
#define ZONEFILE_DEFAULT_COMPRESSION      0
#define ZONEFILE_DEFAULT_DICTSIZE         (64*1024)

#define ZONEFILE_MAGIC_NUMBER 0x464B3138

#define ZONEFILE_SZ_HEADER           32
#define ZONEFILE_SZ_KEYOFFSETS_ENTRY 20
................................................................................
    0,
    zfLz4CompressBound, zfLz4hcCompress, 
    zfGenericUncompressSize, zfLz4Uncompress
  },
#endif /* SQLITE_HAVE_LZ4 */
};

static int zonefileCompress(
  const char *zName,              /* Name of requested compression method */
  ZonefileCompress **pp,          /* OUT: Pointer to compression object */
  char **pzErr                    /* OUT: Error message */
){
  int i;
  assert( *pzErr==0 );
  for(i=0; i<sizeof(aZonefileCompress)/sizeof(aZonefileCompress[0]); i++){
    if( sqlite3_stricmp(aZonefileCompress[i].zName, zName)==0 ){
      *pp = &aZonefileCompress[i];
      return SQLITE_OK;
    }
  }
  *pzErr = sqlite3_mprintf("unknown compression scheme: \"%s\"", zName);
  return SQLITE_ERROR;
}

static ZonefileCompress *zonefileCompressByValue(int eType){
  int i;
  for(i=0; i<sizeof(aZonefileCompress)/sizeof(aZonefileCompress[0]); i++){
    if( aZonefileCompress[i].eType==eType ){
      return &aZonefileCompress[i];
................................................................................



/*
** A structure to store the parameters for a single zonefile_write()
** invocation. 
*/
typedef struct ZonefileParam ZonefileParam;
struct ZonefileParam {
  ZonefileCompress *pCmpIdx;      /* For compressing the index */
  ZonefileCompress *pCmpData;     /* For compressing each frame */
  int encryptionType;
  int maxAutoFrameSize;
  int debugExtendedHeaderSize;    /* Size of extended header */
  char *encryptionKey;            /* Encryption key */
};

/*
** A structure to store a deserialized zonefile header in.
*/
typedef struct ZonefileHeader ZonefileHeader;
struct ZonefileHeader {
................................................................................

int zonefileIsAutoFrame(sqlite3_value *pFrame){
  return (
      sqlite3_value_type(pFrame)==SQLITE_INTEGER 
   && sqlite3_value_int64(pFrame)==-1
  );
}

static int zonefileEncryption(const char *zName, int *peType, char **pzErr){
  struct Encryption {
    const char *zName;
    int eType;
  } a[] = {
    {"NONE", 0}, 
    {"AES_128_CTR", 1}, 
    {"AES_128_CBC", 2}, 
    {"AES_256_CTR", 3}, 
    {"AES_256_CBC", 4}, 
    {"XOR",         5}, 
  };
  int i;

  for(i=0; i<sizeof(a)/sizeof(a[0]); i++){
    if( 0==sqlite3_stricmp(zName, a[i].zName) ){
      *peType = a[i].eType;
      return SQLITE_OK;
    }
  }

  *pzErr = sqlite3_mprintf("unknown encryption type: %s", zName);
  return SQLITE_ERROR;
}

static int zonefileGetParams(
  sqlite3_context *pCtx,          /* Leave any error message here */
  const char *zJson,              /* JSON configuration parameter (or NULL) */
  ZonefileParam *p                /* Populate this object before returning */
){
  sqlite3 *db = sqlite3_context_db_handle(pCtx);
  sqlite3_stmt *pStmt = 0;
  char *zErr = 0;
  int rc = SQLITE_OK;
  int rc2;

  memset(p, 0, sizeof(ZonefileParam));
  p->maxAutoFrameSize = ZONEFILE_DEFAULT_MAXAUTOFRAMESIZE;
  p->encryptionType = ZONEFILE_DEFAULT_ENCRYPTION;
  p->pCmpData = p->pCmpIdx = zonefileCompressByValue(0);

  rc = zonefilePrepare(db, &pStmt, &zErr,"SELECT key, value FROM json_each(?)");
  if( rc==SQLITE_OK ){
    sqlite3_bind_text(pStmt, 1, zJson, -1, SQLITE_STATIC);
  }
  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
................................................................................
      p->debugExtendedHeaderSize = iVal;
    }else
    if( sqlite3_stricmp("maxAutoFrameSize", zKey)==0 ){
      p->maxAutoFrameSize = iVal;
    }else
    if( sqlite3_stricmp("compressionTypeIndexData", zKey)==0 ){
      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
      rc = zonefileCompress(zName, &p->pCmpIdx, &zErr);




    }else
    if( sqlite3_stricmp("compressionTypeContent", zKey)==0 ){
      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
      rc = zonefileCompress(zName, &p->pCmpData, &zErr);
    }else
    if( sqlite3_stricmp("encryptionKey", zKey)==0 ){
      const char *zKey = (const char*)sqlite3_column_text(pStmt, 1);
      p->encryptionKey = sqlite3_mprintf("%s", zKey);
      if( p->encryptionKey==0 ) rc = SQLITE_NOMEM;
    }else
    if( sqlite3_stricmp("encryptionType", zKey)==0 ){
      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
      rc = zonefileEncryption(zName, &p->encryptionType, &zErr);
    }else{
      rc = SQLITE_ERROR;
      zErr = sqlite3_mprintf("unknown parameter name: \"%s\"", zKey);
    }
  }
  rc2 = sqlite3_finalize(pStmt);
  if( rc==SQLITE_OK ) rc = rc2;

  if( zErr ){
    sqlite3_result_error(pCtx, zErr, -1);
    sqlite3_free(zErr);
  }else{
    if( p->encryptionKey==0 ){
      p->encryptionType = 0;
    }
  }
  return rc;
}

/*
** Check that there is room in buffer pBuf for at least nByte bytes more 
** data. If not, attempt to allocate more space. If the allocation attempt
................................................................................
  return pFd;
}

static void zonefileFileClose(FILE *pFd){
  if( pFd ) fclose(pFd);
}

static int zonefileAppendData(
  sqlite3_context *pCtx,          /* Leave any error message here */
  ZonefileCompress *pMethod,      /* Compression method object */
  void *pCmp,                     /* Compression handle */
  ZonefileCodec *pCodec,          /* Compression method, if any */
  ZonefileBuffer *pTo,            /* Append new data here */
  ZonefileBuffer *pFrom           /* Input buffer */
){
  int rc = SQLITE_OK;
  if( pFrom->n ){
    int nNonce = pCodec ? zonefileCodecNonceSize(pCodec) : 0;
    int nOrig = pTo->n;
    if( pMethod->eType==ZONEFILE_COMPRESSION_NONE ){
      if( zonefileBufferGrow(pCtx, pTo, pFrom->n + nNonce) ){
        rc = SQLITE_ERROR;
      }else{
        zonefileAppendBlob(pTo, pFrom->a, pFrom->n);
      }
    }else{
      int nReq = pMethod->xCompressBound(pCmp, pFrom->n);
      if( zonefileBufferGrow(pCtx, pTo, nReq + nNonce) ) return SQLITE_ERROR;
      rc = pMethod->xCompress(pCmp, &pTo->a[pTo->n], &nReq, pFrom->a, pFrom->n);
      pTo->n += nReq;
      if( rc!=SQLITE_OK ){
        return rc;
      }
    }

    /* Encrypt the data just appended to buffer pTo. */
    if( pCodec ){
      zonefileCodecEncode(pCodec, &pTo->a[nOrig], pTo->n - nOrig);
      pTo->n += nNonce;
    }
  }
  return SQLITE_OK;
}

/*
** Append nByte bytes of garbage data to the file opened with pFd. Return
** SQLITE_OK if successful, or SQLITE_ERROR if an error occurs.
................................................................................
  sqlite3_context *pCtx,       /* Context object */
  int objc,                       /* Number of SQL arguments */
  sqlite3_value **objv            /* Array of SQL arguments */
){
  const char *zFile = 0;          /* File to write to */
  const char *zTbl = 0;           /* Database object to read from */
  const char *zJson = 0;          /* JSON configuration parameters */
  ZonefileParam sParam;           /* Decoded JSON parameters */
  int nKey = 0;                   /* Number of keys in new zonefile */
  int nFrame = 0;                 /* Number of frames in new zonefile */
  sqlite3_stmt *pStmt = 0;        /* SQL used to read data from source table */
  FILE *pFd = 0;
  int rc;
  sqlite3_value *pPrev = 0;
  char *zErr = 0;
  void *pCmp = 0;                 /* Data compressor handle */
  u32 iOff;
  ZonefileCodec *pCodec = 0;

  ZonefileBuffer sFrameIdx = {0, 0, 0};     /* Array of frame offsets */
  ZonefileBuffer sKeyIdx = {0, 0, 0};       /* Array of key locations */
  ZonefileBuffer sData = {0, 0, 0};         /* All completed frames so far */
  ZonefileBuffer sFrame = {0, 0, 0};        /* Current frame (uncompressed) */
  ZonefileBuffer sDict = {0, 0, 0};         /* Compression model (if any) */
  ZonefileBuffer sSample = {0,0,0};         /* Sample data for compressor */
................................................................................

  assert( objc==2 || objc==3 );
  zFile = (const char*)sqlite3_value_text(objv[0]);
  zTbl = (const char*)sqlite3_value_text(objv[1]);
  if( objc==3 ){
    zJson = (const char*)sqlite3_value_text(objv[2]);
  }
  if( zonefileGetParams(pCtx, zJson, &sParam) ) return;

  if( sParam.encryptionType!=0 ){
    int n = strlen(sParam.encryptionKey);
    rc = zonefileCodecCreate(
        sParam.encryptionType, (u8*)sParam.encryptionKey, n, &pCodec, &zErr
    );
    if( rc!=SQLITE_OK ){
      sqlite3_result_error(pCtx, zErr, -1);
      sqlite3_free(zErr);
      goto zone_write_out;
    }
  }

  /* Check that the index-data compressor is not one that uses an external
  ** dictionary. This is not permitted as there is no sense in using a
  ** dictionary to compress a single blob of data, and the index-data
  ** compressor only ever compresses a single frame. Also, there is nowhere
  ** in the file-format to store such a dictionary for the index-data.  */
  if( sParam.pCmpIdx->xTrain ){
    zonefileCtxError(pCtx, 
        "compressor \"%s\" may not be used to compress the zonefile index", 
        sParam.pCmpIdx->zName
    );
    goto zone_write_out;
  }

  if( sParam.pCmpData->xOpen ){
    rc = sParam.pCmpData->xOpen(&pCmp, 0, 0);
    if( rc!=SQLITE_OK ){
      zonefileCtxError(pCtx, "error in compressor construction");
      goto zone_write_out;
    }
  }

  /* Prepare the SQL statement used to read data from the source table. This
................................................................................
    sqlite3_result_error(pCtx, zErr, -1);
    sqlite3_free(zErr);
    goto zone_write_out;
  }

  /* If the data compressor uses a global dictionary, create the dictionary
  ** and store it in buffer sDict.  */
  if( sParam.pCmpData->xTrain ){
    int nSample = 0;

    while( SQLITE_ROW==sqlite3_step(pStmt) ){
      int nByte = sqlite3_column_bytes(pStmt, 2);
      const u8 *aByte = (const u8*)sqlite3_column_blob(pStmt, 2);
      if( zonefileBufferGrow(pCtx, &sSample, nByte) ){
        goto zone_write_out;
................................................................................
    }

    if( zonefileBufferGrow(pCtx, &sDict, ZONEFILE_DEFAULT_DICTSIZE) ){
      goto zone_write_out;
    }
    sDict.n = sDict.nAlloc;

    rc = sParam.pCmpData->xTrain(
        pCmp, sDict.a, &sDict.n, sSample.a, aSample, nSample
    );
    if( rc!=SQLITE_OK ){
      zonefileCtxError(pCtx, "error generating dictionary");
      goto zone_write_out;
    }
  }
................................................................................
    sqlite3_value *pFrame = sqlite3_column_value(pStmt, 1);
    int nBlob = sqlite3_column_bytes(pStmt, 2);
    const u8 *pBlob = (const u8*)sqlite3_column_blob(pStmt, 2);

    int bAuto = zonefileIsAutoFrame(pFrame);
    if( sFrame.n>0 ){
      if( zonefileCompareValue(pFrame, pPrev) 
       || (bAuto && (sFrame.n+nBlob)>sParam.maxAutoFrameSize)
      ){
        /* Add new entry to sFrame */
        if( zonefileBufferGrow(pCtx, &sFrameIdx, 4) 
         || zonefileAppendData(pCtx,sParam.pCmpData,pCmp,pCodec,&sData,&sFrame)
        ){
          goto zone_write_out;
        }
        sFrame.n = 0;
        zonefileAppend32(&sFrameIdx, sData.n);
        sqlite3_value_free(pPrev);
        pPrev = 0;
................................................................................
    if( zonefileBufferGrow(pCtx, &sFrame, nBlob) ) goto zone_write_out;
    zonefileAppendBlob(&sFrame, pBlob, nBlob);
    nKey++;
  }

  if( sFrame.n>0 ){
    if( zonefileBufferGrow(pCtx, &sFrameIdx, 4) 
     || zonefileAppendData(pCtx, sParam.pCmpData, pCmp, pCodec, &sData, &sFrame)
    ){
      goto zone_write_out;
    }
    zonefileAppend32(&sFrameIdx, sData.n);
    nFrame++;
  }

  /* If a compression method was specified, compress the key-index here */
  if( sParam.pCmpIdx->eType!=ZONEFILE_COMPRESSION_NONE ){
    if( zonefileBufferGrow(pCtx, &sFrameIdx, sKeyIdx.n) ) goto zone_write_out;
    zonefileAppendBlob(&sFrameIdx, sKeyIdx.a, sKeyIdx.n);
    zonefileBufferFree(&sKeyIdx);
    rc = zonefileAppendData(pCtx, sParam.pCmpIdx, 0, 0, &sKeyIdx, &sFrameIdx);
    sFrameIdx.n = 0;
    if( rc ) goto zone_write_out;
  }

  /* Create the zonefile header in the in-memory buffer */
  memset(aHdr, 0, ZONEFILE_SZ_HEADER);
  zonefilePut32(&aHdr[0], ZONEFILE_MAGIC_NUMBER);
  aHdr[4] = sParam.pCmpIdx->eType;
  aHdr[5] = sParam.pCmpData->eType;
  iOff = ZONEFILE_SZ_HEADER + sFrameIdx.n + sKeyIdx.n;
  zonefilePut32(&aHdr[6], sDict.n ? iOff+sParam.debugExtendedHeaderSize : 0);
  zonefilePut32(&aHdr[10], iOff + sParam.debugExtendedHeaderSize + sDict.n);
  zonefilePut32(&aHdr[14], nFrame);
  zonefilePut32(&aHdr[18], nKey);
  aHdr[22] = sParam.encryptionType;
  aHdr[23] = 0;                   /* Encryption key index */
  aHdr[24] = 0;                   /* extended header version */
  aHdr[25] = sParam.debugExtendedHeaderSize;
  assert( ZONEFILE_SZ_HEADER>=26 );

  rc = zonefileFileWrite(pFd, aHdr, ZONEFILE_SZ_HEADER);
  if( rc==SQLITE_OK ) rc = zonefilePad(pFd, sParam.debugExtendedHeaderSize);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sFrameIdx.a, sFrameIdx.n);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sKeyIdx.a, sKeyIdx.n);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sDict.a, sDict.n);
  if( rc==SQLITE_OK ) rc = zonefileFileWrite(pFd, sData.a, sData.n);
  if( rc ){
    zonefileCtxError(pCtx, "error writing file \"%s\" (fwrite())", zFile);
    goto zone_write_out;
................................................................................

  if( fclose(pFd) ){
    zonefileCtxError(pCtx, "error writing file \"%s\" (fclose())", zFile);
  }
  pFd = 0;

 zone_write_out:
  if( pCmp ) sParam.pCmpData->xClose(pCmp);
  if( pFd ) fclose(pFd);
  sqlite3_value_free(pPrev);
  sqlite3_finalize(pStmt);
  zonefileCodecDestroy(pCodec);
  zonefileBufferFree(&sFrameIdx);
  zonefileBufferFree(&sKeyIdx);
  zonefileBufferFree(&sFrame);
  zonefileBufferFree(&sDict);
  zonefileBufferFree(&sData);
  zonefileBufferFree(&sSample);
  sqlite3_free(aSample);
  sqlite3_free(sParam.encryptionKey);
}

typedef struct ZonefileFilesTab ZonefileFilesTab;
struct ZonefileFilesTab {
  sqlite3_vtab base;              /* Base class - must be first */
  sqlite3 *db;
  char *zBase;                    /* Name of this table */
  char *zDb;                      /* Database containing this table */
  ZonefileGlobal *pGlobal;        /* Global object */
  sqlite3_stmt *pInsert;          /* Insert into the %_shadow_file table */
  sqlite3_stmt *pInsertIdx;       /* Insert into the %_shadow_idx table */
  sqlite3_stmt *pDeleteIdx;       /* Delete by fileid from %_shadow_idx table */
  sqlite3_stmt *pDelete;          /* Delete by rowid from %_shadow_file table */
};

typedef struct ZonefileFilesCsr ZonefileFilesCsr;
................................................................................

/*
** This function does the work of xCreate (if bCreate!=0) or xConnect
** (if bCreate==0) for the zonefile_files module.
*/
static int zffCreateConnect(
  int bCreate,
  void *pAux,
  sqlite3 *db,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  ZonefileFilesTab *p;
  const char *zName = argv[2];
................................................................................
    memset(p, 0, sizeof(ZonefileFilesTab));
    p->zBase = (char*)&p[1];
    memcpy(p->zBase, zName, nName-6);
    p->zBase[nName-6] = '\0';
    p->zDb = &p->zBase[nName+1];
    memcpy(p->zDb, zDb, nDb+1);
    p->db = db;
    p->pGlobal = (ZonefileGlobal*)pAux;
    rc = sqlite3_declare_vtab(db, ZONEFILE_FILES_SCHEMA);
  }

  if( rc!=SQLITE_OK ){
    sqlite3_free(p);
    p = 0;
  }
................................................................................
static int zffCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zffCreateConnect(1, pAux, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile_files virtual table module xConnect method.
*/
static int zffConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zffCreateConnect(0, pAux, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile_files virtual table module xDisconnect method.
*/
static int zffDisconnect(sqlite3_vtab *pVtab){
  ZonefileFilesTab *pTab = (ZonefileFilesTab*)pVtab;
................................................................................
}

/* 
** zonefile_files virtual table module xColumn method.
*/
static int zffColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  ZonefileFilesCsr *pCsr = (ZonefileFilesCsr*)cur;
  if( sqlite3_vtab_nochange(ctx) ){
    return SQLITE_OK;
  }
  switch( i ){
    case 0: /* filename */
      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pSelect, 0));
      break;
    case 1: /* ekey */
      break;
    case 2: { /* header */
................................................................................
  }

  if( rc==SQLITE_OK && hdr.numKeys>0 ){
    u8 *aKey;                     /* Entire KeyOffsets array */
    int nKey;                     /* Size of buffer aKey[] in bytes */
    int i;


    rc = zonefileLoadIndex(&hdr, pFd, &aKey, &nKey, &pTab->base.zErrMsg);

    if( rc==SQLITE_OK && pTab->pInsertIdx==0 ){
      rc = zonefilePrepare(pTab->db, &pTab->pInsertIdx, &pTab->base.zErrMsg,
          "INSERT INTO %Q.'%q_shadow_idx'(k, fileid, frame, ofst, sz)"
          "VALUES(?,?,?,?,?)",
          pTab->zDb, pTab->zBase
................................................................................
    }
    sqlite3_free(aKey);
  }

  zonefileFileClose(pFd);
  return rc;
}

static int zonefileStoreKey(
  ZonefileFilesTab *pTab, 
  i64 iFileid, 
  const char *zKey
){
  ZonefileKey **pp;

  for(pp=&pTab->pGlobal->pList; *pp; pp=&((*pp)->pNext)){
    ZonefileKey *pThis = *pp;
    if( pThis->iFileid==iFileid 
     && 0==sqlite3_stricmp(pTab->zBase, pThis->zName)
     && 0==sqlite3_stricmp(pTab->zDb, pThis->zDb)
    ){
      *pp = pThis->pNext;
      sqlite3_free(pThis);
      break;
    }
  }

  if( zKey ){
    int nKey = strlen(zKey);
    int nDb = strlen(pTab->zDb);
    int nName = strlen(pTab->zBase);
    ZonefileKey *pNew;
    pNew = (ZonefileKey*)sqlite3_malloc(
        sizeof(ZonefileKey) + nKey+1 + nDb+1 + nName+1
        );
    if( pNew==0 ) return SQLITE_NOMEM;
    memset(pNew, 0, sizeof(ZonefileKey));
    pNew->iFileid = iFileid;
    pNew->zKey = (const char*)&pNew[1];
    pNew->nKey = nKey;
    pNew->zDb = &pNew->zKey[nKey+1];
    pNew->zName = &pNew->zDb[nDb+1];
    memcpy((char*)pNew->zKey, zKey, nKey+1);
    memcpy((char*)pNew->zDb, pTab->zDb, nDb+1);
    memcpy((char*)pNew->zName, pTab->zBase, nName+1);

    pNew->pNext = pTab->pGlobal->pList;
    pTab->pGlobal->pList = pNew;
  }
  return SQLITE_OK;
}

/*
** zonefile_files virtual table module xUpdate method.
**
** A delete specifies a single argument - the rowid of the row to remove.
** 
** Update and insert operations pass:
................................................................................
  sqlite3_value **apVal, 
  sqlite_int64 *pRowid
){
  int rc = SQLITE_OK;
  ZonefileFilesTab *pTab = (ZonefileFilesTab*)pVtab;

  if( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ){
    if( nVal>1 && sqlite3_value_nochange(apVal[2]) ){
      const char *zKey = (const char*)sqlite3_value_text(apVal[3]);
      i64 iFileid = sqlite3_value_int64(apVal[0]);
      return zonefileStoreKey(pTab, iFileid, zKey);
    }else{
      if( pTab->pDelete==0 ){
        rc = zonefilePrepare(pTab->db, &pTab->pDelete, &pVtab->zErrMsg,
            "DELETE FROM %Q.'%q_shadow_file' WHERE fileid=?",
            pTab->zDb, pTab->zBase
            );
      }
      if( rc==SQLITE_OK && pTab->pDeleteIdx==0 ){
        rc = zonefilePrepare(pTab->db, &pTab->pDeleteIdx, &pVtab->zErrMsg,
            "DELETE FROM %Q.'%q_shadow_idx' WHERE fileid=?",
            pTab->zDb, pTab->zBase
            );
      }

      if( rc==SQLITE_OK ){
        sqlite3_bind_value(pTab->pDelete, 1, apVal[0]);
        sqlite3_step(pTab->pDelete);
        rc = sqlite3_reset(pTab->pDelete);
      }
      if( rc==SQLITE_OK ){
        sqlite3_bind_value(pTab->pDeleteIdx, 1, apVal[0]);
        sqlite3_step(pTab->pDeleteIdx);
        rc = sqlite3_reset(pTab->pDeleteIdx);
      }
    }
  }
  if( nVal>1 ){
    i64 iFileid = 0;
    const char *zFile = (const char*)sqlite3_value_text(apVal[2]);

    if( pTab->pInsert==0 ){
      rc = zonefilePrepare(pTab->db, &pTab->pInsert, &pVtab->zErrMsg,
          "INSERT INTO %Q.'%q_shadow_file'(filename) VALUES(?)",
          pTab->zDb, pTab->zBase
      );
................................................................................
      sqlite3_step(pTab->pInsert);
      rc = sqlite3_reset(pTab->pInsert);
    }

    /* Populate the %_shadow_idx table with entries for all keys in
    ** the zonefile just added to %_shadow_file.  */
    if( rc==SQLITE_OK ){
      iFileid = sqlite3_last_insert_rowid(pTab->db);
      rc = zonefilePopulateIndex(pTab, zFile, iFileid);
    }

    if( rc==SQLITE_OK ){
      const char *zKey = (const char*)sqlite3_value_text(apVal[3]);
      rc = zonefileStoreKey(pTab, iFileid, zKey);
    }
  }

  return rc;
}

typedef struct ZonefileTab ZonefileTab;
struct ZonefileTab {
  sqlite3_vtab base;         /* Base class - must be first */
  sqlite3 *db;
  sqlite3_stmt *pIdToName;   /* Translate fileid to filename */
  ZonefileGlobal *pGlobal;
  char *zName;               /* Name of this table */
  char *zDb;                 /* Name of db containing this table */
};

typedef struct ZonefileCsr ZonefileCsr;
struct ZonefileCsr {
  sqlite3_vtab_cursor base;  /* Base class - must be first */
................................................................................
**
**   argv[0]   -> module name  ("zonefile")
**   argv[1]   -> database name
**   argv[2]   -> table name
*/
static int zonefileCreateConnect(
  int bCreate,
  void *pAux,
  sqlite3 *db,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  ZonefileTab *p;
  const char *zName = argv[2];
................................................................................
  }else{
    memset(p, 0, sizeof(ZonefileTab));
    p->zName = (char*)&p[1];
    memcpy(p->zName, zName, nName+1);
    p->zDb = &p->zName[nName+1];
    memcpy(p->zDb, zDb, nDb+1);
    p->db = db;
    p->pGlobal = (ZonefileGlobal*)pAux;
  
    if( bCreate ){
      char *zSql = sqlite3_mprintf(
          "CREATE TABLE %Q.'%q_shadow_idx'(" 
          "  k INTEGER PRIMARY KEY,"
          "  fileid INTEGER,"
          "  frame INTEGER,"
................................................................................
static int zonefileCreate(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zonefileCreateConnect(1, pAux, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile virtual table module xConnect method.
*/
static int zonefileConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  return zonefileCreateConnect(0, pAux, db, argc, argv, ppVtab, pzErr);
}

/* 
** zonefile virtual table module xDisconnect method.
*/
static int zonefileDisconnect(sqlite3_vtab *pVtab){
  ZonefileTab *pTab = (ZonefileTab*)pVtab;
................................................................................
  }else if( rc==SQLITE_ERROR ){
    zonefileCtxError(pCtx, "failed to uncompress frame");
  }

  sqlite3_free(aUn);
  return rc;
}

static int zonefileFindKey(ZonefileTab *pTab, i64 iFileid, const char **pzKey){
  ZonefileKey *pKey;

  for(pKey=pTab->pGlobal->pList; pKey; pKey=pKey->pNext){
    if( pKey->iFileid==iFileid 
     && 0==sqlite3_stricmp(pTab->zName, pKey->zName)
     && 0==sqlite3_stricmp(pTab->zDb, pKey->zDb)
    ){
      *pzKey = pKey->zKey;
      return pKey->nKey;
    }
  }

  return 0;
}

static int zonefileGetValue(sqlite3_context *pCtx, ZonefileCsr *pCsr){
  ZonefileTab *pTab = (ZonefileTab*)pCsr->base.pVtab;
  const char *zFile = 0;
  char *zErr = 0;
  FILE *pFd = 0;
  int rc = SQLITE_OK;
  u32 iOff = 0;                   /* Offset of frame in file */
  u32 szFrame = 0;                /* Size of frame in bytes */
  int iKeyOff = 0;                /* Offset of record within frame */
  int szKey = 0;                  /* Uncompressed size of record in bytes */
  i64 iFileid = 0;
  ZonefileHeader hdr;
  ZonefileCompress *pCmpMethod = 0;
  ZonefileCodec *pCodec = 0;
  void *pCmp = 0;

  if( pTab->pIdToName==0 ){
    rc = zonefilePrepare(pTab->db, &pTab->pIdToName, &pTab->base.zErrMsg, 
        "SELECT filename FROM %Q.'%q_shadow_file' WHERE fileid=?",
        pTab->zDb, pTab->zName
    );
................................................................................
    }
  }

  iKeyOff = sqlite3_column_int(pCsr->pSelect, 3);
  szKey = sqlite3_column_int(pCsr->pSelect, 4);

  /* Open the file to read the blob from */
  iFileid = sqlite3_column_int64(pCsr->pSelect,1);
  sqlite3_bind_int64(pTab->pIdToName, 1, iFileid);
  if( SQLITE_ROW==sqlite3_step(pTab->pIdToName) ){
    zFile = (const char*)sqlite3_column_text(pTab->pIdToName, 0);
    pFd = zonefileFileOpen(zFile, 0, &zErr);
  }
  if( zFile==0 ){
    rc = sqlite3_reset(pTab->pIdToName);
    if( rc!=SQLITE_OK ){
................................................................................
      }
    }
    if( rc==SQLITE_OK ){
      rc = pCmpMethod->xOpen(&pCmp, aDict, nDict);
    }
    sqlite3_free(aDict);
  }

  if( hdr.encryptionType ){
    const char *zKey = 0;
    int nKey = zonefileFindKey(pTab, iFileid, &zKey);
    if( nKey==0 ){
      zErr = sqlite3_mprintf("missing encryption key for file \"%s\"", zFile);
      rc = SQLITE_ERROR;
    }else{
      rc = zonefileCodecCreate(hdr.encryptionType,(u8*)zKey,nKey,&pCodec,&zErr);
    }
  }

  /* Find the offset (iOff) and size (szFrame) of the frame that the
  ** record is stored in.  */
  if( rc==SQLITE_OK ){
    int iFrame = sqlite3_column_int(pCsr->pSelect, 2);
    u8 aSpace[8] = {0,0,0,0,0,0,0,0};
    u8 *aOff = aSpace;
................................................................................
    sqlite3_free(aFree);
  }

  /* Read some data into memory. If the data is uncompressed, then just
  ** the required record is read. Otherwise, the entire frame is read
  ** into memory.  */
  if( rc==SQLITE_OK ){
    int nRead;                       /* Bytes of data to read */
    i64 iRead;                       /* Offset to read at */

    if( pCmpMethod || pCodec ){
      nRead = szFrame;
      iRead = iOff;
    }else{
      nRead = szKey;
      iRead = iOff + iKeyOff;
    }
    
    u8 *aBuf = sqlite3_malloc(nRead);
    if( aBuf==0 ){
      rc = SQLITE_NOMEM;
    }else{
      rc = zonefileFileRead(pFd, aBuf, nRead, hdr.byteOffsetFrames + iRead);
      if( rc==SQLITE_OK ){
        if( pCodec ){
          zonefileCodecDecode(pCodec, aBuf, nRead);
        }
        if( pCmpMethod==0 ){
          if( pCodec==0 ){
            sqlite3_result_blob(pCtx, aBuf, szKey, zonefileFree);
            aBuf = 0;
          }else{
            sqlite3_result_blob(pCtx, &aBuf[iKeyOff], szKey, SQLITE_TRANSIENT);
          }
        }else{
          rc = zonefileCtxUncompress(
              pCtx, pCmpMethod, pCmp, aBuf, szFrame, iKeyOff, szKey
          );
        }
      }else{
        zErr = sqlite3_mprintf(
            "failed to read %d bytes at offset %d from file \"%s\"", 
            nRead, (int)(hdr.byteOffsetFrames+iRead), zFile
        );
      }
      sqlite3_free(aBuf);
    }
  }

  sqlite3_reset(pTab->pIdToName);
  if( zErr ){
    assert( rc!=SQLITE_OK );
    sqlite3_result_error(pCtx, zErr, -1);
    sqlite3_free(zErr);
  }
  zonefileFileClose(pFd);
  zonefileCodecDestroy(pCodec);
  if( pCmpMethod ) pCmpMethod->xClose(pCmp);
  return rc;
}

/* 
** zonefile virtual table module xColumn method.
*/
................................................................................
** zonefile virtual table module xRowid method.
*/
static int zonefileRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  ZonefileCsr *pCsr = (ZonefileCsr*)cur;
  *pRowid = sqlite3_column_int64(pCsr->pSelect, 0);
  return SQLITE_OK;
}

static void zonefileGlobalFree(void *p){
  ZonefileGlobal *pGlobal = (ZonefileGlobal*)p;
  ZonefileKey *pKey;
  ZonefileKey *pNext;
  for(pKey=pGlobal->pList; pKey; pKey=pNext){
    pNext = pKey->pNext;
    sqlite3_free(pKey);
  }
  sqlite3_free(pGlobal);
}

/*
** Register the "zonefile" extensions.
*/
static int zonefileRegister(sqlite3 *db){
  static sqlite3_module filesModule = {
    0,                            /* iVersion */
................................................................................
    const char *z;
    int n;
    void (*x)(sqlite3_context*,int,sqlite3_value**);
  } aFunc[] = {
    { "zonefile_write", 2, zonefileWriteFunc },
    { "zonefile_write", 3, zonefileWriteFunc },
  };
  ZonefileGlobal *pGlobal = 0;

  int rc = SQLITE_OK;
  int i;

  for(i=0; rc==SQLITE_OK && i<sizeof(aFunc)/sizeof(aFunc[0]); i++){
    struct Func *p = &aFunc[i];
    rc = sqlite3_create_function(db, p->z, p->n, SQLITE_ANY, 0, p->x, 0, 0);
  }

  if( rc==SQLITE_OK ){
    pGlobal = (ZonefileGlobal*)sqlite3_malloc(sizeof(ZonefileGlobal));
    if( pGlobal==0 ){
      rc = SQLITE_NOMEM;
    }else{
      memset(pGlobal, 0, sizeof(ZonefileGlobal));
    }
  }

  if( rc==SQLITE_OK ){
    rc = sqlite3_create_module(
        db, "zonefile_files", &filesModule, (void*)pGlobal
    );
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_module_v2(db, "zonefile", &zonefileModule, 
        (void*)pGlobal, zonefileGlobalFree
    );
    pGlobal = 0;
  }

  sqlite3_free(pGlobal);
  return rc;
}

#else         /* SQLITE_OMIT_VIRTUALTABLE */
# define zonefileRegister(x) SQLITE_OK
#endif

Changes to ext/zonefile/zonefile1.test.

196
197
198
199
200
201
202
203

204


































205
206
    ORDER BY 1
  } {
    test19.zonefile 1 1
    test20.zonefile 2 2
    test21.zonefile 7 4
  }
}}





































finish_test









>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    ORDER BY 1
  } {
    test19.zonefile 1 1
    test20.zonefile 2 2
    test21.zonefile 7 4
  }
}}

#--------------------------------------------------------------------------
#
reset_db
load_static_extension db zonefile
do_execsql_test 3.0 {
  CREATE TABLE dd(k INTEGER PRIMARY KEY, frame INTEGER, idx INTEGER, v BLOB);
  INSERT INTO dd VALUES(1000, 1, -1, randomblob(44));
  INSERT INTO dd VALUES(1001, 1, -1, randomblob(55));
  INSERT INTO dd VALUES(1002, 2, -1, randomblob(66));
  WITH p(n,v) AS (
      VALUES('maxAutoFrameSize', 2000) UNION ALL
      VALUES('encryptionType', 'xor') UNION ALL
      VALUES('encryptionKey', '0123456789')
  )
  SELECT zonefile_write('test.zonefile', 'dd', json_group_object(n, v)) FROM p;
} {{}}

do_execsql_test 3.1 {
  CREATE VIRTUAL TABLE cc USING zonefile;
  INSERT INTO cc_files(filename,ekey) VALUES('test.zonefile','0123456789');
  SELECT quote(dd.v)==quote(cc.v) FROM cc JOIN dd USING (k)
} {1 1 1}

do_execsql_test 3.2 {
  DELETE FROM cc_files;
  INSERT INTO cc_files(filename,ekey) VALUES('test.zonefile','abcdefghij');
  SELECT quote(dd.v)==quote(cc.v) FROM cc JOIN dd USING (k)
} {0 0 0}

do_execsql_test 3.3 {
  UPDATE cc_files SET ekey = '0123456789';
  SELECT quote(dd.v)==quote(cc.v) FROM cc JOIN dd USING (k)
} {1 1 1}



finish_test