Fossil SCM

Merge all the latest trunk enhancements into the http1-1-chunked branch so that the branch can be more easily tested.

drh 2026-06-22 11:03 UTC http1-1-chunked merge
Commit 4a648d7410ad9d6f4baf10e6c14ea0d6e86708552d014fb386bb1c7bb411fa81
+112 -40
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -5424,11 +5424,11 @@
54245424
}
54255425
j = 0;
54265426
}else{
54275427
i = 0;
54285428
}
5429
- (void)memcpy(&p->buffer[j], &data[i], len - i);
5429
+ if( len-i>0 ) (void)memcpy(&p->buffer[j], &data[i], len - i);
54305430
}
54315431
54325432
/* Compute a string using sqlite3_vsnprintf() and hash it */
54335433
static void hash_step_vformat(
54345434
SHA1Context *p, /* Add content to this context */
@@ -6071,32 +6071,41 @@
60716071
}
60726072
z[i] = 0;
60736073
sqlite3_result_text(pCtx, z, i, sqlite3_free);
60746074
}
60756075
6076
+/* Forward declaration */
6077
+static void decimal_expand(Decimal *p, int nDigit, int nFrac);
6078
+
60766079
/*
60776080
** Round a decimal value to N significant digits. N must be positive.
60786081
*/
60796082
static void decimal_round(Decimal *p, int N){
60806083
int i;
6081
- int nZero;
6084
+ int nZero; /* Number of leading zeros */
60826085
if( N<1 ) return;
60836086
if( p==0 ) return;
60846087
if( p->nDigit<=N ) return;
60856088
for(nZero=0; nZero<p->nDigit && p->a[nZero]==0; nZero++){}
60866089
N += nZero;
60876090
if( p->nDigit<=N ) return;
6088
- if( p->a[N]>4 ){
6091
+ if( p->a[N]>=5 ){
6092
+ /* If all leading digits are 9, increase the number of digits
6093
+ ** by adding a new 0 to the front */
6094
+ for(i=0; i<N && p->a[i]==9; i++){}
6095
+ if( i==N ){
6096
+ decimal_expand(p, p->nDigit+1, 0);
6097
+ if( p->oom ) return;
6098
+ }
6099
+
6100
+ /* Do the rounding */
60896101
p->a[N-1]++;
60906102
for(i=N-1; i>0 && p->a[i]>9; i--){
60916103
p->a[i] = 0;
60926104
p->a[i-1]++;
60936105
}
6094
- if( p->a[0]>9 ){
6095
- p->a[0] = 1;
6096
- p->nFrac--;
6097
- }
6106
+ assert( p->a[0]<=9 );
60986107
}
60996108
memset(&p->a[N], 0, p->nDigit - N);
61006109
}
61016110
61026111
/*
@@ -8378,19 +8387,26 @@
83788387
}
83798388
}else{
83808389
iMin = iMax = sqlite3_value_int64(argv[iArg++]);
83818390
}
83828391
}else{
8383
- if( idxNum & 0x0300 ){ /* value>X or value>=X */
8392
+ if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
83848393
if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
83858394
double r = sqlite3_value_double(argv[iArg++]);
8386
- if( r<(double)SMALLEST_INT64 ){
8395
+ if( r<=(double)SMALLEST_INT64 ){
83878396
iMin = SMALLEST_INT64;
8388
- }else if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8389
- iMin = (sqlite3_int64)seriesCeil(r)+1;
8397
+ }else if( r>(double)LARGEST_INT64 ){
8398
+ goto series_no_rows;
83908399
}else{
83918400
iMin = (sqlite3_int64)seriesCeil(r);
8401
+ if( iMin<0 && r>0.0 ){
8402
+ iMin = LARGEST_INT64;
8403
+ }
8404
+ if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8405
+ if( iMin==LARGEST_INT64 ) goto series_no_rows;
8406
+ iMin++;
8407
+ }
83928408
}
83938409
}else{
83948410
iMin = sqlite3_value_int64(argv[iArg++]);
83958411
if( (idxNum & 0x0200)!=0 ){
83968412
if( iMin==LARGEST_INT64 ){
@@ -8399,19 +8415,25 @@
83998415
iMin++;
84008416
}
84018417
}
84028418
}
84038419
}
8404
- if( idxNum & 0x3000 ){ /* value<X or value<=X */
8420
+ if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
84058421
if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
84068422
double r = sqlite3_value_double(argv[iArg++]);
8407
- if( r>(double)LARGEST_INT64 ){
8423
+ if( r>=(double)LARGEST_INT64 ){
84088424
iMax = LARGEST_INT64;
8409
- }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8410
- iMax = ((sqlite3_int64)r)-1;
8425
+ }else if( r<=(double)SMALLEST_INT64 ){
8426
+ goto series_no_rows;
84118427
}else{
84128428
iMax = (sqlite3_int64)seriesFloor(r);
8429
+ if( iMax<0 && r>0.0 ){
8430
+ iMax = LARGEST_INT64;
8431
+ }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8432
+ if( iMax==SMALLEST_INT64 ) goto series_no_rows;
8433
+ iMax--;
8434
+ }
84138435
}
84148436
}else{
84158437
iMax = sqlite3_value_int64(argv[iArg++]);
84168438
if( idxNum & 0x2000 ){
84178439
if( iMax==SMALLEST_INT64 ){
@@ -10884,10 +10906,13 @@
1088410906
** Return NULL if unable.
1088510907
**
1088610908
** The file or directory X is not required to exist. The answer is formed
1088710909
** by calling system realpath() on the prefix of X that does exist and
1088810910
** appending the tail of X that does not (yet) exist.
10911
+**
10912
+** FIXME: This routine sometimes returns NULL rather than raising
10913
+** an SQLITE_NOMEM error if an OOM is encountered.
1088910914
*/
1089010915
static void realpathFunc(
1089110916
sqlite3_context *context,
1089210917
int argc,
1089310918
sqlite3_value **argv
@@ -10906,10 +10931,11 @@
1090610931
(void)argc;
1090710932
zPath = (const char*)sqlite3_value_text(argv[0]);
1090810933
if( zPath==0 ) return;
1090910934
if( zPath[0]==0 ) zPath = ".";
1091010935
zCopy = sqlite3_mprintf("%s",zPath);
10936
+ if( zCopy==0 ) return;
1091110937
len = strlen(zCopy);
1091210938
while( len>1 && (zCopy[len-1]=='/' || (isWin && zCopy[len-1]=='\\')) ){
1091310939
len--;
1091410940
}
1091510941
zCopy[len] = 0;
@@ -12699,10 +12725,11 @@
1269912725
1270012726
for(p=pCsr->pFreeEntry; p; p=pNext){
1270112727
pNext = p->pNext;
1270212728
zipfileEntryFree(p);
1270312729
}
12730
+ pCsr->pFreeEntry = 0;
1270412731
}
1270512732
1270612733
/*
1270712734
** Destructor for an ZipfileCsr.
1270812735
*/
@@ -13101,11 +13128,17 @@
1310113128
}
1310213129
}
1310313130
1310413131
if( rc==SQLITE_OK ){
1310513132
u32 *pt = &pNew->mUnixTime;
13106
- pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
13133
+ /* aRead[0..nFile-1] might contain embedded \000 characters
13134
+ ** See Bug 2026-05-31T11:43:05Z */
13135
+ pNew->cds.zFile = sqlite3_malloc64(nFile+1);
13136
+ if( pNew->cds.zFile!=0 ){
13137
+ memcpy(pNew->cds.zFile, aRead, nFile);
13138
+ pNew->cds.zFile[nFile] = 0;
13139
+ }
1310713140
pNew->aExtra = (u8*)&pNew[1];
1310813141
memcpy(pNew->aExtra, &aRead[nFile], nExtra);
1310913142
if( pNew->cds.zFile==0 ){
1311013143
rc = SQLITE_NOMEM;
1311113144
}else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
@@ -14205,14 +14238,14 @@
1420514238
ZipfileBuffer body;
1420614239
ZipfileBuffer cds;
1420714240
};
1420814241
1420914242
static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){
14210
- if( pBuf->n+nByte>pBuf->nAlloc ){
14243
+ if( (pBuf->nAlloc-pBuf->n)<nByte ){
1421114244
u8 *aNew;
14212
- sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
14213
- int nReq = pBuf->n + nByte;
14245
+ i64 nNew = pBuf->n ? (i64)pBuf->n*2 : 512;
14246
+ i64 nReq = pBuf->n + nByte;
1421414247
1421514248
while( nNew<nReq ) nNew = nNew*2;
1421614249
aNew = sqlite3_realloc64(pBuf->a, nNew);
1421714250
if( aNew==0 ) return SQLITE_NOMEM;
1421814251
pBuf->a = aNew;
@@ -16310,11 +16343,11 @@
1631016343
p->pTable = pTab;
1631116344
1631216345
/* The statement the vtab will pass to sqlite3_declare_vtab() */
1631316346
zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
1631416347
for(i=0; i<pTab->nCol; i++){
16315
- zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
16348
+ zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %Q",
1631616349
(i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
1631716350
);
1631816351
}
1631916352
zInner = idxAppendText(&rc, zInner, ")");
1632016353
@@ -16510,11 +16543,11 @@
1651016543
sqlite3_free(zCols);
1651116544
sqlite3_free(zOrder);
1651216545
return sqlite3_reset(pIndexXInfo);
1651316546
}
1651416547
zCols = idxAppendText(&rc, zCols,
16515
- "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s",
16548
+ "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %Q",
1651616549
zComma, zName, nCol, zName, zColl
1651716550
);
1651816551
zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
1651916552
}
1652016553
sqlite3_reset(pIndexXInfo);
@@ -25163,11 +25196,11 @@
2516325196
/*
2516425197
** Return true if either the SQLITE_NO_COLOR compile-time option is used
2516525198
** or if the NO_COLOR environment variable exists
2516625199
*/
2516725200
static int shellNoColor(void){
25168
-#ifdef SQLITE_NO_COLOR
25201
+#if defined(SQLITE_NO_COLOR) || defined(SQLITE_SHELL_FIDDLE)
2516925202
return 1;
2517025203
#else
2517125204
return getenv("NO_COLOR")!=0;
2517225205
#endif
2517325206
}
@@ -31316,11 +31349,11 @@
3131631349
typedef struct ArCommand ArCommand;
3131731350
struct ArCommand {
3131831351
u8 eCmd; /* An AR_CMD_* value */
3131931352
u8 bVerbose; /* True if --verbose */
3132031353
u8 bZip; /* True if the archive is a ZIP */
31321
- u8 bDryRun; /* True if --dry-run */
31354
+ u8 bDryRun; /* 1 for --dry-run, 2 for --debug */
3132231355
u8 bAppend; /* True if --append */
3132331356
u8 bGlob; /* True if --glob */
3132431357
u8 fromCmdLine; /* Run from -A instead of .archive */
3132531358
int nArg; /* Number of command arguments */
3132631359
char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
@@ -31378,10 +31411,11 @@
3137831411
#define AR_SWITCH_FILE 9
3137931412
#define AR_SWITCH_DIRECTORY 10
3138031413
#define AR_SWITCH_APPEND 11
3138131414
#define AR_SWITCH_DRYRUN 12
3138231415
#define AR_SWITCH_GLOB 13
31416
+#define AR_SWITCH_DEBUG 14
3138331417
3138431418
static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
3138531419
switch( eSwitch ){
3138631420
case AR_CMD_CREATE:
3138731421
case AR_CMD_EXTRACT:
@@ -31395,11 +31429,14 @@
3139531429
}
3139631430
pAr->eCmd = eSwitch;
3139731431
break;
3139831432
3139931433
case AR_SWITCH_DRYRUN:
31400
- pAr->bDryRun = 1;
31434
+ if( pAr->bDryRun<2 ) pAr->bDryRun = 1;
31435
+ break;
31436
+ case AR_SWITCH_DEBUG:
31437
+ pAr->bDryRun = 2;
3140131438
break;
3140231439
case AR_SWITCH_GLOB:
3140331440
pAr->bGlob = 1;
3140431441
break;
3140531442
case AR_SWITCH_VERBOSE:
@@ -31446,10 +31483,11 @@
3144631483
{ "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
3144731484
{ "file", 'f', AR_SWITCH_FILE, 1 },
3144831485
{ "append", 'a', AR_SWITCH_APPEND, 1 },
3144931486
{ "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
3145031487
{ "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
31488
+ { "debug", 0, AR_SWITCH_DEBUG, 0 },
3145131489
{ "glob", 'g', AR_SWITCH_GLOB, 0 },
3145231490
};
3145331491
int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
3145431492
struct ArSwitch *pEnd = &aSwitch[nSwitch];
3145531493
@@ -31746,18 +31784,41 @@
3174631784
3174731785
/*
3174831786
** Implementation of .ar "eXtract" command.
3174931787
*/
3175031788
static int arExtractCommand(ArCommand *pAr){
31789
+ /* The zSql1[] string is a template for the query that does the
31790
+ ** extraction. Notes:
31791
+ **
31792
+ ** * $dir is the directory into which the archive is to be extracted
31793
+ ** * $pass is the integer pass number: 0, 1, or 2
31794
+ ** * The dest CTE is created so that realpath($dir) only needs
31795
+ ** to be called once.
31796
+ */
3175131797
const char *zSql1 =
31752
- "WITH dest(dpath,dlen) AS (SELECT realpath($dir),length(realpath($dir)))\n"
31753
- "SELECT ($dir || name),\n"
31754
- " CASE WHEN $dryrun THEN 0\n"
31755
- " ELSE writefile($dir||name, %s, mode, mtime) END\n"
31798
+ "WITH dest(dpath,dlen) AS (\n"
31799
+#ifdef _WIN32
31800
+ " SELECT realpath($dir) || '\\',\n"
31801
+#else
31802
+ " SELECT realpath($dir) || '/',\n"
31803
+#endif
31804
+ " 1+length(realpath($dir))\n"
31805
+ ")\n"
31806
+ "SELECT\n"
31807
+ " ($dir || name),\n"
31808
+ " CASE $dryrun\n" /* vv--- azExtraArg */
31809
+ " WHEN 0 THEN writefile($dir||name, %s, mode, mtime)\n"
31810
+ " WHEN 1 THEN 0\n"
31811
+ " ELSE shell_putsnl(format('writefile(%%Q,%%s,%%0o,%%d)',"
31812
+ "$dir||name,quote(%s),mode,mtime)) IS NULL\n"
31813
+ " END\n" /* ^^--- azExtraArg */
3175631814
" FROM dest CROSS JOIN %s\n"
31757
- " WHERE (%s)\n"
31758
- " AND (data IS NULL OR $pass==0)\n" /* Dirs both passes */
31815
+ " WHERE (%s)\n" /* ^^-- pAr->zSrcTable */
31816
+ /* ^^--- zWhere */
31817
+ " AND (CASE $pass WHEN 0 THEN (mode&0xf000)<>0xa000\n"
31818
+ " WHEN 1 THEN (mode&0xf000)=0xa000\n"
31819
+ " ELSE data IS NULL END)\n"
3175931820
" AND dpath=substr(realpath($dir||name),1,dlen)\n" /* No escapes */
3176031821
" AND name NOT GLOB '*..[/\\]*'\n"; /* No /../ in paths */
3176131822
3176231823
const char *azExtraArg[] = {
3176331824
"sqlar_uncompress(data, sz)",
@@ -31784,39 +31845,48 @@
3178431845
}
3178531846
if( zDir==0 ) rc = SQLITE_NOMEM;
3178631847
}
3178731848
3178831849
shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
31789
- azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
31850
+ azExtraArg[pAr->bZip],
31851
+ azExtraArg[pAr->bZip],
31852
+ pAr->zSrcTable,
31853
+ zWhere
3179031854
);
3179131855
3179231856
if( rc==SQLITE_OK ){
3179331857
j = sqlite3_bind_parameter_index(pSql, "$dir");
3179431858
sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
3179531859
j = sqlite3_bind_parameter_index(pSql, "$dryrun");
3179631860
sqlite3_bind_int(pSql, j, pAr->bDryRun);
3179731861
3179831862
/* Run the SELECT statement twice
31799
- ** (0) writefile() all files and directories
31800
- ** (1) writefile() for directory again
31801
- ** The second pass is so that the timestamps for extracted directories
31863
+ ** (0) writefile() files and directories
31864
+ ** (1) writefile() symlinks
31865
+ ** (2) writefile() for directory again
31866
+ ** The third pass is so that the timestamps for extracted directories
3180231867
** will be reset to the value in the archive, since populating them
3180331868
** in the first pass will have changed the timestamp. */
31804
- for(i=0; i<2; i++){
31869
+ for(i=0; i<3; i++){
31870
+ if( pAr->bDryRun>=2 ){
31871
+ cli_printf(pAr->out, "*** BEGIN PASS %d ***\n", i+1);
31872
+ }
3180531873
j = sqlite3_bind_parameter_index(pSql, "$pass");
3180631874
sqlite3_bind_int(pSql, j, i);
31807
- if( pAr->bDryRun ){
31875
+ if( pAr->bDryRun && i==0 ){
3180831876
cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql));
31809
- if( pAr->bVerbose==0 ) break;
3181031877
}
3181131878
while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
3181231879
if( i==0 && pAr->bVerbose ){
3181331880
cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
3181431881
}
3181531882
}
31816
- if( pAr->bDryRun ) break;
31883
+ if( pAr->bDryRun==1 ) break;
3181731884
shellReset(&rc, pSql);
31885
+ if( pAr->bDryRun>=2 ){
31886
+ cli_printf(pAr->out, "*** END PASS %d ***\n", i+1);
31887
+ }
3181831888
}
3181931889
shellFinalize(&rc, pSql);
3182031890
}
3182131891
3182231892
sqlite3_free(zDir);
@@ -32327,11 +32397,11 @@
3232732397
;
3232832398
static const char * const zCollectVar = "\
3232932399
SELECT\
3233032400
'('||x'0a'\
3233132401
|| group_concat(\
32332
- cname||' ANY',\
32402
+ cname,\
3233332403
','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
3233432404
||')' AS ColsSpec \
3233532405
FROM (\
3233632406
SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
3233732407
FROM ColNames ORDER BY cpos\
@@ -37939,11 +38009,11 @@
3793938009
}
3794038010
3794138011
/*
3794238012
** The callback from atexit().
3794338013
*/
37944
-static void abnormalExit(void){
38014
+static void SQLITE_CDECL abnormalExit(void){
3794538015
if( seenInterrupt ) eputz("Program interrupted.\n");
3794638016
if( globalShellState ){
3794738017
clearTempFile(globalShellState, 1, 1);
3794838018
}
3794938019
}
@@ -38498,12 +38568,14 @@
3849838568
}else if( cli_strcmp(z,"-nullvalue")==0 ){
3849938569
modeSetStr(&data.mode.spec.zNull,
3850038570
cmdline_option_value(argc,argv,++i));
3850138571
}else if( cli_strcmp(z,"-header")==0 ){
3850238572
data.mode.spec.bTitles = QRF_Yes;
38573
+ data.mode.mFlags |= MFLG_HDR;
3850338574
}else if( cli_strcmp(z,"-noheader")==0 ){
3850438575
data.mode.spec.bTitles = QRF_No;
38576
+ data.mode.mFlags |= MFLG_HDR;
3850538577
}else if( cli_strcmp(z,"-echo")==0 ){
3850638578
data.mode.mFlags |= MFLG_ECHO;
3850738579
}else if( cli_strcmp(z,"-eqp")==0 ){
3850838580
data.mode.autoEQP = AUTOEQP_on;
3850938581
}else if( cli_strcmp(z,"-eqpfull")==0 ){
3851038582
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -5424,11 +5424,11 @@
5424 }
5425 j = 0;
5426 }else{
5427 i = 0;
5428 }
5429 (void)memcpy(&p->buffer[j], &data[i], len - i);
5430 }
5431
5432 /* Compute a string using sqlite3_vsnprintf() and hash it */
5433 static void hash_step_vformat(
5434 SHA1Context *p, /* Add content to this context */
@@ -6071,32 +6071,41 @@
6071 }
6072 z[i] = 0;
6073 sqlite3_result_text(pCtx, z, i, sqlite3_free);
6074 }
6075
 
 
 
6076 /*
6077 ** Round a decimal value to N significant digits. N must be positive.
6078 */
6079 static void decimal_round(Decimal *p, int N){
6080 int i;
6081 int nZero;
6082 if( N<1 ) return;
6083 if( p==0 ) return;
6084 if( p->nDigit<=N ) return;
6085 for(nZero=0; nZero<p->nDigit && p->a[nZero]==0; nZero++){}
6086 N += nZero;
6087 if( p->nDigit<=N ) return;
6088 if( p->a[N]>4 ){
 
 
 
 
 
 
 
 
 
6089 p->a[N-1]++;
6090 for(i=N-1; i>0 && p->a[i]>9; i--){
6091 p->a[i] = 0;
6092 p->a[i-1]++;
6093 }
6094 if( p->a[0]>9 ){
6095 p->a[0] = 1;
6096 p->nFrac--;
6097 }
6098 }
6099 memset(&p->a[N], 0, p->nDigit - N);
6100 }
6101
6102 /*
@@ -8378,19 +8387,26 @@
8378 }
8379 }else{
8380 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
8381 }
8382 }else{
8383 if( idxNum & 0x0300 ){ /* value>X or value>=X */
8384 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8385 double r = sqlite3_value_double(argv[iArg++]);
8386 if( r<(double)SMALLEST_INT64 ){
8387 iMin = SMALLEST_INT64;
8388 }else if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8389 iMin = (sqlite3_int64)seriesCeil(r)+1;
8390 }else{
8391 iMin = (sqlite3_int64)seriesCeil(r);
 
 
 
 
 
 
 
8392 }
8393 }else{
8394 iMin = sqlite3_value_int64(argv[iArg++]);
8395 if( (idxNum & 0x0200)!=0 ){
8396 if( iMin==LARGEST_INT64 ){
@@ -8399,19 +8415,25 @@
8399 iMin++;
8400 }
8401 }
8402 }
8403 }
8404 if( idxNum & 0x3000 ){ /* value<X or value<=X */
8405 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8406 double r = sqlite3_value_double(argv[iArg++]);
8407 if( r>(double)LARGEST_INT64 ){
8408 iMax = LARGEST_INT64;
8409 }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8410 iMax = ((sqlite3_int64)r)-1;
8411 }else{
8412 iMax = (sqlite3_int64)seriesFloor(r);
 
 
 
 
 
 
8413 }
8414 }else{
8415 iMax = sqlite3_value_int64(argv[iArg++]);
8416 if( idxNum & 0x2000 ){
8417 if( iMax==SMALLEST_INT64 ){
@@ -10884,10 +10906,13 @@
10884 ** Return NULL if unable.
10885 **
10886 ** The file or directory X is not required to exist. The answer is formed
10887 ** by calling system realpath() on the prefix of X that does exist and
10888 ** appending the tail of X that does not (yet) exist.
 
 
 
10889 */
10890 static void realpathFunc(
10891 sqlite3_context *context,
10892 int argc,
10893 sqlite3_value **argv
@@ -10906,10 +10931,11 @@
10906 (void)argc;
10907 zPath = (const char*)sqlite3_value_text(argv[0]);
10908 if( zPath==0 ) return;
10909 if( zPath[0]==0 ) zPath = ".";
10910 zCopy = sqlite3_mprintf("%s",zPath);
 
10911 len = strlen(zCopy);
10912 while( len>1 && (zCopy[len-1]=='/' || (isWin && zCopy[len-1]=='\\')) ){
10913 len--;
10914 }
10915 zCopy[len] = 0;
@@ -12699,10 +12725,11 @@
12699
12700 for(p=pCsr->pFreeEntry; p; p=pNext){
12701 pNext = p->pNext;
12702 zipfileEntryFree(p);
12703 }
 
12704 }
12705
12706 /*
12707 ** Destructor for an ZipfileCsr.
12708 */
@@ -13101,11 +13128,17 @@
13101 }
13102 }
13103
13104 if( rc==SQLITE_OK ){
13105 u32 *pt = &pNew->mUnixTime;
13106 pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
 
 
 
 
 
 
13107 pNew->aExtra = (u8*)&pNew[1];
13108 memcpy(pNew->aExtra, &aRead[nFile], nExtra);
13109 if( pNew->cds.zFile==0 ){
13110 rc = SQLITE_NOMEM;
13111 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
@@ -14205,14 +14238,14 @@
14205 ZipfileBuffer body;
14206 ZipfileBuffer cds;
14207 };
14208
14209 static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){
14210 if( pBuf->n+nByte>pBuf->nAlloc ){
14211 u8 *aNew;
14212 sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
14213 int nReq = pBuf->n + nByte;
14214
14215 while( nNew<nReq ) nNew = nNew*2;
14216 aNew = sqlite3_realloc64(pBuf->a, nNew);
14217 if( aNew==0 ) return SQLITE_NOMEM;
14218 pBuf->a = aNew;
@@ -16310,11 +16343,11 @@
16310 p->pTable = pTab;
16311
16312 /* The statement the vtab will pass to sqlite3_declare_vtab() */
16313 zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
16314 for(i=0; i<pTab->nCol; i++){
16315 zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
16316 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
16317 );
16318 }
16319 zInner = idxAppendText(&rc, zInner, ")");
16320
@@ -16510,11 +16543,11 @@
16510 sqlite3_free(zCols);
16511 sqlite3_free(zOrder);
16512 return sqlite3_reset(pIndexXInfo);
16513 }
16514 zCols = idxAppendText(&rc, zCols,
16515 "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s",
16516 zComma, zName, nCol, zName, zColl
16517 );
16518 zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
16519 }
16520 sqlite3_reset(pIndexXInfo);
@@ -25163,11 +25196,11 @@
25163 /*
25164 ** Return true if either the SQLITE_NO_COLOR compile-time option is used
25165 ** or if the NO_COLOR environment variable exists
25166 */
25167 static int shellNoColor(void){
25168 #ifdef SQLITE_NO_COLOR
25169 return 1;
25170 #else
25171 return getenv("NO_COLOR")!=0;
25172 #endif
25173 }
@@ -31316,11 +31349,11 @@
31316 typedef struct ArCommand ArCommand;
31317 struct ArCommand {
31318 u8 eCmd; /* An AR_CMD_* value */
31319 u8 bVerbose; /* True if --verbose */
31320 u8 bZip; /* True if the archive is a ZIP */
31321 u8 bDryRun; /* True if --dry-run */
31322 u8 bAppend; /* True if --append */
31323 u8 bGlob; /* True if --glob */
31324 u8 fromCmdLine; /* Run from -A instead of .archive */
31325 int nArg; /* Number of command arguments */
31326 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
@@ -31378,10 +31411,11 @@
31378 #define AR_SWITCH_FILE 9
31379 #define AR_SWITCH_DIRECTORY 10
31380 #define AR_SWITCH_APPEND 11
31381 #define AR_SWITCH_DRYRUN 12
31382 #define AR_SWITCH_GLOB 13
 
31383
31384 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
31385 switch( eSwitch ){
31386 case AR_CMD_CREATE:
31387 case AR_CMD_EXTRACT:
@@ -31395,11 +31429,14 @@
31395 }
31396 pAr->eCmd = eSwitch;
31397 break;
31398
31399 case AR_SWITCH_DRYRUN:
31400 pAr->bDryRun = 1;
 
 
 
31401 break;
31402 case AR_SWITCH_GLOB:
31403 pAr->bGlob = 1;
31404 break;
31405 case AR_SWITCH_VERBOSE:
@@ -31446,10 +31483,11 @@
31446 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
31447 { "file", 'f', AR_SWITCH_FILE, 1 },
31448 { "append", 'a', AR_SWITCH_APPEND, 1 },
31449 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
31450 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
 
31451 { "glob", 'g', AR_SWITCH_GLOB, 0 },
31452 };
31453 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
31454 struct ArSwitch *pEnd = &aSwitch[nSwitch];
31455
@@ -31746,18 +31784,41 @@
31746
31747 /*
31748 ** Implementation of .ar "eXtract" command.
31749 */
31750 static int arExtractCommand(ArCommand *pAr){
 
 
 
 
 
 
 
 
31751 const char *zSql1 =
31752 "WITH dest(dpath,dlen) AS (SELECT realpath($dir),length(realpath($dir)))\n"
31753 "SELECT ($dir || name),\n"
31754 " CASE WHEN $dryrun THEN 0\n"
31755 " ELSE writefile($dir||name, %s, mode, mtime) END\n"
 
 
 
 
 
 
 
 
 
 
 
 
31756 " FROM dest CROSS JOIN %s\n"
31757 " WHERE (%s)\n"
31758 " AND (data IS NULL OR $pass==0)\n" /* Dirs both passes */
 
 
 
31759 " AND dpath=substr(realpath($dir||name),1,dlen)\n" /* No escapes */
31760 " AND name NOT GLOB '*..[/\\]*'\n"; /* No /../ in paths */
31761
31762 const char *azExtraArg[] = {
31763 "sqlar_uncompress(data, sz)",
@@ -31784,39 +31845,48 @@
31784 }
31785 if( zDir==0 ) rc = SQLITE_NOMEM;
31786 }
31787
31788 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
31789 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
 
 
 
31790 );
31791
31792 if( rc==SQLITE_OK ){
31793 j = sqlite3_bind_parameter_index(pSql, "$dir");
31794 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
31795 j = sqlite3_bind_parameter_index(pSql, "$dryrun");
31796 sqlite3_bind_int(pSql, j, pAr->bDryRun);
31797
31798 /* Run the SELECT statement twice
31799 ** (0) writefile() all files and directories
31800 ** (1) writefile() for directory again
31801 ** The second pass is so that the timestamps for extracted directories
 
31802 ** will be reset to the value in the archive, since populating them
31803 ** in the first pass will have changed the timestamp. */
31804 for(i=0; i<2; i++){
 
 
 
31805 j = sqlite3_bind_parameter_index(pSql, "$pass");
31806 sqlite3_bind_int(pSql, j, i);
31807 if( pAr->bDryRun ){
31808 cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql));
31809 if( pAr->bVerbose==0 ) break;
31810 }
31811 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
31812 if( i==0 && pAr->bVerbose ){
31813 cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
31814 }
31815 }
31816 if( pAr->bDryRun ) break;
31817 shellReset(&rc, pSql);
 
 
 
31818 }
31819 shellFinalize(&rc, pSql);
31820 }
31821
31822 sqlite3_free(zDir);
@@ -32327,11 +32397,11 @@
32327 ;
32328 static const char * const zCollectVar = "\
32329 SELECT\
32330 '('||x'0a'\
32331 || group_concat(\
32332 cname||' ANY',\
32333 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
32334 ||')' AS ColsSpec \
32335 FROM (\
32336 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
32337 FROM ColNames ORDER BY cpos\
@@ -37939,11 +38009,11 @@
37939 }
37940
37941 /*
37942 ** The callback from atexit().
37943 */
37944 static void abnormalExit(void){
37945 if( seenInterrupt ) eputz("Program interrupted.\n");
37946 if( globalShellState ){
37947 clearTempFile(globalShellState, 1, 1);
37948 }
37949 }
@@ -38498,12 +38568,14 @@
38498 }else if( cli_strcmp(z,"-nullvalue")==0 ){
38499 modeSetStr(&data.mode.spec.zNull,
38500 cmdline_option_value(argc,argv,++i));
38501 }else if( cli_strcmp(z,"-header")==0 ){
38502 data.mode.spec.bTitles = QRF_Yes;
 
38503 }else if( cli_strcmp(z,"-noheader")==0 ){
38504 data.mode.spec.bTitles = QRF_No;
 
38505 }else if( cli_strcmp(z,"-echo")==0 ){
38506 data.mode.mFlags |= MFLG_ECHO;
38507 }else if( cli_strcmp(z,"-eqp")==0 ){
38508 data.mode.autoEQP = AUTOEQP_on;
38509 }else if( cli_strcmp(z,"-eqpfull")==0 ){
38510
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -5424,11 +5424,11 @@
5424 }
5425 j = 0;
5426 }else{
5427 i = 0;
5428 }
5429 if( len-i>0 ) (void)memcpy(&p->buffer[j], &data[i], len - i);
5430 }
5431
5432 /* Compute a string using sqlite3_vsnprintf() and hash it */
5433 static void hash_step_vformat(
5434 SHA1Context *p, /* Add content to this context */
@@ -6071,32 +6071,41 @@
6071 }
6072 z[i] = 0;
6073 sqlite3_result_text(pCtx, z, i, sqlite3_free);
6074 }
6075
6076 /* Forward declaration */
6077 static void decimal_expand(Decimal *p, int nDigit, int nFrac);
6078
6079 /*
6080 ** Round a decimal value to N significant digits. N must be positive.
6081 */
6082 static void decimal_round(Decimal *p, int N){
6083 int i;
6084 int nZero; /* Number of leading zeros */
6085 if( N<1 ) return;
6086 if( p==0 ) return;
6087 if( p->nDigit<=N ) return;
6088 for(nZero=0; nZero<p->nDigit && p->a[nZero]==0; nZero++){}
6089 N += nZero;
6090 if( p->nDigit<=N ) return;
6091 if( p->a[N]>=5 ){
6092 /* If all leading digits are 9, increase the number of digits
6093 ** by adding a new 0 to the front */
6094 for(i=0; i<N && p->a[i]==9; i++){}
6095 if( i==N ){
6096 decimal_expand(p, p->nDigit+1, 0);
6097 if( p->oom ) return;
6098 }
6099
6100 /* Do the rounding */
6101 p->a[N-1]++;
6102 for(i=N-1; i>0 && p->a[i]>9; i--){
6103 p->a[i] = 0;
6104 p->a[i-1]++;
6105 }
6106 assert( p->a[0]<=9 );
 
 
 
6107 }
6108 memset(&p->a[N], 0, p->nDigit - N);
6109 }
6110
6111 /*
@@ -8378,19 +8387,26 @@
8387 }
8388 }else{
8389 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
8390 }
8391 }else{
8392 if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
8393 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8394 double r = sqlite3_value_double(argv[iArg++]);
8395 if( r<=(double)SMALLEST_INT64 ){
8396 iMin = SMALLEST_INT64;
8397 }else if( r>(double)LARGEST_INT64 ){
8398 goto series_no_rows;
8399 }else{
8400 iMin = (sqlite3_int64)seriesCeil(r);
8401 if( iMin<0 && r>0.0 ){
8402 iMin = LARGEST_INT64;
8403 }
8404 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8405 if( iMin==LARGEST_INT64 ) goto series_no_rows;
8406 iMin++;
8407 }
8408 }
8409 }else{
8410 iMin = sqlite3_value_int64(argv[iArg++]);
8411 if( (idxNum & 0x0200)!=0 ){
8412 if( iMin==LARGEST_INT64 ){
@@ -8399,19 +8415,25 @@
8415 iMin++;
8416 }
8417 }
8418 }
8419 }
8420 if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
8421 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8422 double r = sqlite3_value_double(argv[iArg++]);
8423 if( r>=(double)LARGEST_INT64 ){
8424 iMax = LARGEST_INT64;
8425 }else if( r<=(double)SMALLEST_INT64 ){
8426 goto series_no_rows;
8427 }else{
8428 iMax = (sqlite3_int64)seriesFloor(r);
8429 if( iMax<0 && r>0.0 ){
8430 iMax = LARGEST_INT64;
8431 }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8432 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
8433 iMax--;
8434 }
8435 }
8436 }else{
8437 iMax = sqlite3_value_int64(argv[iArg++]);
8438 if( idxNum & 0x2000 ){
8439 if( iMax==SMALLEST_INT64 ){
@@ -10884,10 +10906,13 @@
10906 ** Return NULL if unable.
10907 **
10908 ** The file or directory X is not required to exist. The answer is formed
10909 ** by calling system realpath() on the prefix of X that does exist and
10910 ** appending the tail of X that does not (yet) exist.
10911 **
10912 ** FIXME: This routine sometimes returns NULL rather than raising
10913 ** an SQLITE_NOMEM error if an OOM is encountered.
10914 */
10915 static void realpathFunc(
10916 sqlite3_context *context,
10917 int argc,
10918 sqlite3_value **argv
@@ -10906,10 +10931,11 @@
10931 (void)argc;
10932 zPath = (const char*)sqlite3_value_text(argv[0]);
10933 if( zPath==0 ) return;
10934 if( zPath[0]==0 ) zPath = ".";
10935 zCopy = sqlite3_mprintf("%s",zPath);
10936 if( zCopy==0 ) return;
10937 len = strlen(zCopy);
10938 while( len>1 && (zCopy[len-1]=='/' || (isWin && zCopy[len-1]=='\\')) ){
10939 len--;
10940 }
10941 zCopy[len] = 0;
@@ -12699,10 +12725,11 @@
12725
12726 for(p=pCsr->pFreeEntry; p; p=pNext){
12727 pNext = p->pNext;
12728 zipfileEntryFree(p);
12729 }
12730 pCsr->pFreeEntry = 0;
12731 }
12732
12733 /*
12734 ** Destructor for an ZipfileCsr.
12735 */
@@ -13101,11 +13128,17 @@
13128 }
13129 }
13130
13131 if( rc==SQLITE_OK ){
13132 u32 *pt = &pNew->mUnixTime;
13133 /* aRead[0..nFile-1] might contain embedded \000 characters
13134 ** See Bug 2026-05-31T11:43:05Z */
13135 pNew->cds.zFile = sqlite3_malloc64(nFile+1);
13136 if( pNew->cds.zFile!=0 ){
13137 memcpy(pNew->cds.zFile, aRead, nFile);
13138 pNew->cds.zFile[nFile] = 0;
13139 }
13140 pNew->aExtra = (u8*)&pNew[1];
13141 memcpy(pNew->aExtra, &aRead[nFile], nExtra);
13142 if( pNew->cds.zFile==0 ){
13143 rc = SQLITE_NOMEM;
13144 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
@@ -14205,14 +14238,14 @@
14238 ZipfileBuffer body;
14239 ZipfileBuffer cds;
14240 };
14241
14242 static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){
14243 if( (pBuf->nAlloc-pBuf->n)<nByte ){
14244 u8 *aNew;
14245 i64 nNew = pBuf->n ? (i64)pBuf->n*2 : 512;
14246 i64 nReq = pBuf->n + nByte;
14247
14248 while( nNew<nReq ) nNew = nNew*2;
14249 aNew = sqlite3_realloc64(pBuf->a, nNew);
14250 if( aNew==0 ) return SQLITE_NOMEM;
14251 pBuf->a = aNew;
@@ -16310,11 +16343,11 @@
16343 p->pTable = pTab;
16344
16345 /* The statement the vtab will pass to sqlite3_declare_vtab() */
16346 zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
16347 for(i=0; i<pTab->nCol; i++){
16348 zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %Q",
16349 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
16350 );
16351 }
16352 zInner = idxAppendText(&rc, zInner, ")");
16353
@@ -16510,11 +16543,11 @@
16543 sqlite3_free(zCols);
16544 sqlite3_free(zOrder);
16545 return sqlite3_reset(pIndexXInfo);
16546 }
16547 zCols = idxAppendText(&rc, zCols,
16548 "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %Q",
16549 zComma, zName, nCol, zName, zColl
16550 );
16551 zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
16552 }
16553 sqlite3_reset(pIndexXInfo);
@@ -25163,11 +25196,11 @@
25196 /*
25197 ** Return true if either the SQLITE_NO_COLOR compile-time option is used
25198 ** or if the NO_COLOR environment variable exists
25199 */
25200 static int shellNoColor(void){
25201 #if defined(SQLITE_NO_COLOR) || defined(SQLITE_SHELL_FIDDLE)
25202 return 1;
25203 #else
25204 return getenv("NO_COLOR")!=0;
25205 #endif
25206 }
@@ -31316,11 +31349,11 @@
31349 typedef struct ArCommand ArCommand;
31350 struct ArCommand {
31351 u8 eCmd; /* An AR_CMD_* value */
31352 u8 bVerbose; /* True if --verbose */
31353 u8 bZip; /* True if the archive is a ZIP */
31354 u8 bDryRun; /* 1 for --dry-run, 2 for --debug */
31355 u8 bAppend; /* True if --append */
31356 u8 bGlob; /* True if --glob */
31357 u8 fromCmdLine; /* Run from -A instead of .archive */
31358 int nArg; /* Number of command arguments */
31359 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
@@ -31378,10 +31411,11 @@
31411 #define AR_SWITCH_FILE 9
31412 #define AR_SWITCH_DIRECTORY 10
31413 #define AR_SWITCH_APPEND 11
31414 #define AR_SWITCH_DRYRUN 12
31415 #define AR_SWITCH_GLOB 13
31416 #define AR_SWITCH_DEBUG 14
31417
31418 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
31419 switch( eSwitch ){
31420 case AR_CMD_CREATE:
31421 case AR_CMD_EXTRACT:
@@ -31395,11 +31429,14 @@
31429 }
31430 pAr->eCmd = eSwitch;
31431 break;
31432
31433 case AR_SWITCH_DRYRUN:
31434 if( pAr->bDryRun<2 ) pAr->bDryRun = 1;
31435 break;
31436 case AR_SWITCH_DEBUG:
31437 pAr->bDryRun = 2;
31438 break;
31439 case AR_SWITCH_GLOB:
31440 pAr->bGlob = 1;
31441 break;
31442 case AR_SWITCH_VERBOSE:
@@ -31446,10 +31483,11 @@
31483 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
31484 { "file", 'f', AR_SWITCH_FILE, 1 },
31485 { "append", 'a', AR_SWITCH_APPEND, 1 },
31486 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
31487 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
31488 { "debug", 0, AR_SWITCH_DEBUG, 0 },
31489 { "glob", 'g', AR_SWITCH_GLOB, 0 },
31490 };
31491 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
31492 struct ArSwitch *pEnd = &aSwitch[nSwitch];
31493
@@ -31746,18 +31784,41 @@
31784
31785 /*
31786 ** Implementation of .ar "eXtract" command.
31787 */
31788 static int arExtractCommand(ArCommand *pAr){
31789 /* The zSql1[] string is a template for the query that does the
31790 ** extraction. Notes:
31791 **
31792 ** * $dir is the directory into which the archive is to be extracted
31793 ** * $pass is the integer pass number: 0, 1, or 2
31794 ** * The dest CTE is created so that realpath($dir) only needs
31795 ** to be called once.
31796 */
31797 const char *zSql1 =
31798 "WITH dest(dpath,dlen) AS (\n"
31799 #ifdef _WIN32
31800 " SELECT realpath($dir) || '\\',\n"
31801 #else
31802 " SELECT realpath($dir) || '/',\n"
31803 #endif
31804 " 1+length(realpath($dir))\n"
31805 ")\n"
31806 "SELECT\n"
31807 " ($dir || name),\n"
31808 " CASE $dryrun\n" /* vv--- azExtraArg */
31809 " WHEN 0 THEN writefile($dir||name, %s, mode, mtime)\n"
31810 " WHEN 1 THEN 0\n"
31811 " ELSE shell_putsnl(format('writefile(%%Q,%%s,%%0o,%%d)',"
31812 "$dir||name,quote(%s),mode,mtime)) IS NULL\n"
31813 " END\n" /* ^^--- azExtraArg */
31814 " FROM dest CROSS JOIN %s\n"
31815 " WHERE (%s)\n" /* ^^-- pAr->zSrcTable */
31816 /* ^^--- zWhere */
31817 " AND (CASE $pass WHEN 0 THEN (mode&0xf000)<>0xa000\n"
31818 " WHEN 1 THEN (mode&0xf000)=0xa000\n"
31819 " ELSE data IS NULL END)\n"
31820 " AND dpath=substr(realpath($dir||name),1,dlen)\n" /* No escapes */
31821 " AND name NOT GLOB '*..[/\\]*'\n"; /* No /../ in paths */
31822
31823 const char *azExtraArg[] = {
31824 "sqlar_uncompress(data, sz)",
@@ -31784,39 +31845,48 @@
31845 }
31846 if( zDir==0 ) rc = SQLITE_NOMEM;
31847 }
31848
31849 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
31850 azExtraArg[pAr->bZip],
31851 azExtraArg[pAr->bZip],
31852 pAr->zSrcTable,
31853 zWhere
31854 );
31855
31856 if( rc==SQLITE_OK ){
31857 j = sqlite3_bind_parameter_index(pSql, "$dir");
31858 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
31859 j = sqlite3_bind_parameter_index(pSql, "$dryrun");
31860 sqlite3_bind_int(pSql, j, pAr->bDryRun);
31861
31862 /* Run the SELECT statement twice
31863 ** (0) writefile() files and directories
31864 ** (1) writefile() symlinks
31865 ** (2) writefile() for directory again
31866 ** The third pass is so that the timestamps for extracted directories
31867 ** will be reset to the value in the archive, since populating them
31868 ** in the first pass will have changed the timestamp. */
31869 for(i=0; i<3; i++){
31870 if( pAr->bDryRun>=2 ){
31871 cli_printf(pAr->out, "*** BEGIN PASS %d ***\n", i+1);
31872 }
31873 j = sqlite3_bind_parameter_index(pSql, "$pass");
31874 sqlite3_bind_int(pSql, j, i);
31875 if( pAr->bDryRun && i==0 ){
31876 cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql));
 
31877 }
31878 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
31879 if( i==0 && pAr->bVerbose ){
31880 cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
31881 }
31882 }
31883 if( pAr->bDryRun==1 ) break;
31884 shellReset(&rc, pSql);
31885 if( pAr->bDryRun>=2 ){
31886 cli_printf(pAr->out, "*** END PASS %d ***\n", i+1);
31887 }
31888 }
31889 shellFinalize(&rc, pSql);
31890 }
31891
31892 sqlite3_free(zDir);
@@ -32327,11 +32397,11 @@
32397 ;
32398 static const char * const zCollectVar = "\
32399 SELECT\
32400 '('||x'0a'\
32401 || group_concat(\
32402 cname,\
32403 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
32404 ||')' AS ColsSpec \
32405 FROM (\
32406 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
32407 FROM ColNames ORDER BY cpos\
@@ -37939,11 +38009,11 @@
38009 }
38010
38011 /*
38012 ** The callback from atexit().
38013 */
38014 static void SQLITE_CDECL abnormalExit(void){
38015 if( seenInterrupt ) eputz("Program interrupted.\n");
38016 if( globalShellState ){
38017 clearTempFile(globalShellState, 1, 1);
38018 }
38019 }
@@ -38498,12 +38568,14 @@
38568 }else if( cli_strcmp(z,"-nullvalue")==0 ){
38569 modeSetStr(&data.mode.spec.zNull,
38570 cmdline_option_value(argc,argv,++i));
38571 }else if( cli_strcmp(z,"-header")==0 ){
38572 data.mode.spec.bTitles = QRF_Yes;
38573 data.mode.mFlags |= MFLG_HDR;
38574 }else if( cli_strcmp(z,"-noheader")==0 ){
38575 data.mode.spec.bTitles = QRF_No;
38576 data.mode.mFlags |= MFLG_HDR;
38577 }else if( cli_strcmp(z,"-echo")==0 ){
38578 data.mode.mFlags |= MFLG_ECHO;
38579 }else if( cli_strcmp(z,"-eqp")==0 ){
38580 data.mode.autoEQP = AUTOEQP_on;
38581 }else if( cli_strcmp(z,"-eqpfull")==0 ){
38582
+448 -221
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -16,11 +16,11 @@
1616
** if you want a wrapper to interface SQLite with your choice of programming
1717
** language. The code for the "sqlite3" command-line shell is also in a
1818
** separate file. This file contains only code for the core SQLite library.
1919
**
2020
** The content in this amalgamation comes from Fossil check-in
21
-** 2c605bfb1562d7a3609ad6ffd7446def12f1 with changes in files:
21
+** 3f3fb9b638f59ad982beafb7c117f24ddd3d with changes in files:
2222
**
2323
**
2424
*/
2525
#ifndef SQLITE_AMALGAMATION
2626
#define SQLITE_CORE 1
@@ -467,14 +467,14 @@
467467
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468468
** [sqlite_version()] and [sqlite_source_id()].
469469
*/
470470
#define SQLITE_VERSION "3.54.0"
471471
#define SQLITE_VERSION_NUMBER 3054000
472
-#define SQLITE_SOURCE_ID "2026-05-30 13:23:25 2c605bfb1562d7a3609ad6ffd7446def12f1ac7084e41b9c6723e998c156501d"
472
+#define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
473473
#define SQLITE_SCM_BRANCH "trunk"
474474
#define SQLITE_SCM_TAGS ""
475
-#define SQLITE_SCM_DATETIME "2026-05-30T13:23:25.636Z"
475
+#define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
476476
477477
/*
478478
** CAPI3REF: Run-Time Library Version Numbers
479479
** KEYWORDS: sqlite3_version sqlite3_sourceid
480480
**
@@ -4696,11 +4696,12 @@
46964696
** <dd>The maximum number of columns in a table definition or in the
46974697
** result set of a [SELECT] or the maximum number of columns in an index
46984698
** or in an ORDER BY or GROUP BY clause.</dd>)^
46994699
**
47004700
** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4701
-** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4701
+** <dd>The maximum depth of the parse tree on any expression and
4702
+** the maximum nesting depth for subqueries and VIEWs</dd>)^
47024703
**
47034704
** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
47044705
** <dd>The maximum depth of the LALR(1) parser stack used to analyze
47054706
** input SQL statements.</dd>)^
47064707
**
@@ -4727,11 +4728,12 @@
47274728
** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
47284729
** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
47294730
** <dd>The maximum index number of any [parameter] in an SQL statement.)^
47304731
**
47314732
** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4732
-** <dd>The maximum depth of recursion for triggers.</dd>)^
4733
+** <dd>The maximum depth of recursion for triggers, and the maximum
4734
+** nesting depth for separate triggers.</dd>)^
47334735
**
47344736
** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
47354737
** <dd>The maximum number of auxiliary worker threads that a single
47364738
** [prepared statement] may start.</dd>)^
47374739
** </dl>
@@ -11533,12 +11535,23 @@
1153311535
** reopen S as an in-memory database based on the serialization
1153411536
** contained in P. If S is a NULL pointer, the main database is
1153511537
** used. The serialized database P is N bytes in size. M is the size
1153611538
** of the buffer P, which might be larger than N. If M is larger than
1153711539
** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then
11538
-** SQLite is permitted to add content to the in-memory database as
11539
-** long as the total size does not exceed M bytes.
11540
+** SQLite is permitted to add content to the in-memory database, in
11541
+** page-sized chunks, as long as the total size does not exceed M bytes.
11542
+**
11543
+** The parameter M must be greater than or equal to N. Ideally, M
11544
+** should have a value which is N+(512&times;K)+20 where K determines how
11545
+** must extra space is available to hold new content as the database
11546
+** grows. K can be 0 if the database is read-only.
11547
+**
11548
+** If the database content in P is malformed in a malicious way then
11549
+** it is possible that SQLite might try to read a few more than N bytes
11550
+** from P. If the veracity of the database content P is uncertain,
11551
+** then applications are advised to allocate about 20 extra bytes on
11552
+** the end of the P buffer to avoid a memory error.
1154011553
**
1154111554
** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
1154211555
** invoke sqlite3_free() on the serialization buffer when the database
1154311556
** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
1154411557
** SQLite will try to increase the buffer size using sqlite3_realloc64()
@@ -15809,10 +15822,17 @@
1580915822
*/
1581015823
#ifndef offsetof
1581115824
# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))
1581215825
#endif
1581315826
15827
+/*
15828
+** sizeof64() is like sizeof(), but always returns a 64-bit value, even
15829
+** on 32-bit builds. This can help to avoid overflow by ensuring 64-bit
15830
+** arithmetic is used consistently in both 32-bit and 64-bit builds.
15831
+*/
15832
+#define sizeof64(X) ((sqlite3_int64)sizeof(X))
15833
+
1581415834
/*
1581515835
** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
1581615836
** to avoid complaints from -fsanitize=strict-bounds.
1581715837
*/
1581815838
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
@@ -20928,10 +20948,11 @@
2092820948
int nTab; /* Number of previously allocated VDBE cursors */
2092920949
int nMem; /* Number of memory cells used so far */
2093020950
int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
2093120951
int iSelfTab; /* Table associated with an index on expr, or negative
2093220952
** of the base register during check-constraint eval */
20953
+ int nNestSel; /* Number of nested SELECT statements and/or VIEWs */
2093320954
int nLabel; /* The *negative* of the number of labels used */
2093420955
int nLabelAlloc; /* Number of slots in aLabel */
2093520956
int *aLabel; /* Space to hold the labels */
2093620957
ExprList *pConstExpr;/* Constant expressions */
2093720958
IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
@@ -33389,12 +33410,12 @@
3338933410
if( flag_alternateform ){
3339033411
/* For %#q, do unistr()-style backslash escapes for
3339133412
** all control characters, and for backslash itself.
3339233413
** For %#Q, do the same but only if there is at least
3339333414
** one control character. */
33394
- u32 nBack = 0;
33395
- u32 nCtrl = 0;
33415
+ i64 nBack = 0;
33416
+ i64 nCtrl = 0;
3339633417
for(k=0; k<i; k++){
3339733418
if( escarg[k]=='\\' ){
3339833419
nBack++;
3339933420
}else if( ((u8*)escarg)[k]<=0x1f ){
3340033421
nCtrl++;
@@ -39255,10 +39276,26 @@
3925539276
******************************************************************************
3925639277
**
3925739278
** This file contains an experimental VFS layer that operates on a
3925839279
** Key/Value storage engine where both keys and values must be pure
3925939280
** text.
39281
+**
39282
+** DEBUG AND TEST
39283
+**
39284
+** For testing on Unix, compile using:
39285
+**
39286
+** make clean sqlite3d CFLAGS='-DSQLITE_OS_KV_OPTIONAL'
39287
+**
39288
+** Then start up a shell using something like:
39289
+**
39290
+** ./sqlite3d 'file:dbname?vfs=kvvfs'
39291
+**
39292
+** Each K/V entry is stored in a separate file in the working
39293
+** directory that has a name like "kvvfs-dbname-*". Due to limitations
39294
+** on the key size, the name of the database must be very short - just
39295
+** a few characters. If the database name is too long, the VFS will
39296
+** malfunction and you will get SQLITE_CORRUPT errors.
3926039297
*/
3926139298
/* #include <sqliteInt.h> */
3926239299
#if SQLITE_OS_KV || (SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL))
3926339300
3926439301
/*****************************************************************************
@@ -39707,16 +39744,18 @@
3970739744
}
3970839745
if( j+n>nOut ) return -1;
3970939746
memset(&aOut[j], 0, n);
3971039747
j += n;
3971139748
if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
39712
- }else{
39749
+ }else if( j<nOut ){
3971339750
aOut[j] = c<<4;
3971439751
c = kvvfsHexValue[aIn[++i]];
3971539752
if( c<0 ) return -1 /* hex bytes are always in pairs */;
3971639753
aOut[j++] += c;
3971739754
i++;
39755
+ }else{
39756
+ return -1;
3971839757
}
3971939758
}
3972039759
return j;
3972139760
}
3972239761
@@ -40138,10 +40177,22 @@
4013840177
}else{
4013940178
pFile->isJournal = 0;
4014040179
pFile->base.pMethods = &kvvfs_db_io_methods;
4014140180
}
4014240181
if( !pFile->zClass ){
40182
+#ifdef SQLITE_WASM
40183
+ if( strlen(zName) >= (KVRECORD_KEY_SZ
40184
+ - 6 /* "kvvfs-" */
40185
+ - 11 /* "-##########" */) ){
40186
+ return SQLITE_CANTOPEN;
40187
+ }
40188
+#else
40189
+ if( 0!=strcmp(zName, "local") && 0!=strcmp(zName, "session") ){
40190
+ /* Historical naming restriction which journaling depends on. */
40191
+ return SQLITE_CANTOPEN;
40192
+ }
40193
+#endif
4014340194
pFile->zClass = zName;
4014440195
}
4014540196
pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ);
4014640197
if( pFile->aData==0 ){
4014740198
return SQLITE_NOMEM;
@@ -52170,15 +52221,33 @@
5217052221
# define sqlite3_win_test_unc_locking 0
5217152222
#endif
5217252223
5217352224
/*
5217452225
** Return true if the string passed as the only argument is likely
52175
-** to be a UNC path. In other words, if it starts with "\\".
52226
+** to be a UNC path. Return false if note.
52227
+**
52228
+** Return true if:
52229
+**
52230
+** (1) The name begins with "\\"
52231
+** (2) But does not begin with "\\?\C:\" where C can be any alphabetic
52232
+** character.
52233
+**
52234
+** For testing, also return true in all cases if the global variable
52235
+** sqlite3_win_test_unc_locking is true.
5217652236
*/
5217752237
static int winIsUNCPath(const char *zFile){
5217852238
if( zFile[0]=='\\' && zFile[1]=='\\' ){
52179
- return 1;
52239
+ if( zFile[2]=='?'
52240
+ && zFile[3]=='\\'
52241
+ && sqlite3Isalpha(zFile[4])
52242
+ && zFile[5]==':'
52243
+ && winIsDirSep(zFile[6])
52244
+ ){
52245
+ return sqlite3_win_test_unc_locking;
52246
+ }else{
52247
+ return 1;
52248
+ }
5218052249
}
5218152250
return sqlite3_win_test_unc_locking;
5218252251
}
5218352252
5218452253
/*
@@ -56926,26 +56995,28 @@
5692656995
szBulk = -1024 * (i64)pcache1.nInitPage;
5692756996
}
5692856997
if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
5692956998
szBulk = pCache->szAlloc*(i64)pCache->nMax;
5693056999
}
56931
- zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
56932
- sqlite3EndBenignMalloc();
56933
- if( zBulk ){
56934
- int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
56935
- do{
56936
- PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
56937
- pX->page.pBuf = zBulk;
56938
- pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX));
56939
- assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) );
56940
- pX->isBulkLocal = 1;
56941
- pX->isAnchor = 0;
56942
- pX->pNext = pCache->pFree;
56943
- pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
56944
- pCache->pFree = pX;
56945
- zBulk += pCache->szAlloc;
56946
- }while( --nBulk );
57000
+ if( szBulk>=pCache->szAlloc ){
57001
+ zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
57002
+ sqlite3EndBenignMalloc();
57003
+ if( zBulk ){
57004
+ int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
57005
+ do{
57006
+ PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
57007
+ pX->page.pBuf = zBulk;
57008
+ pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX));
57009
+ assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) );
57010
+ pX->isBulkLocal = 1;
57011
+ pX->isAnchor = 0;
57012
+ pX->pNext = pCache->pFree;
57013
+ pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
57014
+ pCache->pFree = pX;
57015
+ zBulk += pCache->szAlloc;
57016
+ }while( --nBulk );
57017
+ }
5694757018
}
5694857019
return pCache->pFree!=0;
5694957020
}
5695057021
5695157022
/*
@@ -59839,73 +59910,84 @@
5983959910
#define pager_set_pagehash(X)
5984059911
#define CHECK_PAGE(x)
5984159912
#endif /* SQLITE_CHECK_PAGES */
5984259913
5984359914
/*
59844
-** When this is called the journal file for pager pPager must be open.
59845
-** This function attempts to read a super-journal file name from the
59846
-** end of the file and, if successful, copies it into memory supplied
59847
-** by the caller. See comments above writeSuperJournal() for the format
59848
-** used to store a super-journal file name at the end of a journal file.
59849
-**
59850
-** zSuper must point to a buffer of at least nSuper bytes allocated by
59851
-** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
59852
-** enough space to write the super-journal name). If the super-journal
59853
-** name in the journal is longer than nSuper bytes (including a
59854
-** nul-terminator), then this is handled as if no super-journal name
59855
-** were present in the journal.
59856
-**
59857
-** If a super-journal file name is present at the end of the journal
59858
-** file, then it is copied into the buffer pointed to by zSuper. A
59859
-** nul-terminator byte is appended to the buffer following the
59860
-** super-journal file name.
59861
-**
59862
-** If it is determined that no super-journal file name is present
59863
-** zSuper[0] is set to 0 and SQLITE_OK returned.
59864
-**
59865
-** If an error occurs while reading from the journal file, an SQLite
59866
-** error code is returned.
59867
-*/
59868
-static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u64 nSuper){
59915
+** Free a buffer allocated by the readSuperJournal() function.
59916
+*/
59917
+static void freeSuperJournal(char *zSuper){
59918
+ if( zSuper ){
59919
+ sqlite3_free(&zSuper[-4]);
59920
+ }
59921
+}
59922
+
59923
+/*
59924
+** Parameter pJrnl is a file-handle open on a journal file. This function
59925
+** attempts to read a super-journal file name from the end of the journal
59926
+** file. If successful, it sets output parameter (*pzSuper) to point to a
59927
+** buffer containing the super-journal name as a nul-terminated string.
59928
+** The caller is responsible for freeing the buffer using freeSuperJournal().
59929
+**
59930
+** Refer to comments above writeSuperJournal() for the format used to store
59931
+** a super-journal file name at the end of a journal file.
59932
+**
59933
+** Parameter nSuper is passed the maximum allowable size of the super journal
59934
+** name in bytes. If the super-journal name in the journal is longer than
59935
+** nSuper bytes (including a nul-terminator), then this is handled as if no
59936
+** super-journal name were present in the journal.
59937
+**
59938
+** If there is no super-journal name at the end of pJrnl, (*pzSuper) is
59939
+** set to 0 and SQLITE_OK is returned. Or, if an error occurs while reading
59940
+** the super-journal name, an SQLite error code is returned and (*pzSuper)
59941
+** is set to 0.
59942
+*/
59943
+static int readSuperJournal(sqlite3_file *pJrnl, u64 nSuper, char **pzSuper){
5986959944
int rc; /* Return code */
5987059945
u32 len; /* Length in bytes of super-journal name */
5987159946
i64 szJ; /* Total size in bytes of journal file pJrnl */
5987259947
u32 cksum; /* MJ checksum value read from journal */
59873
- u32 u; /* Unsigned loop counter */
5987459948
unsigned char aMagic[8]; /* A buffer to hold the magic header */
59875
- zSuper[0] = '\0';
59949
+ char *zOut = 0;
5987659950
59951
+ *pzSuper = 0;
5987759952
if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
5987859953
|| szJ<16
5987959954
|| SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
5988059955
|| len>=nSuper
5988159956
|| len>szJ-16
5988259957
|| len==0
5988359958
|| SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
5988459959
|| SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
5988559960
|| memcmp(aMagic, aJournalMagic, 8)
59886
- || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
5988759961
){
5988859962
return rc;
5988959963
}
5989059964
59891
- /* See if the checksum matches the super-journal name */
59892
- for(u=0; u<len; u++){
59893
- cksum -= zSuper[u];
59894
- }
59895
- if( cksum ){
59896
- /* If the checksum doesn't add up, then one or more of the disk sectors
59897
- ** containing the super-journal filename is corrupted. This means
59898
- ** definitely roll back, so just return SQLITE_OK and report a (nul)
59899
- ** super-journal filename.
59900
- */
59901
- len = 0;
59902
- }
59903
- zSuper[len] = '\0';
59904
- zSuper[len+1] = '\0';
59905
-
59906
- return SQLITE_OK;
59965
+ zOut = (char*)sqlite3MallocZero(4 + len + 2);
59966
+ if( !zOut ){
59967
+ rc = SQLITE_NOMEM_BKPT;
59968
+ }else{
59969
+ zOut = &zOut[4];
59970
+ if( SQLITE_OK==(rc = sqlite3OsRead(pJrnl, zOut, len, szJ-16-len)) ){
59971
+ u32 u; /* Unsigned loop counter */
59972
+ /* See if the checksum matches the super-journal name */
59973
+ for(u=0; u<len; u++){
59974
+ cksum -= zOut[u];
59975
+ }
59976
+ }
59977
+ if( rc!=SQLITE_OK || cksum ){
59978
+ /* If the checksum doesn't add up, then one or more of the disk sectors
59979
+ ** containing the super-journal filename is corrupted. This means
59980
+ ** definitely roll back, so just return SQLITE_OK and report a (nul)
59981
+ ** super-journal filename. */
59982
+ freeSuperJournal(zOut);
59983
+ zOut = 0;
59984
+ }
59985
+ }
59986
+
59987
+ *pzSuper = zOut;
59988
+ return rc;
5990759989
}
5990859990
5990959991
/*
5991059992
** Return the offset of the sector boundary at or immediately
5991159993
** following the value in pPager->journalOff, assuming a sector
@@ -61106,13 +61188,11 @@
6110661188
sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */
6110761189
sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
6110861190
char *zSuperJournal = 0; /* Contents of super-journal file */
6110961191
i64 nSuperJournal; /* Size of super-journal file */
6111061192
char *zJournal; /* Pointer to one journal within MJ file */
61111
- char *zSuperPtr; /* Space to hold super-journal filename */
6111261193
char *zFree = 0; /* Free this buffer */
61113
- i64 nSuperPtr; /* Amount of space allocated to zSuperPtr[] */
6111461194
6111561195
/* Allocate space for both the pJournal and pSuper file descriptors.
6111661196
** If successful, open the super-journal file for reading.
6111761197
*/
6111861198
pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
@@ -61131,22 +61211,20 @@
6113161211
** sufficient space (in zSuperPtr) to hold the names of super-journal
6113261212
** files extracted from regular rollback-journals.
6113361213
*/
6113461214
rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
6113561215
if( rc!=SQLITE_OK ) goto delsuper_out;
61136
- nSuperPtr = 1 + (i64)pVfs->mxPathname;
61137
- assert( nSuperJournal>=0 && nSuperPtr>0 );
61138
- zFree = sqlite3Malloc(4 + nSuperJournal + 2 + nSuperPtr + 2);
61216
+ assert( nSuperJournal>=0 );
61217
+ zFree = sqlite3Malloc(4 + nSuperJournal + 2);
6113961218
if( !zFree ){
6114061219
rc = SQLITE_NOMEM_BKPT;
6114161220
goto delsuper_out;
6114261221
}else{
6114361222
assert( nSuperJournal<=0x7fffffff );
6114461223
}
6114561224
zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;
6114661225
zSuperJournal = &zFree[4];
61147
- zSuperPtr = &zSuperJournal[nSuperJournal+2];
6114861226
rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
6114961227
if( rc!=SQLITE_OK ) goto delsuper_out;
6115061228
zSuperJournal[nSuperJournal] = 0;
6115161229
zSuperJournal[nSuperJournal+1] = 0;
6115261230
@@ -61156,10 +61234,12 @@
6115661234
rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
6115761235
if( rc!=SQLITE_OK ){
6115861236
goto delsuper_out;
6115961237
}
6116061238
if( exists ){
61239
+ char *zSuperPtr = 0;
61240
+
6116161241
/* One of the journals pointed to by the super-journal exists.
6116261242
** Open it and check if it points at the super-journal. If
6116361243
** so, return without deleting the super-journal file.
6116461244
** NB: zJournal is really a MAIN_JOURNAL. But call it a
6116561245
** SUPER_JOURNAL here so that the VFS will not send the zJournal
@@ -61170,17 +61250,19 @@
6117061250
rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
6117161251
if( rc!=SQLITE_OK ){
6117261252
goto delsuper_out;
6117361253
}
6117461254
61175
- rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr);
61255
+ rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr);
6117661256
sqlite3OsClose(pJournal);
6117761257
if( rc!=SQLITE_OK ){
61258
+ assert( zSuperPtr==0 );
6117861259
goto delsuper_out;
6117961260
}
6118061261
61181
- c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0;
61262
+ c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0;
61263
+ freeSuperJournal(zSuperPtr);
6118261264
if( c ){
6118361265
/* We have a match. Do not delete the super-journal file. */
6118461266
goto delsuper_out;
6118561267
}
6118661268
}
@@ -61391,23 +61473,15 @@
6139161473
6139261474
/* Read the super-journal name from the journal, if it is present.
6139361475
** If a super-journal file name is specified, but the file is not
6139461476
** present on disk, then the journal is not hot and does not need to be
6139561477
** played back.
61396
- **
61397
- ** TODO: Technically the following is an error because it assumes that
61398
- ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
61399
- ** ((pPager->pageSize+8) >= pPager->pVfs->mxPathname+1). Using os_unix.c,
61400
- ** mxPathname is 512, which is the same as the minimum allowable value
61401
- ** for pageSize, and so this assumption holds. But it might not for some
61402
- ** custom VFS. */
61403
- zSuper = pPager->pTmpSpace;
61404
- rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);
61405
- if( rc==SQLITE_OK && zSuper[0] ){
61478
+ */
61479
+ rc = readSuperJournal(pPager->jfd, 1+(i64)pPager->pVfs->mxPathname, &zSuper);
61480
+ if( rc==SQLITE_OK && zSuper ){
6140661481
rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
6140761482
}
61408
- zSuper = 0;
6140961483
if( rc!=SQLITE_OK || !res ){
6141061484
goto end_playback;
6141161485
}
6141261486
pPager->journalOff = 0;
6141361487
needPagerReset = isHot;
@@ -61532,34 +61606,24 @@
6153261606
** problems for other processes at some point in the future. So, just
6153361607
** in case this has happened, clear the changeCountDone flag now.
6153461608
*/
6153561609
pPager->changeCountDone = pPager->tempFile;
6153661610
61537
- if( rc==SQLITE_OK ){
61538
- /* Leave 4 bytes of space before the super-journal filename in memory.
61539
- ** This is because it may end up being passed to sqlite3OsOpen(), in
61540
- ** which case it requires 4 0x00 bytes in memory immediately before
61541
- ** the filename. */
61542
- zSuper = &pPager->pTmpSpace[4];
61543
- rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);
61544
- testcase( rc!=SQLITE_OK );
61545
- }
6154661611
if( rc==SQLITE_OK
6154761612
&& (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
6154861613
){
6154961614
rc = sqlite3PagerSync(pPager, 0);
6155061615
}
6155161616
if( rc==SQLITE_OK ){
61552
- rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0);
61617
+ rc = pager_end_transaction(pPager, zSuper!=0, 0);
6155361618
testcase( rc!=SQLITE_OK );
6155461619
}
61555
- if( rc==SQLITE_OK && zSuper[0] && res ){
61620
+ if( rc==SQLITE_OK && zSuper && res ){
6155661621
/* If there was a super-journal and this routine will return success,
6155761622
** see if it is possible to delete the super-journal.
6155861623
*/
61559
- assert( zSuper==&pPager->pTmpSpace[4] );
61560
- memset(pPager->pTmpSpace, 0, 4);
61624
+ assert( memcmp(&zSuper[-4], "\0\0\0\0", 4)==0 );
6156161625
rc = pager_delsuper(pPager, zSuper);
6156261626
testcase( rc!=SQLITE_OK );
6156361627
}
6156461628
if( isHot && nPlayback ){
6156561629
sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
@@ -61568,10 +61632,11 @@
6156861632
6156961633
/* The Pager.sectorSize variable may have been updated while rolling
6157061634
** back a journal created by a process with a different sector size
6157161635
** value. Reset it to the correct value for this process.
6157261636
*/
61637
+ freeSuperJournal(zSuper);
6157361638
setSectorSize(pPager);
6157461639
return rc;
6157561640
}
6157661641
6157761642
@@ -67426,10 +67491,16 @@
6742667491
*/
6742767492
pgno = sqlite3Get4byte(&aFrame[0]);
6742867493
if( pgno==0 ){
6742967494
return 0;
6743067495
}
67496
+
67497
+ /* Need a valid page size
67498
+ */
67499
+ if( !pWal->szPage ){
67500
+ return 0;
67501
+ }
6743167502
6743267503
/* A frame is only valid if a checksum of the WAL header,
6743367504
** all prior frames, the first 16 bytes of this frame-header,
6743467505
** and the frame-data matches the checksum in the last 8
6743567506
** bytes of this frame-header.
@@ -69281,11 +69352,11 @@
6928169352
goto begin_unreliable_shm_out;
6928269353
}
6928369354
6928469355
/* Allocate a buffer to read frames into */
6928569356
assert( (pWal->szPage & (pWal->szPage-1))==0 );
69286
- assert( pWal->szPage>=512 && pWal->szPage<=65536 );
69357
+ assert( (pWal->szPage>=512 && pWal->szPage<=65536) || pWal->szPage==0 );
6928769358
szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
6928869359
aFrame = (u8 *)sqlite3_malloc64(szFrame);
6928969360
if( aFrame==0 ){
6929069361
rc = SQLITE_NOMEM_BKPT;
6929169362
goto begin_unreliable_shm_out;
@@ -83086,10 +83157,15 @@
8308683157
if( pc+info.nSize>usableSize ){
8308783158
checkAppendMsg(pCheck, "Extends off end of page");
8308883159
doCoverageCheck = 0;
8308983160
continue;
8309083161
}
83162
+ if( info.nPayload && info.pPayload[0]<2 ){
83163
+ checkAppendMsg(pCheck, "Bad cell header size");
83164
+ doCoverageCheck = 0;
83165
+ continue;
83166
+ }
8309183167
8309283168
/* Check for integer primary key out of range */
8309383169
if( pPage->intKey ){
8309483170
if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
8309583171
checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
@@ -84596,12 +84672,12 @@
8459684672
/* Work-around for GCC bug or bugs:
8459784673
** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270
8459884674
** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114659
8459984675
** The problem appears to be fixed in GCC 15 */
8460084676
i64 x;
84601
- assert( (MEM_Str&~p->flags)*4==sizeof(x) );
84602
- memcpy(&x, (char*)&p->u, (MEM_Str&~p->flags)*4);
84677
+ assert( (sqlite3Config.bSmallMalloc!=0xee)*8==sizeof(x) );
84678
+ memcpy(&x, (char*)&p->u.i, (sqlite3Config.bSmallMalloc!=0xee)*8);
8460384679
p->n = sqlite3Int64ToText(x, zBuf);
8460484680
#else
8460584681
p->n = sqlite3Int64ToText(p->u.i, zBuf);
8460684682
#endif
8460784683
if( p->flags & MEM_IntReal ){
@@ -95448,11 +95524,11 @@
9544895524
QueryPerformanceCounter(&tm);
9544995525
return (sqlite3_uint64)tm.QuadPart;
9545095526
}
9545195527
9545295528
#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && \
95453
- (defined(i386) || defined(__i386__) || defined(_M_IX86))
95529
+ (defined(i586) || defined(__i586__) || defined(_M_IX86))
9545495530
9545595531
__inline__ sqlite_uint64 sqlite3Hwtime(void){
9545695532
unsigned int lo, hi;
9545795533
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
9545895534
return (sqlite_uint64)hi << 32 | lo;
@@ -103037,11 +103113,11 @@
103037103113
if( pFrame ) break;
103038103114
}
103039103115
103040103116
if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
103041103117
rc = SQLITE_ERROR;
103042
- sqlite3VdbeError(p, "too many levels of trigger recursion");
103118
+ sqlite3VdbeError(p, "triggers nested too deep");
103043103119
goto abort_due_to_error;
103044103120
}
103045103121
103046103122
/* Register pRt is used to store the memory required to save the state
103047103123
** of the current program, and the memory required at runtime to execute
@@ -110164,11 +110240,11 @@
110164110240
/*
110165110241
** cnt==0 means there was not match.
110166110242
** cnt>1 means there were two or more matches.
110167110243
**
110168110244
** cnt==0 is always an error. cnt>1 is often an error, but might
110169
- ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
110245
+ ** be multiple matches for a NATURAL OUTER JOIN or a OUTER JOIN USING.
110170110246
*/
110171110247
assert( pFJMatch==0 || cnt>0 );
110172110248
assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
110173110249
if( cnt!=1 ){
110174110250
const char *zErr;
@@ -110247,12 +110323,21 @@
110247110323
pExpr->op = eNewExprOp;
110248110324
lookupname_end:
110249110325
if( cnt==1 ){
110250110326
assert( pNC!=0 );
110251110327
#ifndef SQLITE_OMIT_AUTHORIZATION
110252
- if( db->xAuth && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER) ){
110253
- sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
110328
+ if( db->xAuth ){
110329
+ if( pFJMatch ){
110330
+ assert( pExpr->op==TK_FUNCTION );
110331
+ assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 );
110332
+ assert( pExpr->x.pList==pFJMatch );
110333
+ assert( pFJMatch->nExpr>0 );
110334
+ pExpr = pFJMatch->a[0].pExpr;
110335
+ }
110336
+ if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
110337
+ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
110338
+ }
110254110339
}
110255110340
#endif
110256110341
/* Increment the nRef value on all name contexts from TopNC up to
110257110342
** the point where the name matched. */
110258110343
for(;;){
@@ -115930,10 +116015,11 @@
115930116015
if( i!=nVector ){
115931116016
/* Need to reorder the LHS fields according to aiMap */
115932116017
int rLhsOrig = rLhs;
115933116018
rLhs = sqlite3GetTempRange(pParse, nVector);
115934116019
for(i=0; i<nVector; i++){
116020
+ testcase( aiMap[i]!=i );
115935116021
sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
115936116022
}
115937116023
sqlite3ReleaseTempReg(pParse, rLhsOrig);
115938116024
}
115939116025
}
@@ -115950,11 +116036,12 @@
115950116036
}
115951116037
for(i=0; i<nVector; i++){
115952116038
Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
115953116039
if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
115954116040
if( sqlite3ExprCanBeNull(p) ){
115955
- sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
116041
+ testcase( aiMap[i]!=i );
116042
+ sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+aiMap[i], destStep2);
115956116043
VdbeCoverage(v);
115957116044
}
115958116045
}
115959116046
115960116047
/* Step 3. The LHS is now known to be non-NULL. Do the binary search
@@ -116024,13 +116111,23 @@
116024116111
for(i=0; i<nVector; i++){
116025116112
Expr *p;
116026116113
CollSeq *pColl;
116027116114
int r3 = sqlite3GetTempReg(pParse);
116028116115
p = sqlite3VectorFieldSubexpr(pLeft, i);
116029
- pColl = sqlite3ExprCollSeq(pParse, p);
116030
- sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
116031
- sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
116116
+ if( ExprUseXSelect(pExpr) ){
116117
+ Expr *pRhs = pExpr->x.pSelect->pEList->a[i].pExpr;
116118
+ pColl = sqlite3BinaryCompareCollSeq(pParse, p, pRhs);
116119
+ }else{
116120
+ /* If the RHS of the IN(...) expression are scalar expressions, do
116121
+ ** not consider their collation sequences. The documentation says
116122
+ ** "The collating sequence used for expressions of the form "x IN (y, z,
116123
+ ** ...)" is the collating sequence of x.". */
116124
+ pColl = sqlite3ExprCollSeq(pParse, p);
116125
+ }
116126
+ testcase( aiMap[i]!=i );
116127
+ sqlite3VdbeAddOp3(v, OP_Column, iTab, aiMap[i], r3);
116128
+ sqlite3VdbeAddOp4(v, OP_Ne, rLhs+aiMap[i], destNotNull, r3,
116032116129
(void*)pColl, P4_COLLSEQ);
116033116130
VdbeCoverage(v);
116034116131
sqlite3ReleaseTempReg(pParse, r3);
116035116132
}
116036116133
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
@@ -124365,21 +124462,21 @@
124365124462
}else{
124366124463
nIdxCol = pIdx->nColumn;
124367124464
}
124368124465
pIdx->nSampleCol = nIdxCol;
124369124466
pIdx->mxSample = nSample;
124370
- nByte = ROUND8(sizeof(IndexSample) * nSample);
124371
- nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
124372
- nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
124467
+ nByte = ROUND8(sizeof64(IndexSample) * nSample);
124468
+ nByte += sizeof64(tRowcnt) * nIdxCol * 3 * nSample;
124469
+ nByte += nIdxCol * sizeof64(tRowcnt); /* Space for Index.aAvgEq[] */
124373124470
124374124471
pIdx->aSample = sqlite3DbMallocZero(db, nByte);
124375124472
if( pIdx->aSample==0 ){
124376124473
sqlite3_finalize(pStmt);
124377124474
return SQLITE_NOMEM_BKPT;
124378124475
}
124379124476
pPtr = (u8*)pIdx->aSample;
124380
- pPtr += ROUND8(nSample*sizeof(pIdx->aSample[0]));
124477
+ pPtr += ROUND8(nSample*sizeof64(pIdx->aSample[0]));
124381124478
pSpace = (tRowcnt*)pPtr;
124382124479
assert( EIGHT_BYTE_ALIGNMENT( pSpace ) );
124383124480
pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
124384124481
pIdx->pTable->tabFlags |= TF_HasStat4;
124385124482
for(i=0; i<nSample; i++){
@@ -133231,13 +133328,22 @@
133231133328
x.nUsed = 0;
133232133329
x.apArg = argv+1;
133233133330
sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
133234133331
str.printfFlags = SQLITE_PRINTF_SQLFUNC;
133235133332
sqlite3_str_appendf(&str, zFormat, &x);
133236
- n = str.nChar;
133237
- sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
133238
- SQLITE_DYNAMIC);
133333
+ if( str.accError==SQLITE_OK ){
133334
+ n = str.nChar;
133335
+ sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
133336
+ SQLITE_DYNAMIC);
133337
+ }else{
133338
+ if( str.accError==SQLITE_NOMEM ){
133339
+ sqlite3_result_error_nomem(context);
133340
+ }else{
133341
+ sqlite3_result_error_toobig(context);
133342
+ }
133343
+ sqlite3_str_reset(&str);
133344
+ }
133239133345
}
133240133346
}
133241133347
133242133348
/*
133243133349
** Implementation of the substr() function.
@@ -134405,11 +134511,11 @@
134405134511
int nStr; /* Size of zStr */
134406134512
int nPattern; /* Size of zPattern */
134407134513
int nRep; /* Size of zRep */
134408134514
i64 nOut; /* Maximum size of zOut */
134409134515
int loopLimit; /* Last zStr[] that might match zPattern[] */
134410
- int i, j; /* Loop counters */
134516
+ i64 i, j; /* Loop counters */
134411134517
unsigned cntExpand; /* Number zOut expansions */
134412134518
sqlite3 *db = sqlite3_context_db_handle(context);
134413134519
134414134520
assert( argc==3 );
134415134521
UNUSED_PARAMETER(argc);
@@ -135859,57 +135965,95 @@
135859135965
** from the standard library because:
135860135966
**
135861135967
** (1) To avoid a dependency on qsort()
135862135968
** (2) To avoid the function call to the comparison routine for each
135863135969
** comparison.
135970
+**
135971
+** If parameter iReq is non-negative, then the caller will only access
135972
+** elements a[iReq] and a[iReq+1] (if it exists) of the sorted array and
135973
+** so it is not necessary to position any other elements. Or if iReq is
135974
+** negative, then the final array must be fully sorted.
135864135975
*/
135865
-static void percentSort(double *a, unsigned int n){
135976
+static void percentSort(
135977
+ double *a, /* Array to sort */
135978
+ unsigned int n, /* Number of elements in array a[] */
135979
+ int iReq /* Element caller cares about (or -ve) */
135980
+){
135866135981
int iLt; /* Entries before a[iLt] are less than rPivot */
135867135982
int iGt; /* Entries at or after a[iGt] are greater than rPivot */
135868135983
int i; /* Loop counter */
135869135984
double rPivot; /* The pivot value */
135870135985
135871135986
assert( n>=2 );
135872
- if( a[0]>a[n-1] ){
135873
- SWAP_DOUBLE(a[0],a[n-1])
135874
- }
135875
- if( n==2 ) return;
135876
- iGt = n-1;
135877
- i = n/2;
135878
- if( a[0]>a[i] ){
135879
- SWAP_DOUBLE(a[0],a[i])
135880
- }else if( a[i]>a[iGt] ){
135881
- SWAP_DOUBLE(a[i],a[iGt])
135882
- }
135883
- if( n==3 ) return;
135884
- rPivot = a[i];
135885
- iLt = i = 1;
135886
- do{
135887
- if( a[i]<rPivot ){
135888
- if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
135889
- iLt++;
135890
- i++;
135891
- }else if( a[i]>rPivot ){
135892
- do{
135893
- iGt--;
135894
- }while( iGt>i && a[iGt]>rPivot );
135895
- SWAP_DOUBLE(a[i],a[iGt])
135896
- }else{
135897
- i++;
135898
- }
135899
- }while( i<iGt );
135900
- if( iLt>=2 ) percentSort(a, iLt);
135901
- if( n-iGt>=2 ) percentSort(a+iGt, n-iGt);
135902
-
135903
-/* Uncomment for testing */
135904
-#if 0
135905
- for(i=0; i<n-1; i++){
135906
- assert( a[i]<=a[i+1] );
135907
- }
135908
-#endif
135909
-}
135910
-
135987
+ do{
135988
+ if( a[0]>a[n-1] ){
135989
+ SWAP_DOUBLE(a[0],a[n-1])
135990
+ }
135991
+ if( n==2 ) return;
135992
+ iGt = n-1;
135993
+ i = n/2;
135994
+ if( a[0]>a[i] ){
135995
+ SWAP_DOUBLE(a[0],a[i])
135996
+ }else if( a[i]>a[iGt] ){
135997
+ SWAP_DOUBLE(a[i],a[iGt])
135998
+ }
135999
+ if( n==3 ) return;
136000
+ rPivot = a[i];
136001
+ iLt = i = 1;
136002
+ do{
136003
+ if( a[i]<rPivot ){
136004
+ if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
136005
+ iLt++;
136006
+ i++;
136007
+ }else if( a[i]>rPivot ){
136008
+ do{
136009
+ iGt--;
136010
+ }while( iGt>i && a[iGt]>rPivot );
136011
+ SWAP_DOUBLE(a[i],a[iGt])
136012
+ }else{
136013
+ i++;
136014
+ }
136015
+ }while( i<iGt );
136016
+
136017
+ assert( a[iLt]==rPivot );
136018
+ assert( iGt>iLt );
136019
+
136020
+ if( iReq>=0 ){
136021
+ /* In this case, the only elements that the caller requires sorted into
136022
+ ** the correct positions are elements a[iReq] and a[iReq+1]. At this
136023
+ ** point we know that element a[iLt] is in the correct position and
136024
+ ** all elements smaller than a[iLt] are in the left-hand partition.
136025
+ ** So if (iReq<iLt), then it is only necessary to sort the left
136026
+ ** partition.
136027
+ **
136028
+ ** If (iReq>=iLt), then elements iReq and iReq+1 are either in the
136029
+ ** right partition or the equal partition (elements for which
136030
+ ** iLt<=iElem<iGt). Therefore it is always sufficient to sort only
136031
+ ** the right partition in this case. */
136032
+ if( iReq<iLt ){
136033
+ n = iLt;
136034
+ }else{
136035
+ a += iGt;
136036
+ n -= iGt;
136037
+ iReq = MAX(0, iReq-iGt);
136038
+ }
136039
+ }else{
136040
+ /* Recurse on the smaller partition only. The smaller partition
136041
+ ** will hold n/2 or fewer entries, which assures that the stack
136042
+ ** depth will not exceed O(log(n)), even for pathological cases.
136043
+ ** Loop without recursion for the larger partition. */
136044
+ if( iLt>(int)(n/2) ){
136045
+ if( n-iGt>=2 ) percentSort(a+iGt, n-iGt, -1);
136046
+ n = iLt;
136047
+ }else{
136048
+ if( iLt>=2 ) percentSort(a, iLt, -1);
136049
+ a += iGt;
136050
+ n -= iGt;
136051
+ }
136052
+ }
136053
+ }while( n>=2 );
136054
+}
135911136055
135912136056
/*
135913136057
** The "inverse" function for percentile(Y,P) is called to remove a
135914136058
** row that was previously inserted by "step".
135915136059
*/
@@ -135939,11 +136083,11 @@
135939136083
if( percentIsInfinity(y) ){
135940136084
return;
135941136085
}
135942136086
if( p->bSorted==0 ){
135943136087
assert( p->nUsed>1 );
135944
- percentSort(p->a, p->nUsed);
136088
+ percentSort(p->a, p->nUsed, -1);
135945136089
p->bSorted = 1;
135946136090
}
135947136091
p->bKeepSorted = 1;
135948136092
135949136093
/* Find and remove the row */
@@ -135968,17 +136112,21 @@
135968136112
double ix, vx;
135969136113
p = (Percentile*)sqlite3_aggregate_context(pCtx, 0);
135970136114
if( p==0 ) return;
135971136115
if( p->a==0 ) return;
135972136116
if( p->nUsed ){
136117
+ ix = p->rPct*(p->nUsed-1);
136118
+ i1 = (unsigned)ix;
135973136119
if( p->bSorted==0 ){
136120
+ /* In cases where bIsFinal is non-zero, setting Percentile.bSorted
136121
+ ** after the percentSort() call here is not technically correct, as
136122
+ ** the array is not fully sorted. But in this case the object will be
136123
+ ** freed below anyway, so it doesn't matter. */
135974136124
assert( p->nUsed>1 );
135975
- percentSort(p->a, p->nUsed);
136125
+ percentSort(p->a, p->nUsed, (bIsFinal ? (int)i1 : -1));
135976136126
p->bSorted = 1;
135977136127
}
135978
- ix = p->rPct*(p->nUsed-1);
135979
- i1 = (unsigned)ix;
135980136128
if( settings & 1 ){
135981136129
vx = p->a[i1];
135982136130
}else{
135983136131
i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1;
135984136132
v1 = p->a[i1];
@@ -150488,10 +150636,17 @@
150488150636
SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
150489150637
Table *pTab;
150490150638
sqlite3 *db = pParse->db;
150491150639
u64 savedFlags;
150492150640
150641
+ pParse->nNestSel++;
150642
+#if SQLITE_MAX_EXPR_DEPTH>0
150643
+ if( pParse->nNestSel >= db->aLimit[SQLITE_LIMIT_EXPR_DEPTH] ){
150644
+ sqlite3ErrorMsg(pParse, "VIEWs and/or subqueries nested too deep");
150645
+ return 0;
150646
+ }
150647
+#endif
150493150648
savedFlags = db->flags;
150494150649
db->flags &= ~(u64)SQLITE_FullColNames;
150495150650
db->flags |= SQLITE_ShortColNames;
150496150651
sqlite3SelectPrep(pParse, pSelect, 0);
150497150652
db->flags = savedFlags;
@@ -150509,10 +150664,12 @@
150509150664
pTab->iPKey = -1;
150510150665
if( db->mallocFailed ){
150511150666
sqlite3DeleteTable(db, pTab);
150512150667
return 0;
150513150668
}
150669
+ pParse->nNestSel--;
150670
+ assert( pParse->nNestSel>=0 );
150514150671
return pTab;
150515150672
}
150516150673
150517150674
/*
150518150675
** Get a VDBE for the given parser context. Create a new one if necessary.
@@ -155479,12 +155636,15 @@
155479155636
** Then, if CheckOnCtx.iJoin indicates that this expression is part of an
155480155637
** ON clause from that SrcList (i.e. if iJoin is non-zero), check that it
155481155638
** does not refer to a table to the right of CheckOnCtx.iJoin. */
155482155639
do {
155483155640
SrcList *pSrc = pCtx->pSrc;
155641
+ int nSrc = pSrc->nSrc;
155484155642
int iTab = pExpr->iTable;
155485
- if( iTab>=pSrc->a[0].iCursor && iTab<=pSrc->a[pSrc->nSrc-1].iCursor ){
155643
+ int ii;
155644
+ for(ii=0; ii<nSrc && pSrc->a[ii].iCursor!=iTab; ii++){}
155645
+ if( ii<nSrc ){
155486155646
if( pCtx->iJoin && iTab>pCtx->iJoin ){
155487155647
sqlite3ErrorMsg(pWalker->pParse,
155488155648
"%s references tables to its right",
155489155649
(pCtx->bFuncArg ? "table-function argument" : "ON clause")
155490155650
);
@@ -158449,22 +158609,36 @@
158449158609
Parse *pParse, /* Current parse context */
158450158610
Trigger *pTrigger, /* Trigger to code */
158451158611
Table *pTab, /* The table pTrigger is attached to */
158452158612
int orconf /* ON CONFLICT policy to code trigger program with */
158453158613
){
158454
- Parse *pTop = sqlite3ParseToplevel(pParse);
158614
+ Parse *pTop; /* Top level Parse object */
158455158615
sqlite3 *db = pParse->db; /* Database handle */
158456158616
TriggerPrg *pPrg; /* Value to return */
158457158617
Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
158458158618
Vdbe *v; /* Temporary VM */
158459158619
NameContext sNC; /* Name context for sub-vdbe */
158460158620
SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
158461158621
int iEndTrigger = 0; /* Label to jump to if WHEN is false */
158462158622
Parse sSubParse; /* Parse context for sub-vdbe */
158623
+ int nDepth; /* Trigger depth */
158463158624
158625
+ /* Ensure that triggers are not chained too deep. This test is linear
158626
+ ** in the chaining depth, but sensible code ought not be chaining
158627
+ ** triggers excessively, so that shouldn't be a problem.
158628
+ */
158629
+ pTop = pParse;
158630
+ for(nDepth=0; pTop->pOuterParse; pTop = pTop->pOuterParse, nDepth++){}
158631
+ if( nDepth>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
158632
+ sqlite3ErrorMsg(pParse, "triggers nested too deep");
158633
+ return 0;
158634
+ }
158635
+
158636
+ pTop = sqlite3ParseToplevel(pParse);
158464158637
assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
158465158638
assert( pTop->pVdbe );
158639
+
158466158640
158467158641
/* Allocate the TriggerPrg and SubProgram objects. To ensure that they
158468158642
** are freed if an error occurs, link them into the Parse.pTriggerPrg
158469158643
** list of the top-level Parse object sooner rather than later. */
158470158644
pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
@@ -160462,11 +160636,12 @@
160462160636
** So we have to make a copy before passing it down into sqlite3Update() */
160463160637
pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
160464160638
/* excluded.* columns of type REAL need to be converted to a hard real */
160465160639
for(i=0; i<pTab->nCol; i++){
160466160640
if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
160467
- sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i);
160641
+ int iStorage = pTop->regData + sqlite3TableColumnToStorage(pTab, i);
160642
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, iStorage);
160468160643
}
160469160644
}
160470160645
sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
160471160646
sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
160472160647
VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
@@ -165680,10 +165855,11 @@
165680165855
assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
165681165856
pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
165682165857
WO_EQ|WO_IN|WO_IS, 0);
165683165858
if( pAlt==0 ) continue;
165684165859
if( pAlt->wtFlags & (TERM_CODED) ) continue;
165860
+ if( ExprHasProperty(pAlt->pExpr, EP_Collate) ) continue;
165685165861
if( (pAlt->eOperator & WO_IN)
165686165862
&& ExprUseXSelect(pAlt->pExpr)
165687165863
&& (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
165688165864
){
165689165865
continue;
@@ -166433,11 +166609,14 @@
166433166609
** Mark term iChild as being a child of term iParent
166434166610
*/
166435166611
static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
166436166612
pWC->a[iChild].iParent = iParent;
166437166613
pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
166614
+ assert( pWC->a[iParent].nChild < UMXV(pWC->a[0].nChild) );
166438166615
pWC->a[iParent].nChild++;
166616
+ testcase( pWC->a[iParent].nChild == UMXV(pWC->a[0].nChild) );
166617
+
166439166618
}
166440166619
166441166620
/*
166442166621
** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
166443166622
** a conjunction, then return just pTerm when N==0. If N is exceeds
@@ -166872,21 +167051,22 @@
166872167051
** 1. The SQLITE_Transitive optimization must be enabled
166873167052
** 2. Must be either an == or an IS operator
166874167053
** 3. Not originating in the ON clause of an OUTER JOIN
166875167054
** 4. The operator is not IS or else the query does not contain RIGHT JOIN
166876167055
** 5. The affinities of A and B must be compatible
166877
-** 6. Both operands use the same collating sequence
167056
+** 6. Both operands use the same collating sequence, and they must not
167057
+** use explicit COLLATE clauses.
166878167058
** If this routine returns TRUE, that means that the RHS can be substituted
166879167059
** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
166880167060
** This is an optimization. No harm comes from returning 0. But if 1 is
166881167061
** returned when it should not be, then incorrect answers might result.
166882167062
*/
166883167063
static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){
166884167064
char aff1, aff2;
166885167065
if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; /* (1) */
166886167066
if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; /* (2) */
166887
- if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* (3) */
167067
+ if( ExprHasProperty(pExpr, EP_OuterON|EP_Collate) ) return 0; /* (3) */
166888167068
assert( pSrc!=0 );
166889167069
if( pExpr->op==TK_IS
166890167070
&& pSrc->nSrc>=2
166891167071
&& (pSrc->a[0].fg.jointype & JT_LTORJ)!=0
166892167072
){
@@ -167209,10 +167389,11 @@
167209167389
static const u8 ops[] = {TK_GE, TK_LE};
167210167390
assert( ExprUseXList(pExpr) );
167211167391
pList = pExpr->x.pList;
167212167392
assert( pList!=0 );
167213167393
assert( pList->nExpr==2 );
167394
+ assert( pWC->a[idxTerm].nChild==0 );
167214167395
for(i=0; i<2; i++){
167215167396
Expr *pNewExpr;
167216167397
int idxNew;
167217167398
pNewExpr = sqlite3PExpr(pParse, ops[i],
167218167399
sqlite3ExprDup(db, pExpr->pLeft, 0),
@@ -167419,12 +167600,15 @@
167419167600
&& (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
167420167601
#ifndef SQLITE_OMIT_WINDOWFUNC
167421167602
&& pExpr->x.pSelect->pWin==0
167422167603
#endif
167423167604
&& pWC->op==TK_AND
167605
+ && pExpr->x.pSelect->pEList->nExpr <= UMXV(pTerm->nChild)
167606
+ /* ^-- See bug 2026-06-04T10:00:49Z */
167424167607
){
167425167608
int i;
167609
+ assert( pTerm->nChild==0 );
167426167610
for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
167427167611
int idxNew;
167428167612
idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE);
167429167613
pWC->a[idxNew].u.x.iField = i+1;
167430167614
exprAnalyze(pSrc, pWC, idxNew);
@@ -186978,11 +187162,11 @@
186978187162
** or disables the collection of memory allocation statistics. */
186979187163
sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
186980187164
break;
186981187165
}
186982187166
case SQLITE_CONFIG_SMALL_MALLOC: {
186983
- sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
187167
+ sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int)!=0;
186984187168
break;
186985187169
}
186986187170
case SQLITE_CONFIG_PAGECACHE: {
186987187171
/* EVIDENCE-OF: R-18761-36601 There are three arguments to
186988187172
** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
@@ -193287,10 +193471,16 @@
193287193471
#ifndef SQLITE_CORE
193288193472
/* # include "sqlite3ext.h" */
193289193473
SQLITE_EXTENSION_INIT1
193290193474
#endif
193291193475
193476
+
193477
+/*
193478
+** Assume any b-tree layer with more levels than this is corrupt.
193479
+*/
193480
+#define FTS3_MAX_BTREE_HEIGHT 48
193481
+
193292193482
typedef struct Fts3HashWrapper Fts3HashWrapper;
193293193483
struct Fts3HashWrapper {
193294193484
Fts3Hash hash; /* Hash table */
193295193485
int nRef; /* Number of pointers to this object */
193296193486
};
@@ -195003,11 +195193,15 @@
195003195193
int iHeight; /* Height of this node in tree */
195004195194
195005195195
assert( piLeaf || piLeaf2 );
195006195196
195007195197
fts3GetVarint32(zNode, &iHeight);
195008
- rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
195198
+ if( iHeight>FTS3_MAX_BTREE_HEIGHT ){
195199
+ rc = FTS_CORRUPT_VTAB;
195200
+ }else{
195201
+ rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
195202
+ }
195009195203
assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
195010195204
195011195205
if( rc==SQLITE_OK && iHeight>1 ){
195012195206
char *zBlob = 0; /* Blob read from %_segments table */
195013195207
int nBlob = 0; /* Size of zBlob in bytes */
@@ -195048,12 +195242,17 @@
195048195242
char **pp, /* IN/OUT: Output pointer */
195049195243
sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
195050195244
sqlite3_int64 iVal /* Write this value to the list */
195051195245
){
195052195246
assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
195053
- *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
195054
- *piPrev = iVal;
195247
+ if( iVal-(*piPrev)>=0 ){
195248
+ /* Refuse to write a negative delta integer. This only happens with a
195249
+ ** corrupt db (see the assert above) and can cause buffer overwrites
195250
+ ** in some cases. */
195251
+ *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
195252
+ *piPrev = iVal;
195253
+ }
195055195254
}
195056195255
195057195256
/*
195058195257
** When this function is called, *ppPoslist is assumed to point to the
195059195258
** start of a position-list. After it returns, *ppPoslist points to the
@@ -199532,11 +199731,11 @@
199532199731
break;
199533199732
199534199733
/* State 3. The integer just read is a column number. */
199535199734
default: assert( eState==3 );
199536199735
iCol = (int)v;
199537
- if( iCol<1 || iCol>0x3fffffff ){
199736
+ if( iCol<1 || iCol>(pFts3->nColumn+1) ){
199538199737
rc = SQLITE_CORRUPT_VTAB;
199539199738
break;
199540199739
}
199541199740
if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
199542199741
pCsr->aStat[iCol+1].nDoc++;
@@ -206469,10 +206668,14 @@
206469206668
iMul = -1;
206470206669
}
206471206670
for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
206472206671
iVal = iVal*10 + (zText[i] - '0');
206473206672
}
206673
+
206674
+ /* This if() clause is just to avoid an integer overflow. The record is
206675
+ ** corrupt in this case. */
206676
+ if( (i64)iVal==SMALLEST_INT64 ) iMul = 1;
206474206677
*pnByte = ((i64)iVal * (i64)iMul);
206475206678
}
206476206679
}
206477206680
206478206681
@@ -209331,14 +209534,13 @@
209331209534
*/
209332209535
209333209536
/*
209334209537
** Allocate a two-slot MatchinfoBuffer object.
209335209538
*/
209336
-static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
209539
+static MatchinfoBuffer *fts3MIBufferNew(i64 nElem, const char *zMatchinfo){
209337209540
MatchinfoBuffer *pRet;
209338
- sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
209339
- + SZ_MATCHINFOBUFFER(1);
209541
+ sqlite3_int64 nByte = sizeof(u32) * (2*(i64)nElem+1) + SZ_MATCHINFOBUFFER(1);
209340209542
sqlite3_int64 nStr = strlen(zMatchinfo);
209341209543
209342209544
pRet = sqlite3Fts3MallocZero(nByte + nStr+1);
209343209545
if( pRet ){
209344209546
pRet->aMI[0] = (u8*)(&pRet->aMI[1]) - (u8*)pRet;
@@ -210205,12 +210407,12 @@
210205210407
}
210206210408
sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
210207210409
return SQLITE_ERROR;
210208210410
}
210209210411
210210
-static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
210211
- size_t nVal; /* Number of integers output by cArg */
210412
+static i64 fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
210413
+ i64 nVal; /* Number of integers output by cArg */
210212210414
210213210415
switch( cArg ){
210214210416
case FTS3_MATCHINFO_NDOC:
210215210417
case FTS3_MATCHINFO_NPHRASE:
210216210418
case FTS3_MATCHINFO_NCOL:
@@ -210222,20 +210424,20 @@
210222210424
case FTS3_MATCHINFO_LCS:
210223210425
nVal = pInfo->nCol;
210224210426
break;
210225210427
210226210428
case FTS3_MATCHINFO_LHITS:
210227
- nVal = (size_t)pInfo->nCol * pInfo->nPhrase;
210429
+ nVal = (i64)pInfo->nCol * pInfo->nPhrase;
210228210430
break;
210229210431
210230210432
case FTS3_MATCHINFO_LHITS_BM:
210231
- nVal = (size_t)pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
210433
+ nVal = (i64)pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
210232210434
break;
210233210435
210234210436
default:
210235210437
assert( cArg==FTS3_MATCHINFO_HITS );
210236
- nVal = (size_t)pInfo->nCol * pInfo->nPhrase * 3;
210438
+ nVal = (i64)pInfo->nCol * pInfo->nPhrase * 3;
210237210439
break;
210238210440
}
210239210441
210240210442
return nVal;
210241210443
}
@@ -210513,11 +210715,11 @@
210513210715
}
210514210716
break;
210515210717
210516210718
case FTS3_MATCHINFO_LHITS_BM:
210517210719
case FTS3_MATCHINFO_LHITS: {
210518
- size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
210720
+ i64 nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
210519210721
memset(pInfo->aMatchinfo, 0, nZero);
210520210722
rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
210521210723
break;
210522210724
}
210523210725
@@ -210582,11 +210784,11 @@
210582210784
** matchinfo function has been called for this query. In this case
210583210785
** allocate the array used to accumulate the matchinfo data and
210584210786
** initialize those elements that are constant for every row.
210585210787
*/
210586210788
if( pCsr->pMIBuffer==0 ){
210587
- size_t nMatchinfo = 0; /* Number of u32 elements in match-info */
210789
+ i64 nMatchinfo = 0; /* Number of u32 elements in match-info */
210588210790
int i; /* Used to iterate through zArg */
210589210791
210590210792
/* Determine the number of phrases in the query */
210591210793
pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
210592210794
sInfo.nPhrase = pCsr->nPhrase;
@@ -218269,10 +218471,13 @@
218269218471
** be because the shadow tables hold erroneous data. */
218270218472
if( rc==SQLITE_ERROR ){
218271218473
rc = SQLITE_CORRUPT_VTAB;
218272218474
RTREE_IS_CORRUPT(pRtree);
218273218475
}
218476
+ }else if( iNode<=0 ){
218477
+ RTREE_IS_CORRUPT(pRtree);
218478
+ rc = SQLITE_CORRUPT_VTAB;
218274218479
}else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
218275218480
pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
218276218481
if( !pNode ){
218277218482
rc = SQLITE_NOMEM;
218278218483
}else{
@@ -218910,11 +219115,11 @@
218910219115
i64 iRowid,
218911219116
int *piIndex
218912219117
){
218913219118
int ii;
218914219119
int nCell = NCELL(pNode);
218915
- assert( nCell<200 );
219120
+ assert( nCell<65536 && nCell>=0 );
218916219121
for(ii=0; ii<nCell; ii++){
218917219122
if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
218918219123
*piIndex = ii;
218919219124
return SQLITE_OK;
218920219125
}
@@ -223953,10 +224158,13 @@
223953224158
if( c>=0xc0 ){ \
223954224159
c = icuUtf8Trans1[c-0xc0]; \
223955224160
while( (*zIn & 0xc0)==0x80 ){ \
223956224161
c = (c<<6) + (0x3f & *(zIn++)); \
223957224162
} \
224163
+ if( c<0x80 \
224164
+ || (c&0xFFFFF800)==0xD800 \
224165
+ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
223958224166
}
223959224167
223960224168
#define SQLITE_ICU_SKIP_UTF8(zIn) \
223961224169
assert( *zIn ); \
223962224170
if( *(zIn++)>=0xc0 ){ \
@@ -225858,20 +226066,30 @@
225858226066
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
225859226067
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
225860226068
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
225861226069
-1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
225862226070
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
226071
+
226072
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226073
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226074
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226075
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226076
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226077
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226078
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226079
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
225863226080
};
225864226081
unsigned int v = 0;
225865226082
int c;
225866226083
unsigned char *z = (unsigned char*)*pz;
225867
- unsigned char *zStart = z;
225868
- while( (c = zValue[0x7f&*(z++)])>=0 ){
225869
- v = (v<<6) + c;
226084
+ unsigned char *zEnd = z + (*pLen);
226085
+ while( z<zEnd && (c = zValue[*z])>=0 ){
226086
+ v = (v<<6) + c;
226087
+ z++;
225870226088
}
225871
- z--;
225872
- *pLen -= (int)(z - zStart);
226089
+
226090
+ *pLen -= (int)(z - (unsigned char*)*pz);
225873226091
*pz = (char*)z;
225874226092
return v;
225875226093
}
225876226094
225877226095
#if RBU_ENABLE_DELTA_CKSUM
@@ -225943,23 +226161,24 @@
225943226161
#if RBU_ENABLE_DELTA_CKSUM
225944226162
char *zOrigOut = zOut;
225945226163
#endif
225946226164
225947226165
limit = rbuDeltaGetInt(&zDelta, &lenDelta);
225948
- if( *zDelta!='\n' ){
226166
+ if( lenDelta<=0 || *zDelta!='\n' ){
225949226167
/* ERROR: size integer not terminated by "\n" */
225950226168
return -1;
225951226169
}
225952226170
zDelta++; lenDelta--;
225953226171
while( *zDelta && lenDelta>0 ){
225954226172
unsigned int cnt, ofst;
225955226173
cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
226174
+ if( lenDelta<=0 ) return -1;
225956226175
switch( zDelta[0] ){
225957226176
case '@': {
225958226177
zDelta++; lenDelta--;
225959226178
ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
225960
- if( lenDelta>0 && zDelta[0]!=',' ){
226179
+ if( lenDelta>0 || zDelta[0]!=',' ){
225961226180
/* ERROR: copy command not terminated by ',' */
225962226181
return -1;
225963226182
}
225964226183
zDelta++; lenDelta--;
225965226184
total += cnt;
@@ -225980,11 +226199,11 @@
225980226199
total += cnt;
225981226200
if( total>limit ){
225982226201
/* ERROR: insert command gives an output larger than predicted */
225983226202
return -1;
225984226203
}
225985
- if( (int)cnt>lenDelta ){
226204
+ if( (i64)cnt>(i64)lenDelta ){
225986226205
/* ERROR: insert count exceeds size of delta */
225987226206
return -1;
225988226207
}
225989226208
memcpy(zOut, zDelta, cnt);
225990226209
zOut += cnt;
@@ -226018,11 +226237,11 @@
226018226237
}
226019226238
226020226239
static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
226021226240
int size;
226022226241
size = rbuDeltaGetInt(&zDelta, &lenDelta);
226023
- if( *zDelta!='\n' ){
226242
+ if( lenDelta<=0 || *zDelta!='\n' ){
226024226243
/* ERROR: size integer not terminated by "\n" */
226025226244
return -1;
226026226245
}
226027226246
return size;
226028226247
}
@@ -226066,11 +226285,11 @@
226066226285
if( nOut<0 ){
226067226286
sqlite3_result_error(context, "corrupt fossil delta", -1);
226068226287
return;
226069226288
}
226070226289
226071
- aOut = sqlite3_malloc(nOut+1);
226290
+ aOut = sqlite3_malloc64((i64)nOut+1);
226072226291
if( aOut==0 ){
226073226292
sqlite3_result_error_nomem(context);
226074226293
}else{
226075226294
nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
226076226295
if( nOut2!=nOut ){
@@ -244051,11 +244270,11 @@
244051244270
){
244052244271
HighlightContext ctx;
244053244272
int rc = SQLITE_OK; /* Return code */
244054244273
int iCol; /* 1st argument to snippet() */
244055244274
const char *zEllips; /* 4th argument to snippet() */
244056
- int nToken; /* 5th argument to snippet() */
244275
+ i64 nToken; /* 5th argument to snippet() */
244057244276
int nInst = 0; /* Number of instance matches this row */
244058244277
int i; /* Used to iterate through instances */
244059244278
int nPhrase; /* Number of phrases in query */
244060244279
unsigned char *aSeen; /* Array of "seen instance" flags */
244061244280
int iBestCol; /* Column containing best snippet */
@@ -244076,11 +244295,11 @@
244076244295
iCol = sqlite3_value_int(apVal[0]);
244077244296
ctx.zOpen = fts5ValueToText(apVal[1]);
244078244297
ctx.zClose = fts5ValueToText(apVal[2]);
244079244298
ctx.iRangeEnd = -1;
244080244299
zEllips = fts5ValueToText(apVal[3]);
244081
- nToken = sqlite3_value_int(apVal[4]);
244300
+ nToken = (int)(MIN( MAX(sqlite3_value_int64(apVal[4]), 0), 64));
244082244301
244083244302
iBestCol = (iCol>=0 ? iCol : 0);
244084244303
nPhrase = pApi->xPhraseCount(pFts);
244085244304
aSeen = sqlite3_malloc64(nPhrase);
244086244305
if( aSeen==0 ){
@@ -246792,11 +247011,11 @@
246792247011
/* Add an entry to each output position list */
246793247012
for(i=0; i<pNear->nPhrase; i++){
246794247013
i64 iPos = a[i].reader.iPos;
246795247014
Fts5PoslistWriter *pWriter = &a[i].writer;
246796247015
if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
246797
- sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
247016
+ sqlite3Fts5PoslistSafeAppend(a[i].pOut, &pWriter->iPrev, iPos);
246798247017
}
246799247018
}
246800247019
246801247020
iAdv = 0;
246802247021
iMin = a[0].reader.iLookahead;
@@ -247743,14 +247962,14 @@
247743247962
rc = SQLITE_NOMEM;
247744247963
}else{
247745247964
memset(pSyn, 0, (size_t)nByte);
247746247965
pSyn->pTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
247747247966
pSyn->nFullTerm = pSyn->nQueryTerm = nToken;
247967
+ memcpy(pSyn->pTerm, pToken, nToken);
247748247968
if( pCtx->pConfig->bTokendata ){
247749247969
pSyn->nQueryTerm = (int)strlen(pSyn->pTerm);
247750247970
}
247751
- memcpy(pSyn->pTerm, pToken, nToken);
247752247971
pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
247753247972
pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
247754247973
}
247755247974
}else{
247756247975
Fts5ExprTerm *pTerm;
@@ -249595,11 +249814,11 @@
249595249814
** + 1 byte for a "new column" byte,
249596249815
** + 3 bytes for a new column number (16-bit max) as a varint,
249597249816
** + 5 bytes for the new position offset (32-bit max).
249598249817
*/
249599249818
if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
249600
- sqlite3_int64 nNew = p->nAlloc * 2;
249819
+ sqlite3_int64 nNew = (i64)p->nAlloc * 2;
249601249820
Fts5HashEntry *pNew;
249602249821
Fts5HashEntry **pp;
249603249822
pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
249604249823
if( pNew==0 ) return SQLITE_NOMEM;
249605249824
pNew->nAlloc = (int)nNew;
@@ -251029,11 +251248,11 @@
251029251248
}else{
251030251249
i += fts5GetVarint32(&pData[i], pLvl->nMerge);
251031251250
i += fts5GetVarint32(&pData[i], nTotal);
251032251251
if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
251033251252
pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
251034
- nTotal * sizeof(Fts5StructureSegment)
251253
+ (i64)nTotal * sizeof(Fts5StructureSegment)
251035251254
);
251036251255
nSegment -= nTotal;
251037251256
}
251038251257
251039251258
if( rc==SQLITE_OK ){
@@ -251558,19 +251777,20 @@
251558251777
assert( pLvl->bEof==0 );
251559251778
if( iOff<=pLvl->iFirstOff ){
251560251779
pLvl->bEof = 1;
251561251780
}else{
251562251781
u8 *a = pLvl->pData->p;
251782
+ int nn = pLvl->pData->nn;
251563251783
251564251784
pLvl->iOff = 0;
251565251785
fts5DlidxLvlNext(pLvl);
251566251786
while( 1 ){
251567251787
int nZero = 0;
251568251788
int ii = pLvl->iOff;
251569251789
u64 delta = 0;
251570251790
251571
- while( a[ii]==0 ){
251791
+ while( ii<nn && a[ii]==0 ){
251572251792
nZero++;
251573251793
ii++;
251574251794
}
251575251795
ii += sqlite3Fts5GetVarint(&a[ii], &delta);
251576251796
@@ -251985,11 +252205,11 @@
251985252205
fts5DataRelease(pIter->pLeaf);
251986252206
pIter->pLeaf = 0;
251987252207
while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
251988252208
Fts5Data *pNew;
251989252209
pIter->iLeafPgno--;
251990
- pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
252210
+ pNew = fts5LeafRead(p, FTS5_SEGMENT_ROWID(
251991252211
pIter->pSeg->iSegid, pIter->iLeafPgno
251992252212
));
251993252213
if( pNew ){
251994252214
/* iTermLeafOffset may be equal to szLeaf if the term is the last
251995252215
** thing on the page - i.e. the first rowid is on the following page.
@@ -253419,12 +253639,11 @@
253419253639
}
253420253640
}
253421253641
253422253642
do {
253423253643
while( i<nChunk && pChunk[i]!=0x01 ){
253424
- while( pChunk[i] & 0x80 ) i++;
253425
- i++;
253644
+ fts5IndexSkipVarint(pChunk, i);
253426253645
}
253427253646
if( pCtx->eState ){
253428253647
fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
253429253648
}
253430253649
if( i<nChunk ){
@@ -255163,10 +255382,15 @@
255163255382
int iSOP; /* Start-Of-Position-list */
255164255383
if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
255165255384
iStart = pSeg->iTermLeafOffset;
255166255385
}else{
255167255386
iStart = fts5GetU16(&aPg[0]);
255387
+ }
255388
+ if( iStart>nPg ){
255389
+ FTS5_CORRUPT_IDX(p);
255390
+ sqlite3_free(aIdx);
255391
+ return;
255168255392
}
255169255393
255170255394
iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
255171255395
assert_nc( iSOP<=pSeg->iLeafOffset );
255172255396
@@ -257849,12 +258073,12 @@
257849258073
int *pnOut, /* OUT: Number of output pages */
257850258074
Fts5Data ***papOut /* OUT: Output hash pages */
257851258075
){
257852258076
const int MINSLOT = 32;
257853258077
int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey);
257854
- int nSlot = 0; /* Number of slots in each output page */
257855
- int nOut = 0;
258078
+ i64 nSlot = 0; /* Number of slots in each output page */
258079
+ i64 nOut = 0;
257856258080
257857258081
/* Figure out how many output pages (nOut) and how many slots per
257858258082
** page (nSlot). There are three possibilities:
257859258083
**
257860258084
** 1. The hash table does not yet exist. In this case the new hash
@@ -257875,27 +258099,30 @@
257875258099
/* Case 1. */
257876258100
nOut = 1;
257877258101
nSlot = MINSLOT;
257878258102
}else if( pSeg->nPgTombstone==1 ){
257879258103
/* Case 2. */
257880
- int nElem = (int)fts5GetU32(&pData1->p[4]);
258104
+ u32 nElem = fts5GetU32(&pData1->p[4]);
257881258105
assert( pData1 && iPg1==0 );
257882
- nOut = 1;
257883
- nSlot = MAX(nElem*4, MINSLOT);
257884
- if( nSlot>nSlotPerPage ) nOut = 0;
258106
+ if( nElem>((u32)nSlotPerPage/4) ){
258107
+ nOut = 0;
258108
+ }else{
258109
+ nOut = 1;
258110
+ nSlot = MAX((i64)nElem*4, MINSLOT);
258111
+ }
257885258112
}
257886258113
if( nOut==0 ){
257887258114
/* Case 3. */
257888
- nOut = (pSeg->nPgTombstone * 2 + 1);
258115
+ nOut = ((i64)pSeg->nPgTombstone * 2 + 1);
257889258116
nSlot = nSlotPerPage;
257890258117
}
257891258118
257892258119
/* Allocate the required array and output pages */
257893258120
while( 1 ){
257894258121
int res = 0;
257895
- int ii = 0;
257896
- int szPage = 0;
258122
+ i64 ii = 0;
258123
+ i64 szPage = 0;
257897258124
Fts5Data **apOut = 0;
257898258125
257899258126
/* Allocate space for the new hash table */
257900258127
assert( nSlot>=MINSLOT );
257901258128
apOut = (Fts5Data**)sqlite3Fts5MallocZero(&p->rc, sizeof(Fts5Data*) * nOut);
@@ -258429,11 +258656,11 @@
258429258656
){
258430258657
258431258658
/* Check any rowid-less pages that occur before the current leaf. */
258432258659
for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
258433258660
iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
258434
- pLeaf = fts5DataRead(p, iKey);
258661
+ pLeaf = fts5LeafRead(p, iKey);
258435258662
if( pLeaf ){
258436258663
if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
258437258664
fts5DataRelease(pLeaf);
258438258665
}
258439258666
}
@@ -258440,11 +258667,11 @@
258440258667
iPrevLeaf = fts5DlidxIterPgno(pDlidx);
258441258668
258442258669
/* Check that the leaf page indicated by the iterator really does
258443258670
** contain the rowid suggested by the same. */
258444258671
iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
258445
- pLeaf = fts5DataRead(p, iKey);
258672
+ pLeaf = fts5LeafRead(p, iKey);
258446258673
if( pLeaf ){
258447258674
i64 iRowid;
258448258675
int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
258449258676
ASSERT_SZLEAF_OK(pLeaf);
258450258677
if( iRowidOff>=pLeaf->szLeaf ){
@@ -263040,11 +263267,11 @@
263040263267
int nArg, /* Number of args */
263041263268
sqlite3_value **apUnused /* Function arguments */
263042263269
){
263043263270
assert( nArg==0 );
263044263271
UNUSED_PARAM2(nArg, apUnused);
263045
- sqlite3_result_text(pCtx, "fts5: 2026-05-30 10:24:03 7487a1c59d3aaea9f8b2569dca76bbccf21948b1e7bd8a1d841e04382db696f4", -1, SQLITE_TRANSIENT);
263272
+ sqlite3_result_text(pCtx, "fts5: 2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06", -1, SQLITE_TRANSIENT);
263046263273
}
263047263274
263048263275
/*
263049263276
** Implementation of fts5_locale(LOCALE, TEXT) function.
263050263277
**
263051263278
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -16,11 +16,11 @@
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 **
20 ** The content in this amalgamation comes from Fossil check-in
21 ** 2c605bfb1562d7a3609ad6ffd7446def12f1 with changes in files:
22 **
23 **
24 */
25 #ifndef SQLITE_AMALGAMATION
26 #define SQLITE_CORE 1
@@ -467,14 +467,14 @@
467 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468 ** [sqlite_version()] and [sqlite_source_id()].
469 */
470 #define SQLITE_VERSION "3.54.0"
471 #define SQLITE_VERSION_NUMBER 3054000
472 #define SQLITE_SOURCE_ID "2026-05-30 13:23:25 2c605bfb1562d7a3609ad6ffd7446def12f1ac7084e41b9c6723e998c156501d"
473 #define SQLITE_SCM_BRANCH "trunk"
474 #define SQLITE_SCM_TAGS ""
475 #define SQLITE_SCM_DATETIME "2026-05-30T13:23:25.636Z"
476
477 /*
478 ** CAPI3REF: Run-Time Library Version Numbers
479 ** KEYWORDS: sqlite3_version sqlite3_sourceid
480 **
@@ -4696,11 +4696,12 @@
4696 ** <dd>The maximum number of columns in a table definition or in the
4697 ** result set of a [SELECT] or the maximum number of columns in an index
4698 ** or in an ORDER BY or GROUP BY clause.</dd>)^
4699 **
4700 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4701 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
 
4702 **
4703 ** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
4704 ** <dd>The maximum depth of the LALR(1) parser stack used to analyze
4705 ** input SQL statements.</dd>)^
4706 **
@@ -4727,11 +4728,12 @@
4727 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4728 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4729 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4730 **
4731 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4732 ** <dd>The maximum depth of recursion for triggers.</dd>)^
 
4733 **
4734 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4735 ** <dd>The maximum number of auxiliary worker threads that a single
4736 ** [prepared statement] may start.</dd>)^
4737 ** </dl>
@@ -11533,12 +11535,23 @@
11533 ** reopen S as an in-memory database based on the serialization
11534 ** contained in P. If S is a NULL pointer, the main database is
11535 ** used. The serialized database P is N bytes in size. M is the size
11536 ** of the buffer P, which might be larger than N. If M is larger than
11537 ** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then
11538 ** SQLite is permitted to add content to the in-memory database as
11539 ** long as the total size does not exceed M bytes.
 
 
 
 
 
 
 
 
 
 
 
11540 **
11541 ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
11542 ** invoke sqlite3_free() on the serialization buffer when the database
11543 ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
11544 ** SQLite will try to increase the buffer size using sqlite3_realloc64()
@@ -15809,10 +15822,17 @@
15809 */
15810 #ifndef offsetof
15811 # define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))
15812 #endif
15813
 
 
 
 
 
 
 
15814 /*
15815 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
15816 ** to avoid complaints from -fsanitize=strict-bounds.
15817 */
15818 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
@@ -20928,10 +20948,11 @@
20928 int nTab; /* Number of previously allocated VDBE cursors */
20929 int nMem; /* Number of memory cells used so far */
20930 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
20931 int iSelfTab; /* Table associated with an index on expr, or negative
20932 ** of the base register during check-constraint eval */
 
20933 int nLabel; /* The *negative* of the number of labels used */
20934 int nLabelAlloc; /* Number of slots in aLabel */
20935 int *aLabel; /* Space to hold the labels */
20936 ExprList *pConstExpr;/* Constant expressions */
20937 IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
@@ -33389,12 +33410,12 @@
33389 if( flag_alternateform ){
33390 /* For %#q, do unistr()-style backslash escapes for
33391 ** all control characters, and for backslash itself.
33392 ** For %#Q, do the same but only if there is at least
33393 ** one control character. */
33394 u32 nBack = 0;
33395 u32 nCtrl = 0;
33396 for(k=0; k<i; k++){
33397 if( escarg[k]=='\\' ){
33398 nBack++;
33399 }else if( ((u8*)escarg)[k]<=0x1f ){
33400 nCtrl++;
@@ -39255,10 +39276,26 @@
39255 ******************************************************************************
39256 **
39257 ** This file contains an experimental VFS layer that operates on a
39258 ** Key/Value storage engine where both keys and values must be pure
39259 ** text.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39260 */
39261 /* #include <sqliteInt.h> */
39262 #if SQLITE_OS_KV || (SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL))
39263
39264 /*****************************************************************************
@@ -39707,16 +39744,18 @@
39707 }
39708 if( j+n>nOut ) return -1;
39709 memset(&aOut[j], 0, n);
39710 j += n;
39711 if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
39712 }else{
39713 aOut[j] = c<<4;
39714 c = kvvfsHexValue[aIn[++i]];
39715 if( c<0 ) return -1 /* hex bytes are always in pairs */;
39716 aOut[j++] += c;
39717 i++;
 
 
39718 }
39719 }
39720 return j;
39721 }
39722
@@ -40138,10 +40177,22 @@
40138 }else{
40139 pFile->isJournal = 0;
40140 pFile->base.pMethods = &kvvfs_db_io_methods;
40141 }
40142 if( !pFile->zClass ){
 
 
 
 
 
 
 
 
 
 
 
 
40143 pFile->zClass = zName;
40144 }
40145 pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ);
40146 if( pFile->aData==0 ){
40147 return SQLITE_NOMEM;
@@ -52170,15 +52221,33 @@
52170 # define sqlite3_win_test_unc_locking 0
52171 #endif
52172
52173 /*
52174 ** Return true if the string passed as the only argument is likely
52175 ** to be a UNC path. In other words, if it starts with "\\".
 
 
 
 
 
 
 
 
 
52176 */
52177 static int winIsUNCPath(const char *zFile){
52178 if( zFile[0]=='\\' && zFile[1]=='\\' ){
52179 return 1;
 
 
 
 
 
 
 
 
 
52180 }
52181 return sqlite3_win_test_unc_locking;
52182 }
52183
52184 /*
@@ -56926,26 +56995,28 @@
56926 szBulk = -1024 * (i64)pcache1.nInitPage;
56927 }
56928 if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
56929 szBulk = pCache->szAlloc*(i64)pCache->nMax;
56930 }
56931 zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
56932 sqlite3EndBenignMalloc();
56933 if( zBulk ){
56934 int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
56935 do{
56936 PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
56937 pX->page.pBuf = zBulk;
56938 pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX));
56939 assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) );
56940 pX->isBulkLocal = 1;
56941 pX->isAnchor = 0;
56942 pX->pNext = pCache->pFree;
56943 pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
56944 pCache->pFree = pX;
56945 zBulk += pCache->szAlloc;
56946 }while( --nBulk );
 
 
56947 }
56948 return pCache->pFree!=0;
56949 }
56950
56951 /*
@@ -59839,73 +59910,84 @@
59839 #define pager_set_pagehash(X)
59840 #define CHECK_PAGE(x)
59841 #endif /* SQLITE_CHECK_PAGES */
59842
59843 /*
59844 ** When this is called the journal file for pager pPager must be open.
59845 ** This function attempts to read a super-journal file name from the
59846 ** end of the file and, if successful, copies it into memory supplied
59847 ** by the caller. See comments above writeSuperJournal() for the format
59848 ** used to store a super-journal file name at the end of a journal file.
59849 **
59850 ** zSuper must point to a buffer of at least nSuper bytes allocated by
59851 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
59852 ** enough space to write the super-journal name). If the super-journal
59853 ** name in the journal is longer than nSuper bytes (including a
59854 ** nul-terminator), then this is handled as if no super-journal name
59855 ** were present in the journal.
59856 **
59857 ** If a super-journal file name is present at the end of the journal
59858 ** file, then it is copied into the buffer pointed to by zSuper. A
59859 ** nul-terminator byte is appended to the buffer following the
59860 ** super-journal file name.
59861 **
59862 ** If it is determined that no super-journal file name is present
59863 ** zSuper[0] is set to 0 and SQLITE_OK returned.
59864 **
59865 ** If an error occurs while reading from the journal file, an SQLite
59866 ** error code is returned.
59867 */
59868 static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u64 nSuper){
 
 
 
 
59869 int rc; /* Return code */
59870 u32 len; /* Length in bytes of super-journal name */
59871 i64 szJ; /* Total size in bytes of journal file pJrnl */
59872 u32 cksum; /* MJ checksum value read from journal */
59873 u32 u; /* Unsigned loop counter */
59874 unsigned char aMagic[8]; /* A buffer to hold the magic header */
59875 zSuper[0] = '\0';
59876
 
59877 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
59878 || szJ<16
59879 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
59880 || len>=nSuper
59881 || len>szJ-16
59882 || len==0
59883 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
59884 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
59885 || memcmp(aMagic, aJournalMagic, 8)
59886 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
59887 ){
59888 return rc;
59889 }
59890
59891 /* See if the checksum matches the super-journal name */
59892 for(u=0; u<len; u++){
59893 cksum -= zSuper[u];
59894 }
59895 if( cksum ){
59896 /* If the checksum doesn't add up, then one or more of the disk sectors
59897 ** containing the super-journal filename is corrupted. This means
59898 ** definitely roll back, so just return SQLITE_OK and report a (nul)
59899 ** super-journal filename.
59900 */
59901 len = 0;
59902 }
59903 zSuper[len] = '\0';
59904 zSuper[len+1] = '\0';
59905
59906 return SQLITE_OK;
 
 
 
 
 
 
 
 
59907 }
59908
59909 /*
59910 ** Return the offset of the sector boundary at or immediately
59911 ** following the value in pPager->journalOff, assuming a sector
@@ -61106,13 +61188,11 @@
61106 sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */
61107 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
61108 char *zSuperJournal = 0; /* Contents of super-journal file */
61109 i64 nSuperJournal; /* Size of super-journal file */
61110 char *zJournal; /* Pointer to one journal within MJ file */
61111 char *zSuperPtr; /* Space to hold super-journal filename */
61112 char *zFree = 0; /* Free this buffer */
61113 i64 nSuperPtr; /* Amount of space allocated to zSuperPtr[] */
61114
61115 /* Allocate space for both the pJournal and pSuper file descriptors.
61116 ** If successful, open the super-journal file for reading.
61117 */
61118 pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
@@ -61131,22 +61211,20 @@
61131 ** sufficient space (in zSuperPtr) to hold the names of super-journal
61132 ** files extracted from regular rollback-journals.
61133 */
61134 rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
61135 if( rc!=SQLITE_OK ) goto delsuper_out;
61136 nSuperPtr = 1 + (i64)pVfs->mxPathname;
61137 assert( nSuperJournal>=0 && nSuperPtr>0 );
61138 zFree = sqlite3Malloc(4 + nSuperJournal + 2 + nSuperPtr + 2);
61139 if( !zFree ){
61140 rc = SQLITE_NOMEM_BKPT;
61141 goto delsuper_out;
61142 }else{
61143 assert( nSuperJournal<=0x7fffffff );
61144 }
61145 zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;
61146 zSuperJournal = &zFree[4];
61147 zSuperPtr = &zSuperJournal[nSuperJournal+2];
61148 rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
61149 if( rc!=SQLITE_OK ) goto delsuper_out;
61150 zSuperJournal[nSuperJournal] = 0;
61151 zSuperJournal[nSuperJournal+1] = 0;
61152
@@ -61156,10 +61234,12 @@
61156 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
61157 if( rc!=SQLITE_OK ){
61158 goto delsuper_out;
61159 }
61160 if( exists ){
 
 
61161 /* One of the journals pointed to by the super-journal exists.
61162 ** Open it and check if it points at the super-journal. If
61163 ** so, return without deleting the super-journal file.
61164 ** NB: zJournal is really a MAIN_JOURNAL. But call it a
61165 ** SUPER_JOURNAL here so that the VFS will not send the zJournal
@@ -61170,17 +61250,19 @@
61170 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
61171 if( rc!=SQLITE_OK ){
61172 goto delsuper_out;
61173 }
61174
61175 rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr);
61176 sqlite3OsClose(pJournal);
61177 if( rc!=SQLITE_OK ){
 
61178 goto delsuper_out;
61179 }
61180
61181 c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0;
 
61182 if( c ){
61183 /* We have a match. Do not delete the super-journal file. */
61184 goto delsuper_out;
61185 }
61186 }
@@ -61391,23 +61473,15 @@
61391
61392 /* Read the super-journal name from the journal, if it is present.
61393 ** If a super-journal file name is specified, but the file is not
61394 ** present on disk, then the journal is not hot and does not need to be
61395 ** played back.
61396 **
61397 ** TODO: Technically the following is an error because it assumes that
61398 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
61399 ** ((pPager->pageSize+8) >= pPager->pVfs->mxPathname+1). Using os_unix.c,
61400 ** mxPathname is 512, which is the same as the minimum allowable value
61401 ** for pageSize, and so this assumption holds. But it might not for some
61402 ** custom VFS. */
61403 zSuper = pPager->pTmpSpace;
61404 rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);
61405 if( rc==SQLITE_OK && zSuper[0] ){
61406 rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
61407 }
61408 zSuper = 0;
61409 if( rc!=SQLITE_OK || !res ){
61410 goto end_playback;
61411 }
61412 pPager->journalOff = 0;
61413 needPagerReset = isHot;
@@ -61532,34 +61606,24 @@
61532 ** problems for other processes at some point in the future. So, just
61533 ** in case this has happened, clear the changeCountDone flag now.
61534 */
61535 pPager->changeCountDone = pPager->tempFile;
61536
61537 if( rc==SQLITE_OK ){
61538 /* Leave 4 bytes of space before the super-journal filename in memory.
61539 ** This is because it may end up being passed to sqlite3OsOpen(), in
61540 ** which case it requires 4 0x00 bytes in memory immediately before
61541 ** the filename. */
61542 zSuper = &pPager->pTmpSpace[4];
61543 rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);
61544 testcase( rc!=SQLITE_OK );
61545 }
61546 if( rc==SQLITE_OK
61547 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
61548 ){
61549 rc = sqlite3PagerSync(pPager, 0);
61550 }
61551 if( rc==SQLITE_OK ){
61552 rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0);
61553 testcase( rc!=SQLITE_OK );
61554 }
61555 if( rc==SQLITE_OK && zSuper[0] && res ){
61556 /* If there was a super-journal and this routine will return success,
61557 ** see if it is possible to delete the super-journal.
61558 */
61559 assert( zSuper==&pPager->pTmpSpace[4] );
61560 memset(pPager->pTmpSpace, 0, 4);
61561 rc = pager_delsuper(pPager, zSuper);
61562 testcase( rc!=SQLITE_OK );
61563 }
61564 if( isHot && nPlayback ){
61565 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
@@ -61568,10 +61632,11 @@
61568
61569 /* The Pager.sectorSize variable may have been updated while rolling
61570 ** back a journal created by a process with a different sector size
61571 ** value. Reset it to the correct value for this process.
61572 */
 
61573 setSectorSize(pPager);
61574 return rc;
61575 }
61576
61577
@@ -67426,10 +67491,16 @@
67426 */
67427 pgno = sqlite3Get4byte(&aFrame[0]);
67428 if( pgno==0 ){
67429 return 0;
67430 }
 
 
 
 
 
 
67431
67432 /* A frame is only valid if a checksum of the WAL header,
67433 ** all prior frames, the first 16 bytes of this frame-header,
67434 ** and the frame-data matches the checksum in the last 8
67435 ** bytes of this frame-header.
@@ -69281,11 +69352,11 @@
69281 goto begin_unreliable_shm_out;
69282 }
69283
69284 /* Allocate a buffer to read frames into */
69285 assert( (pWal->szPage & (pWal->szPage-1))==0 );
69286 assert( pWal->szPage>=512 && pWal->szPage<=65536 );
69287 szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
69288 aFrame = (u8 *)sqlite3_malloc64(szFrame);
69289 if( aFrame==0 ){
69290 rc = SQLITE_NOMEM_BKPT;
69291 goto begin_unreliable_shm_out;
@@ -83086,10 +83157,15 @@
83086 if( pc+info.nSize>usableSize ){
83087 checkAppendMsg(pCheck, "Extends off end of page");
83088 doCoverageCheck = 0;
83089 continue;
83090 }
 
 
 
 
 
83091
83092 /* Check for integer primary key out of range */
83093 if( pPage->intKey ){
83094 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
83095 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
@@ -84596,12 +84672,12 @@
84596 /* Work-around for GCC bug or bugs:
84597 ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270
84598 ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114659
84599 ** The problem appears to be fixed in GCC 15 */
84600 i64 x;
84601 assert( (MEM_Str&~p->flags)*4==sizeof(x) );
84602 memcpy(&x, (char*)&p->u, (MEM_Str&~p->flags)*4);
84603 p->n = sqlite3Int64ToText(x, zBuf);
84604 #else
84605 p->n = sqlite3Int64ToText(p->u.i, zBuf);
84606 #endif
84607 if( p->flags & MEM_IntReal ){
@@ -95448,11 +95524,11 @@
95448 QueryPerformanceCounter(&tm);
95449 return (sqlite3_uint64)tm.QuadPart;
95450 }
95451
95452 #elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && \
95453 (defined(i386) || defined(__i386__) || defined(_M_IX86))
95454
95455 __inline__ sqlite_uint64 sqlite3Hwtime(void){
95456 unsigned int lo, hi;
95457 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
95458 return (sqlite_uint64)hi << 32 | lo;
@@ -103037,11 +103113,11 @@
103037 if( pFrame ) break;
103038 }
103039
103040 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
103041 rc = SQLITE_ERROR;
103042 sqlite3VdbeError(p, "too many levels of trigger recursion");
103043 goto abort_due_to_error;
103044 }
103045
103046 /* Register pRt is used to store the memory required to save the state
103047 ** of the current program, and the memory required at runtime to execute
@@ -110164,11 +110240,11 @@
110164 /*
110165 ** cnt==0 means there was not match.
110166 ** cnt>1 means there were two or more matches.
110167 **
110168 ** cnt==0 is always an error. cnt>1 is often an error, but might
110169 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
110170 */
110171 assert( pFJMatch==0 || cnt>0 );
110172 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
110173 if( cnt!=1 ){
110174 const char *zErr;
@@ -110247,12 +110323,21 @@
110247 pExpr->op = eNewExprOp;
110248 lookupname_end:
110249 if( cnt==1 ){
110250 assert( pNC!=0 );
110251 #ifndef SQLITE_OMIT_AUTHORIZATION
110252 if( db->xAuth && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER) ){
110253 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
 
 
 
 
 
 
 
 
 
110254 }
110255 #endif
110256 /* Increment the nRef value on all name contexts from TopNC up to
110257 ** the point where the name matched. */
110258 for(;;){
@@ -115930,10 +116015,11 @@
115930 if( i!=nVector ){
115931 /* Need to reorder the LHS fields according to aiMap */
115932 int rLhsOrig = rLhs;
115933 rLhs = sqlite3GetTempRange(pParse, nVector);
115934 for(i=0; i<nVector; i++){
 
115935 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
115936 }
115937 sqlite3ReleaseTempReg(pParse, rLhsOrig);
115938 }
115939 }
@@ -115950,11 +116036,12 @@
115950 }
115951 for(i=0; i<nVector; i++){
115952 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
115953 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
115954 if( sqlite3ExprCanBeNull(p) ){
115955 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
 
115956 VdbeCoverage(v);
115957 }
115958 }
115959
115960 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
@@ -116024,13 +116111,23 @@
116024 for(i=0; i<nVector; i++){
116025 Expr *p;
116026 CollSeq *pColl;
116027 int r3 = sqlite3GetTempReg(pParse);
116028 p = sqlite3VectorFieldSubexpr(pLeft, i);
116029 pColl = sqlite3ExprCollSeq(pParse, p);
116030 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
116031 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
 
 
 
 
 
 
 
 
 
 
116032 (void*)pColl, P4_COLLSEQ);
116033 VdbeCoverage(v);
116034 sqlite3ReleaseTempReg(pParse, r3);
116035 }
116036 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
@@ -124365,21 +124462,21 @@
124365 }else{
124366 nIdxCol = pIdx->nColumn;
124367 }
124368 pIdx->nSampleCol = nIdxCol;
124369 pIdx->mxSample = nSample;
124370 nByte = ROUND8(sizeof(IndexSample) * nSample);
124371 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
124372 nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
124373
124374 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
124375 if( pIdx->aSample==0 ){
124376 sqlite3_finalize(pStmt);
124377 return SQLITE_NOMEM_BKPT;
124378 }
124379 pPtr = (u8*)pIdx->aSample;
124380 pPtr += ROUND8(nSample*sizeof(pIdx->aSample[0]));
124381 pSpace = (tRowcnt*)pPtr;
124382 assert( EIGHT_BYTE_ALIGNMENT( pSpace ) );
124383 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
124384 pIdx->pTable->tabFlags |= TF_HasStat4;
124385 for(i=0; i<nSample; i++){
@@ -133231,13 +133328,22 @@
133231 x.nUsed = 0;
133232 x.apArg = argv+1;
133233 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
133234 str.printfFlags = SQLITE_PRINTF_SQLFUNC;
133235 sqlite3_str_appendf(&str, zFormat, &x);
133236 n = str.nChar;
133237 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
133238 SQLITE_DYNAMIC);
 
 
 
 
 
 
 
 
 
133239 }
133240 }
133241
133242 /*
133243 ** Implementation of the substr() function.
@@ -134405,11 +134511,11 @@
134405 int nStr; /* Size of zStr */
134406 int nPattern; /* Size of zPattern */
134407 int nRep; /* Size of zRep */
134408 i64 nOut; /* Maximum size of zOut */
134409 int loopLimit; /* Last zStr[] that might match zPattern[] */
134410 int i, j; /* Loop counters */
134411 unsigned cntExpand; /* Number zOut expansions */
134412 sqlite3 *db = sqlite3_context_db_handle(context);
134413
134414 assert( argc==3 );
134415 UNUSED_PARAMETER(argc);
@@ -135859,57 +135965,95 @@
135859 ** from the standard library because:
135860 **
135861 ** (1) To avoid a dependency on qsort()
135862 ** (2) To avoid the function call to the comparison routine for each
135863 ** comparison.
 
 
 
 
 
135864 */
135865 static void percentSort(double *a, unsigned int n){
 
 
 
 
135866 int iLt; /* Entries before a[iLt] are less than rPivot */
135867 int iGt; /* Entries at or after a[iGt] are greater than rPivot */
135868 int i; /* Loop counter */
135869 double rPivot; /* The pivot value */
135870
135871 assert( n>=2 );
135872 if( a[0]>a[n-1] ){
135873 SWAP_DOUBLE(a[0],a[n-1])
135874 }
135875 if( n==2 ) return;
135876 iGt = n-1;
135877 i = n/2;
135878 if( a[0]>a[i] ){
135879 SWAP_DOUBLE(a[0],a[i])
135880 }else if( a[i]>a[iGt] ){
135881 SWAP_DOUBLE(a[i],a[iGt])
135882 }
135883 if( n==3 ) return;
135884 rPivot = a[i];
135885 iLt = i = 1;
135886 do{
135887 if( a[i]<rPivot ){
135888 if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
135889 iLt++;
135890 i++;
135891 }else if( a[i]>rPivot ){
135892 do{
135893 iGt--;
135894 }while( iGt>i && a[iGt]>rPivot );
135895 SWAP_DOUBLE(a[i],a[iGt])
135896 }else{
135897 i++;
135898 }
135899 }while( i<iGt );
135900 if( iLt>=2 ) percentSort(a, iLt);
135901 if( n-iGt>=2 ) percentSort(a+iGt, n-iGt);
135902
135903 /* Uncomment for testing */
135904 #if 0
135905 for(i=0; i<n-1; i++){
135906 assert( a[i]<=a[i+1] );
135907 }
135908 #endif
135909 }
135910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135911
135912 /*
135913 ** The "inverse" function for percentile(Y,P) is called to remove a
135914 ** row that was previously inserted by "step".
135915 */
@@ -135939,11 +136083,11 @@
135939 if( percentIsInfinity(y) ){
135940 return;
135941 }
135942 if( p->bSorted==0 ){
135943 assert( p->nUsed>1 );
135944 percentSort(p->a, p->nUsed);
135945 p->bSorted = 1;
135946 }
135947 p->bKeepSorted = 1;
135948
135949 /* Find and remove the row */
@@ -135968,17 +136112,21 @@
135968 double ix, vx;
135969 p = (Percentile*)sqlite3_aggregate_context(pCtx, 0);
135970 if( p==0 ) return;
135971 if( p->a==0 ) return;
135972 if( p->nUsed ){
 
 
135973 if( p->bSorted==0 ){
 
 
 
 
135974 assert( p->nUsed>1 );
135975 percentSort(p->a, p->nUsed);
135976 p->bSorted = 1;
135977 }
135978 ix = p->rPct*(p->nUsed-1);
135979 i1 = (unsigned)ix;
135980 if( settings & 1 ){
135981 vx = p->a[i1];
135982 }else{
135983 i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1;
135984 v1 = p->a[i1];
@@ -150488,10 +150636,17 @@
150488 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
150489 Table *pTab;
150490 sqlite3 *db = pParse->db;
150491 u64 savedFlags;
150492
 
 
 
 
 
 
 
150493 savedFlags = db->flags;
150494 db->flags &= ~(u64)SQLITE_FullColNames;
150495 db->flags |= SQLITE_ShortColNames;
150496 sqlite3SelectPrep(pParse, pSelect, 0);
150497 db->flags = savedFlags;
@@ -150509,10 +150664,12 @@
150509 pTab->iPKey = -1;
150510 if( db->mallocFailed ){
150511 sqlite3DeleteTable(db, pTab);
150512 return 0;
150513 }
 
 
150514 return pTab;
150515 }
150516
150517 /*
150518 ** Get a VDBE for the given parser context. Create a new one if necessary.
@@ -155479,12 +155636,15 @@
155479 ** Then, if CheckOnCtx.iJoin indicates that this expression is part of an
155480 ** ON clause from that SrcList (i.e. if iJoin is non-zero), check that it
155481 ** does not refer to a table to the right of CheckOnCtx.iJoin. */
155482 do {
155483 SrcList *pSrc = pCtx->pSrc;
 
155484 int iTab = pExpr->iTable;
155485 if( iTab>=pSrc->a[0].iCursor && iTab<=pSrc->a[pSrc->nSrc-1].iCursor ){
 
 
155486 if( pCtx->iJoin && iTab>pCtx->iJoin ){
155487 sqlite3ErrorMsg(pWalker->pParse,
155488 "%s references tables to its right",
155489 (pCtx->bFuncArg ? "table-function argument" : "ON clause")
155490 );
@@ -158449,22 +158609,36 @@
158449 Parse *pParse, /* Current parse context */
158450 Trigger *pTrigger, /* Trigger to code */
158451 Table *pTab, /* The table pTrigger is attached to */
158452 int orconf /* ON CONFLICT policy to code trigger program with */
158453 ){
158454 Parse *pTop = sqlite3ParseToplevel(pParse);
158455 sqlite3 *db = pParse->db; /* Database handle */
158456 TriggerPrg *pPrg; /* Value to return */
158457 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
158458 Vdbe *v; /* Temporary VM */
158459 NameContext sNC; /* Name context for sub-vdbe */
158460 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
158461 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
158462 Parse sSubParse; /* Parse context for sub-vdbe */
 
158463
 
 
 
 
 
 
 
 
 
 
 
 
158464 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
158465 assert( pTop->pVdbe );
 
158466
158467 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
158468 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
158469 ** list of the top-level Parse object sooner rather than later. */
158470 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
@@ -160462,11 +160636,12 @@
160462 ** So we have to make a copy before passing it down into sqlite3Update() */
160463 pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
160464 /* excluded.* columns of type REAL need to be converted to a hard real */
160465 for(i=0; i<pTab->nCol; i++){
160466 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
160467 sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i);
 
160468 }
160469 }
160470 sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
160471 sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
160472 VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
@@ -165680,10 +165855,11 @@
165680 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
165681 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
165682 WO_EQ|WO_IN|WO_IS, 0);
165683 if( pAlt==0 ) continue;
165684 if( pAlt->wtFlags & (TERM_CODED) ) continue;
 
165685 if( (pAlt->eOperator & WO_IN)
165686 && ExprUseXSelect(pAlt->pExpr)
165687 && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
165688 ){
165689 continue;
@@ -166433,11 +166609,14 @@
166433 ** Mark term iChild as being a child of term iParent
166434 */
166435 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
166436 pWC->a[iChild].iParent = iParent;
166437 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
 
166438 pWC->a[iParent].nChild++;
 
 
166439 }
166440
166441 /*
166442 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
166443 ** a conjunction, then return just pTerm when N==0. If N is exceeds
@@ -166872,21 +167051,22 @@
166872 ** 1. The SQLITE_Transitive optimization must be enabled
166873 ** 2. Must be either an == or an IS operator
166874 ** 3. Not originating in the ON clause of an OUTER JOIN
166875 ** 4. The operator is not IS or else the query does not contain RIGHT JOIN
166876 ** 5. The affinities of A and B must be compatible
166877 ** 6. Both operands use the same collating sequence
 
166878 ** If this routine returns TRUE, that means that the RHS can be substituted
166879 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
166880 ** This is an optimization. No harm comes from returning 0. But if 1 is
166881 ** returned when it should not be, then incorrect answers might result.
166882 */
166883 static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){
166884 char aff1, aff2;
166885 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; /* (1) */
166886 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; /* (2) */
166887 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* (3) */
166888 assert( pSrc!=0 );
166889 if( pExpr->op==TK_IS
166890 && pSrc->nSrc>=2
166891 && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0
166892 ){
@@ -167209,10 +167389,11 @@
167209 static const u8 ops[] = {TK_GE, TK_LE};
167210 assert( ExprUseXList(pExpr) );
167211 pList = pExpr->x.pList;
167212 assert( pList!=0 );
167213 assert( pList->nExpr==2 );
 
167214 for(i=0; i<2; i++){
167215 Expr *pNewExpr;
167216 int idxNew;
167217 pNewExpr = sqlite3PExpr(pParse, ops[i],
167218 sqlite3ExprDup(db, pExpr->pLeft, 0),
@@ -167419,12 +167600,15 @@
167419 && (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
167420 #ifndef SQLITE_OMIT_WINDOWFUNC
167421 && pExpr->x.pSelect->pWin==0
167422 #endif
167423 && pWC->op==TK_AND
 
 
167424 ){
167425 int i;
 
167426 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
167427 int idxNew;
167428 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE);
167429 pWC->a[idxNew].u.x.iField = i+1;
167430 exprAnalyze(pSrc, pWC, idxNew);
@@ -186978,11 +187162,11 @@
186978 ** or disables the collection of memory allocation statistics. */
186979 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
186980 break;
186981 }
186982 case SQLITE_CONFIG_SMALL_MALLOC: {
186983 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
186984 break;
186985 }
186986 case SQLITE_CONFIG_PAGECACHE: {
186987 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
186988 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
@@ -193287,10 +193471,16 @@
193287 #ifndef SQLITE_CORE
193288 /* # include "sqlite3ext.h" */
193289 SQLITE_EXTENSION_INIT1
193290 #endif
193291
 
 
 
 
 
 
193292 typedef struct Fts3HashWrapper Fts3HashWrapper;
193293 struct Fts3HashWrapper {
193294 Fts3Hash hash; /* Hash table */
193295 int nRef; /* Number of pointers to this object */
193296 };
@@ -195003,11 +195193,15 @@
195003 int iHeight; /* Height of this node in tree */
195004
195005 assert( piLeaf || piLeaf2 );
195006
195007 fts3GetVarint32(zNode, &iHeight);
195008 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
 
 
 
 
195009 assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
195010
195011 if( rc==SQLITE_OK && iHeight>1 ){
195012 char *zBlob = 0; /* Blob read from %_segments table */
195013 int nBlob = 0; /* Size of zBlob in bytes */
@@ -195048,12 +195242,17 @@
195048 char **pp, /* IN/OUT: Output pointer */
195049 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
195050 sqlite3_int64 iVal /* Write this value to the list */
195051 ){
195052 assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
195053 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
195054 *piPrev = iVal;
 
 
 
 
 
195055 }
195056
195057 /*
195058 ** When this function is called, *ppPoslist is assumed to point to the
195059 ** start of a position-list. After it returns, *ppPoslist points to the
@@ -199532,11 +199731,11 @@
199532 break;
199533
199534 /* State 3. The integer just read is a column number. */
199535 default: assert( eState==3 );
199536 iCol = (int)v;
199537 if( iCol<1 || iCol>0x3fffffff ){
199538 rc = SQLITE_CORRUPT_VTAB;
199539 break;
199540 }
199541 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
199542 pCsr->aStat[iCol+1].nDoc++;
@@ -206469,10 +206668,14 @@
206469 iMul = -1;
206470 }
206471 for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
206472 iVal = iVal*10 + (zText[i] - '0');
206473 }
 
 
 
 
206474 *pnByte = ((i64)iVal * (i64)iMul);
206475 }
206476 }
206477
206478
@@ -209331,14 +209534,13 @@
209331 */
209332
209333 /*
209334 ** Allocate a two-slot MatchinfoBuffer object.
209335 */
209336 static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
209337 MatchinfoBuffer *pRet;
209338 sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
209339 + SZ_MATCHINFOBUFFER(1);
209340 sqlite3_int64 nStr = strlen(zMatchinfo);
209341
209342 pRet = sqlite3Fts3MallocZero(nByte + nStr+1);
209343 if( pRet ){
209344 pRet->aMI[0] = (u8*)(&pRet->aMI[1]) - (u8*)pRet;
@@ -210205,12 +210407,12 @@
210205 }
210206 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
210207 return SQLITE_ERROR;
210208 }
210209
210210 static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
210211 size_t nVal; /* Number of integers output by cArg */
210212
210213 switch( cArg ){
210214 case FTS3_MATCHINFO_NDOC:
210215 case FTS3_MATCHINFO_NPHRASE:
210216 case FTS3_MATCHINFO_NCOL:
@@ -210222,20 +210424,20 @@
210222 case FTS3_MATCHINFO_LCS:
210223 nVal = pInfo->nCol;
210224 break;
210225
210226 case FTS3_MATCHINFO_LHITS:
210227 nVal = (size_t)pInfo->nCol * pInfo->nPhrase;
210228 break;
210229
210230 case FTS3_MATCHINFO_LHITS_BM:
210231 nVal = (size_t)pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
210232 break;
210233
210234 default:
210235 assert( cArg==FTS3_MATCHINFO_HITS );
210236 nVal = (size_t)pInfo->nCol * pInfo->nPhrase * 3;
210237 break;
210238 }
210239
210240 return nVal;
210241 }
@@ -210513,11 +210715,11 @@
210513 }
210514 break;
210515
210516 case FTS3_MATCHINFO_LHITS_BM:
210517 case FTS3_MATCHINFO_LHITS: {
210518 size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
210519 memset(pInfo->aMatchinfo, 0, nZero);
210520 rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
210521 break;
210522 }
210523
@@ -210582,11 +210784,11 @@
210582 ** matchinfo function has been called for this query. In this case
210583 ** allocate the array used to accumulate the matchinfo data and
210584 ** initialize those elements that are constant for every row.
210585 */
210586 if( pCsr->pMIBuffer==0 ){
210587 size_t nMatchinfo = 0; /* Number of u32 elements in match-info */
210588 int i; /* Used to iterate through zArg */
210589
210590 /* Determine the number of phrases in the query */
210591 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
210592 sInfo.nPhrase = pCsr->nPhrase;
@@ -218269,10 +218471,13 @@
218269 ** be because the shadow tables hold erroneous data. */
218270 if( rc==SQLITE_ERROR ){
218271 rc = SQLITE_CORRUPT_VTAB;
218272 RTREE_IS_CORRUPT(pRtree);
218273 }
 
 
 
218274 }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
218275 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
218276 if( !pNode ){
218277 rc = SQLITE_NOMEM;
218278 }else{
@@ -218910,11 +219115,11 @@
218910 i64 iRowid,
218911 int *piIndex
218912 ){
218913 int ii;
218914 int nCell = NCELL(pNode);
218915 assert( nCell<200 );
218916 for(ii=0; ii<nCell; ii++){
218917 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
218918 *piIndex = ii;
218919 return SQLITE_OK;
218920 }
@@ -223953,10 +224158,13 @@
223953 if( c>=0xc0 ){ \
223954 c = icuUtf8Trans1[c-0xc0]; \
223955 while( (*zIn & 0xc0)==0x80 ){ \
223956 c = (c<<6) + (0x3f & *(zIn++)); \
223957 } \
 
 
 
223958 }
223959
223960 #define SQLITE_ICU_SKIP_UTF8(zIn) \
223961 assert( *zIn ); \
223962 if( *(zIn++)>=0xc0 ){ \
@@ -225858,20 +226066,30 @@
225858 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
225859 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
225860 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
225861 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
225862 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
 
 
 
 
 
 
 
 
 
225863 };
225864 unsigned int v = 0;
225865 int c;
225866 unsigned char *z = (unsigned char*)*pz;
225867 unsigned char *zStart = z;
225868 while( (c = zValue[0x7f&*(z++)])>=0 ){
225869 v = (v<<6) + c;
 
225870 }
225871 z--;
225872 *pLen -= (int)(z - zStart);
225873 *pz = (char*)z;
225874 return v;
225875 }
225876
225877 #if RBU_ENABLE_DELTA_CKSUM
@@ -225943,23 +226161,24 @@
225943 #if RBU_ENABLE_DELTA_CKSUM
225944 char *zOrigOut = zOut;
225945 #endif
225946
225947 limit = rbuDeltaGetInt(&zDelta, &lenDelta);
225948 if( *zDelta!='\n' ){
225949 /* ERROR: size integer not terminated by "\n" */
225950 return -1;
225951 }
225952 zDelta++; lenDelta--;
225953 while( *zDelta && lenDelta>0 ){
225954 unsigned int cnt, ofst;
225955 cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
 
225956 switch( zDelta[0] ){
225957 case '@': {
225958 zDelta++; lenDelta--;
225959 ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
225960 if( lenDelta>0 && zDelta[0]!=',' ){
225961 /* ERROR: copy command not terminated by ',' */
225962 return -1;
225963 }
225964 zDelta++; lenDelta--;
225965 total += cnt;
@@ -225980,11 +226199,11 @@
225980 total += cnt;
225981 if( total>limit ){
225982 /* ERROR: insert command gives an output larger than predicted */
225983 return -1;
225984 }
225985 if( (int)cnt>lenDelta ){
225986 /* ERROR: insert count exceeds size of delta */
225987 return -1;
225988 }
225989 memcpy(zOut, zDelta, cnt);
225990 zOut += cnt;
@@ -226018,11 +226237,11 @@
226018 }
226019
226020 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
226021 int size;
226022 size = rbuDeltaGetInt(&zDelta, &lenDelta);
226023 if( *zDelta!='\n' ){
226024 /* ERROR: size integer not terminated by "\n" */
226025 return -1;
226026 }
226027 return size;
226028 }
@@ -226066,11 +226285,11 @@
226066 if( nOut<0 ){
226067 sqlite3_result_error(context, "corrupt fossil delta", -1);
226068 return;
226069 }
226070
226071 aOut = sqlite3_malloc(nOut+1);
226072 if( aOut==0 ){
226073 sqlite3_result_error_nomem(context);
226074 }else{
226075 nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
226076 if( nOut2!=nOut ){
@@ -244051,11 +244270,11 @@
244051 ){
244052 HighlightContext ctx;
244053 int rc = SQLITE_OK; /* Return code */
244054 int iCol; /* 1st argument to snippet() */
244055 const char *zEllips; /* 4th argument to snippet() */
244056 int nToken; /* 5th argument to snippet() */
244057 int nInst = 0; /* Number of instance matches this row */
244058 int i; /* Used to iterate through instances */
244059 int nPhrase; /* Number of phrases in query */
244060 unsigned char *aSeen; /* Array of "seen instance" flags */
244061 int iBestCol; /* Column containing best snippet */
@@ -244076,11 +244295,11 @@
244076 iCol = sqlite3_value_int(apVal[0]);
244077 ctx.zOpen = fts5ValueToText(apVal[1]);
244078 ctx.zClose = fts5ValueToText(apVal[2]);
244079 ctx.iRangeEnd = -1;
244080 zEllips = fts5ValueToText(apVal[3]);
244081 nToken = sqlite3_value_int(apVal[4]);
244082
244083 iBestCol = (iCol>=0 ? iCol : 0);
244084 nPhrase = pApi->xPhraseCount(pFts);
244085 aSeen = sqlite3_malloc64(nPhrase);
244086 if( aSeen==0 ){
@@ -246792,11 +247011,11 @@
246792 /* Add an entry to each output position list */
246793 for(i=0; i<pNear->nPhrase; i++){
246794 i64 iPos = a[i].reader.iPos;
246795 Fts5PoslistWriter *pWriter = &a[i].writer;
246796 if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
246797 sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
246798 }
246799 }
246800
246801 iAdv = 0;
246802 iMin = a[0].reader.iLookahead;
@@ -247743,14 +247962,14 @@
247743 rc = SQLITE_NOMEM;
247744 }else{
247745 memset(pSyn, 0, (size_t)nByte);
247746 pSyn->pTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
247747 pSyn->nFullTerm = pSyn->nQueryTerm = nToken;
 
247748 if( pCtx->pConfig->bTokendata ){
247749 pSyn->nQueryTerm = (int)strlen(pSyn->pTerm);
247750 }
247751 memcpy(pSyn->pTerm, pToken, nToken);
247752 pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
247753 pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
247754 }
247755 }else{
247756 Fts5ExprTerm *pTerm;
@@ -249595,11 +249814,11 @@
249595 ** + 1 byte for a "new column" byte,
249596 ** + 3 bytes for a new column number (16-bit max) as a varint,
249597 ** + 5 bytes for the new position offset (32-bit max).
249598 */
249599 if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
249600 sqlite3_int64 nNew = p->nAlloc * 2;
249601 Fts5HashEntry *pNew;
249602 Fts5HashEntry **pp;
249603 pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
249604 if( pNew==0 ) return SQLITE_NOMEM;
249605 pNew->nAlloc = (int)nNew;
@@ -251029,11 +251248,11 @@
251029 }else{
251030 i += fts5GetVarint32(&pData[i], pLvl->nMerge);
251031 i += fts5GetVarint32(&pData[i], nTotal);
251032 if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
251033 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
251034 nTotal * sizeof(Fts5StructureSegment)
251035 );
251036 nSegment -= nTotal;
251037 }
251038
251039 if( rc==SQLITE_OK ){
@@ -251558,19 +251777,20 @@
251558 assert( pLvl->bEof==0 );
251559 if( iOff<=pLvl->iFirstOff ){
251560 pLvl->bEof = 1;
251561 }else{
251562 u8 *a = pLvl->pData->p;
 
251563
251564 pLvl->iOff = 0;
251565 fts5DlidxLvlNext(pLvl);
251566 while( 1 ){
251567 int nZero = 0;
251568 int ii = pLvl->iOff;
251569 u64 delta = 0;
251570
251571 while( a[ii]==0 ){
251572 nZero++;
251573 ii++;
251574 }
251575 ii += sqlite3Fts5GetVarint(&a[ii], &delta);
251576
@@ -251985,11 +252205,11 @@
251985 fts5DataRelease(pIter->pLeaf);
251986 pIter->pLeaf = 0;
251987 while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
251988 Fts5Data *pNew;
251989 pIter->iLeafPgno--;
251990 pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
251991 pIter->pSeg->iSegid, pIter->iLeafPgno
251992 ));
251993 if( pNew ){
251994 /* iTermLeafOffset may be equal to szLeaf if the term is the last
251995 ** thing on the page - i.e. the first rowid is on the following page.
@@ -253419,12 +253639,11 @@
253419 }
253420 }
253421
253422 do {
253423 while( i<nChunk && pChunk[i]!=0x01 ){
253424 while( pChunk[i] & 0x80 ) i++;
253425 i++;
253426 }
253427 if( pCtx->eState ){
253428 fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
253429 }
253430 if( i<nChunk ){
@@ -255163,10 +255382,15 @@
255163 int iSOP; /* Start-Of-Position-list */
255164 if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
255165 iStart = pSeg->iTermLeafOffset;
255166 }else{
255167 iStart = fts5GetU16(&aPg[0]);
 
 
 
 
 
255168 }
255169
255170 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
255171 assert_nc( iSOP<=pSeg->iLeafOffset );
255172
@@ -257849,12 +258073,12 @@
257849 int *pnOut, /* OUT: Number of output pages */
257850 Fts5Data ***papOut /* OUT: Output hash pages */
257851 ){
257852 const int MINSLOT = 32;
257853 int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey);
257854 int nSlot = 0; /* Number of slots in each output page */
257855 int nOut = 0;
257856
257857 /* Figure out how many output pages (nOut) and how many slots per
257858 ** page (nSlot). There are three possibilities:
257859 **
257860 ** 1. The hash table does not yet exist. In this case the new hash
@@ -257875,27 +258099,30 @@
257875 /* Case 1. */
257876 nOut = 1;
257877 nSlot = MINSLOT;
257878 }else if( pSeg->nPgTombstone==1 ){
257879 /* Case 2. */
257880 int nElem = (int)fts5GetU32(&pData1->p[4]);
257881 assert( pData1 && iPg1==0 );
257882 nOut = 1;
257883 nSlot = MAX(nElem*4, MINSLOT);
257884 if( nSlot>nSlotPerPage ) nOut = 0;
 
 
 
257885 }
257886 if( nOut==0 ){
257887 /* Case 3. */
257888 nOut = (pSeg->nPgTombstone * 2 + 1);
257889 nSlot = nSlotPerPage;
257890 }
257891
257892 /* Allocate the required array and output pages */
257893 while( 1 ){
257894 int res = 0;
257895 int ii = 0;
257896 int szPage = 0;
257897 Fts5Data **apOut = 0;
257898
257899 /* Allocate space for the new hash table */
257900 assert( nSlot>=MINSLOT );
257901 apOut = (Fts5Data**)sqlite3Fts5MallocZero(&p->rc, sizeof(Fts5Data*) * nOut);
@@ -258429,11 +258656,11 @@
258429 ){
258430
258431 /* Check any rowid-less pages that occur before the current leaf. */
258432 for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
258433 iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
258434 pLeaf = fts5DataRead(p, iKey);
258435 if( pLeaf ){
258436 if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
258437 fts5DataRelease(pLeaf);
258438 }
258439 }
@@ -258440,11 +258667,11 @@
258440 iPrevLeaf = fts5DlidxIterPgno(pDlidx);
258441
258442 /* Check that the leaf page indicated by the iterator really does
258443 ** contain the rowid suggested by the same. */
258444 iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
258445 pLeaf = fts5DataRead(p, iKey);
258446 if( pLeaf ){
258447 i64 iRowid;
258448 int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
258449 ASSERT_SZLEAF_OK(pLeaf);
258450 if( iRowidOff>=pLeaf->szLeaf ){
@@ -263040,11 +263267,11 @@
263040 int nArg, /* Number of args */
263041 sqlite3_value **apUnused /* Function arguments */
263042 ){
263043 assert( nArg==0 );
263044 UNUSED_PARAM2(nArg, apUnused);
263045 sqlite3_result_text(pCtx, "fts5: 2026-05-30 10:24:03 7487a1c59d3aaea9f8b2569dca76bbccf21948b1e7bd8a1d841e04382db696f4", -1, SQLITE_TRANSIENT);
263046 }
263047
263048 /*
263049 ** Implementation of fts5_locale(LOCALE, TEXT) function.
263050 **
263051
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -16,11 +16,11 @@
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 **
20 ** The content in this amalgamation comes from Fossil check-in
21 ** 3f3fb9b638f59ad982beafb7c117f24ddd3d with changes in files:
22 **
23 **
24 */
25 #ifndef SQLITE_AMALGAMATION
26 #define SQLITE_CORE 1
@@ -467,14 +467,14 @@
467 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468 ** [sqlite_version()] and [sqlite_source_id()].
469 */
470 #define SQLITE_VERSION "3.54.0"
471 #define SQLITE_VERSION_NUMBER 3054000
472 #define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
473 #define SQLITE_SCM_BRANCH "trunk"
474 #define SQLITE_SCM_TAGS ""
475 #define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
476
477 /*
478 ** CAPI3REF: Run-Time Library Version Numbers
479 ** KEYWORDS: sqlite3_version sqlite3_sourceid
480 **
@@ -4696,11 +4696,12 @@
4696 ** <dd>The maximum number of columns in a table definition or in the
4697 ** result set of a [SELECT] or the maximum number of columns in an index
4698 ** or in an ORDER BY or GROUP BY clause.</dd>)^
4699 **
4700 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4701 ** <dd>The maximum depth of the parse tree on any expression and
4702 ** the maximum nesting depth for subqueries and VIEWs</dd>)^
4703 **
4704 ** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
4705 ** <dd>The maximum depth of the LALR(1) parser stack used to analyze
4706 ** input SQL statements.</dd>)^
4707 **
@@ -4727,11 +4728,12 @@
4728 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4729 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4730 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4731 **
4732 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4733 ** <dd>The maximum depth of recursion for triggers, and the maximum
4734 ** nesting depth for separate triggers.</dd>)^
4735 **
4736 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4737 ** <dd>The maximum number of auxiliary worker threads that a single
4738 ** [prepared statement] may start.</dd>)^
4739 ** </dl>
@@ -11533,12 +11535,23 @@
11535 ** reopen S as an in-memory database based on the serialization
11536 ** contained in P. If S is a NULL pointer, the main database is
11537 ** used. The serialized database P is N bytes in size. M is the size
11538 ** of the buffer P, which might be larger than N. If M is larger than
11539 ** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then
11540 ** SQLite is permitted to add content to the in-memory database, in
11541 ** page-sized chunks, as long as the total size does not exceed M bytes.
11542 **
11543 ** The parameter M must be greater than or equal to N. Ideally, M
11544 ** should have a value which is N+(512&times;K)+20 where K determines how
11545 ** must extra space is available to hold new content as the database
11546 ** grows. K can be 0 if the database is read-only.
11547 **
11548 ** If the database content in P is malformed in a malicious way then
11549 ** it is possible that SQLite might try to read a few more than N bytes
11550 ** from P. If the veracity of the database content P is uncertain,
11551 ** then applications are advised to allocate about 20 extra bytes on
11552 ** the end of the P buffer to avoid a memory error.
11553 **
11554 ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
11555 ** invoke sqlite3_free() on the serialization buffer when the database
11556 ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
11557 ** SQLite will try to increase the buffer size using sqlite3_realloc64()
@@ -15809,10 +15822,17 @@
15822 */
15823 #ifndef offsetof
15824 # define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))
15825 #endif
15826
15827 /*
15828 ** sizeof64() is like sizeof(), but always returns a 64-bit value, even
15829 ** on 32-bit builds. This can help to avoid overflow by ensuring 64-bit
15830 ** arithmetic is used consistently in both 32-bit and 64-bit builds.
15831 */
15832 #define sizeof64(X) ((sqlite3_int64)sizeof(X))
15833
15834 /*
15835 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
15836 ** to avoid complaints from -fsanitize=strict-bounds.
15837 */
15838 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
@@ -20928,10 +20948,11 @@
20948 int nTab; /* Number of previously allocated VDBE cursors */
20949 int nMem; /* Number of memory cells used so far */
20950 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
20951 int iSelfTab; /* Table associated with an index on expr, or negative
20952 ** of the base register during check-constraint eval */
20953 int nNestSel; /* Number of nested SELECT statements and/or VIEWs */
20954 int nLabel; /* The *negative* of the number of labels used */
20955 int nLabelAlloc; /* Number of slots in aLabel */
20956 int *aLabel; /* Space to hold the labels */
20957 ExprList *pConstExpr;/* Constant expressions */
20958 IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
@@ -33389,12 +33410,12 @@
33410 if( flag_alternateform ){
33411 /* For %#q, do unistr()-style backslash escapes for
33412 ** all control characters, and for backslash itself.
33413 ** For %#Q, do the same but only if there is at least
33414 ** one control character. */
33415 i64 nBack = 0;
33416 i64 nCtrl = 0;
33417 for(k=0; k<i; k++){
33418 if( escarg[k]=='\\' ){
33419 nBack++;
33420 }else if( ((u8*)escarg)[k]<=0x1f ){
33421 nCtrl++;
@@ -39255,10 +39276,26 @@
39276 ******************************************************************************
39277 **
39278 ** This file contains an experimental VFS layer that operates on a
39279 ** Key/Value storage engine where both keys and values must be pure
39280 ** text.
39281 **
39282 ** DEBUG AND TEST
39283 **
39284 ** For testing on Unix, compile using:
39285 **
39286 ** make clean sqlite3d CFLAGS='-DSQLITE_OS_KV_OPTIONAL'
39287 **
39288 ** Then start up a shell using something like:
39289 **
39290 ** ./sqlite3d 'file:dbname?vfs=kvvfs'
39291 **
39292 ** Each K/V entry is stored in a separate file in the working
39293 ** directory that has a name like "kvvfs-dbname-*". Due to limitations
39294 ** on the key size, the name of the database must be very short - just
39295 ** a few characters. If the database name is too long, the VFS will
39296 ** malfunction and you will get SQLITE_CORRUPT errors.
39297 */
39298 /* #include <sqliteInt.h> */
39299 #if SQLITE_OS_KV || (SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL))
39300
39301 /*****************************************************************************
@@ -39707,16 +39744,18 @@
39744 }
39745 if( j+n>nOut ) return -1;
39746 memset(&aOut[j], 0, n);
39747 j += n;
39748 if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
39749 }else if( j<nOut ){
39750 aOut[j] = c<<4;
39751 c = kvvfsHexValue[aIn[++i]];
39752 if( c<0 ) return -1 /* hex bytes are always in pairs */;
39753 aOut[j++] += c;
39754 i++;
39755 }else{
39756 return -1;
39757 }
39758 }
39759 return j;
39760 }
39761
@@ -40138,10 +40177,22 @@
40177 }else{
40178 pFile->isJournal = 0;
40179 pFile->base.pMethods = &kvvfs_db_io_methods;
40180 }
40181 if( !pFile->zClass ){
40182 #ifdef SQLITE_WASM
40183 if( strlen(zName) >= (KVRECORD_KEY_SZ
40184 - 6 /* "kvvfs-" */
40185 - 11 /* "-##########" */) ){
40186 return SQLITE_CANTOPEN;
40187 }
40188 #else
40189 if( 0!=strcmp(zName, "local") && 0!=strcmp(zName, "session") ){
40190 /* Historical naming restriction which journaling depends on. */
40191 return SQLITE_CANTOPEN;
40192 }
40193 #endif
40194 pFile->zClass = zName;
40195 }
40196 pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ);
40197 if( pFile->aData==0 ){
40198 return SQLITE_NOMEM;
@@ -52170,15 +52221,33 @@
52221 # define sqlite3_win_test_unc_locking 0
52222 #endif
52223
52224 /*
52225 ** Return true if the string passed as the only argument is likely
52226 ** to be a UNC path. Return false if note.
52227 **
52228 ** Return true if:
52229 **
52230 ** (1) The name begins with "\\"
52231 ** (2) But does not begin with "\\?\C:\" where C can be any alphabetic
52232 ** character.
52233 **
52234 ** For testing, also return true in all cases if the global variable
52235 ** sqlite3_win_test_unc_locking is true.
52236 */
52237 static int winIsUNCPath(const char *zFile){
52238 if( zFile[0]=='\\' && zFile[1]=='\\' ){
52239 if( zFile[2]=='?'
52240 && zFile[3]=='\\'
52241 && sqlite3Isalpha(zFile[4])
52242 && zFile[5]==':'
52243 && winIsDirSep(zFile[6])
52244 ){
52245 return sqlite3_win_test_unc_locking;
52246 }else{
52247 return 1;
52248 }
52249 }
52250 return sqlite3_win_test_unc_locking;
52251 }
52252
52253 /*
@@ -56926,26 +56995,28 @@
56995 szBulk = -1024 * (i64)pcache1.nInitPage;
56996 }
56997 if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
56998 szBulk = pCache->szAlloc*(i64)pCache->nMax;
56999 }
57000 if( szBulk>=pCache->szAlloc ){
57001 zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
57002 sqlite3EndBenignMalloc();
57003 if( zBulk ){
57004 int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
57005 do{
57006 PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
57007 pX->page.pBuf = zBulk;
57008 pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX));
57009 assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) );
57010 pX->isBulkLocal = 1;
57011 pX->isAnchor = 0;
57012 pX->pNext = pCache->pFree;
57013 pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
57014 pCache->pFree = pX;
57015 zBulk += pCache->szAlloc;
57016 }while( --nBulk );
57017 }
57018 }
57019 return pCache->pFree!=0;
57020 }
57021
57022 /*
@@ -59839,73 +59910,84 @@
59910 #define pager_set_pagehash(X)
59911 #define CHECK_PAGE(x)
59912 #endif /* SQLITE_CHECK_PAGES */
59913
59914 /*
59915 ** Free a buffer allocated by the readSuperJournal() function.
59916 */
59917 static void freeSuperJournal(char *zSuper){
59918 if( zSuper ){
59919 sqlite3_free(&zSuper[-4]);
59920 }
59921 }
59922
59923 /*
59924 ** Parameter pJrnl is a file-handle open on a journal file. This function
59925 ** attempts to read a super-journal file name from the end of the journal
59926 ** file. If successful, it sets output parameter (*pzSuper) to point to a
59927 ** buffer containing the super-journal name as a nul-terminated string.
59928 ** The caller is responsible for freeing the buffer using freeSuperJournal().
59929 **
59930 ** Refer to comments above writeSuperJournal() for the format used to store
59931 ** a super-journal file name at the end of a journal file.
59932 **
59933 ** Parameter nSuper is passed the maximum allowable size of the super journal
59934 ** name in bytes. If the super-journal name in the journal is longer than
59935 ** nSuper bytes (including a nul-terminator), then this is handled as if no
59936 ** super-journal name were present in the journal.
59937 **
59938 ** If there is no super-journal name at the end of pJrnl, (*pzSuper) is
59939 ** set to 0 and SQLITE_OK is returned. Or, if an error occurs while reading
59940 ** the super-journal name, an SQLite error code is returned and (*pzSuper)
59941 ** is set to 0.
59942 */
59943 static int readSuperJournal(sqlite3_file *pJrnl, u64 nSuper, char **pzSuper){
59944 int rc; /* Return code */
59945 u32 len; /* Length in bytes of super-journal name */
59946 i64 szJ; /* Total size in bytes of journal file pJrnl */
59947 u32 cksum; /* MJ checksum value read from journal */
 
59948 unsigned char aMagic[8]; /* A buffer to hold the magic header */
59949 char *zOut = 0;
59950
59951 *pzSuper = 0;
59952 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
59953 || szJ<16
59954 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
59955 || len>=nSuper
59956 || len>szJ-16
59957 || len==0
59958 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
59959 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
59960 || memcmp(aMagic, aJournalMagic, 8)
 
59961 ){
59962 return rc;
59963 }
59964
59965 zOut = (char*)sqlite3MallocZero(4 + len + 2);
59966 if( !zOut ){
59967 rc = SQLITE_NOMEM_BKPT;
59968 }else{
59969 zOut = &zOut[4];
59970 if( SQLITE_OK==(rc = sqlite3OsRead(pJrnl, zOut, len, szJ-16-len)) ){
59971 u32 u; /* Unsigned loop counter */
59972 /* See if the checksum matches the super-journal name */
59973 for(u=0; u<len; u++){
59974 cksum -= zOut[u];
59975 }
59976 }
59977 if( rc!=SQLITE_OK || cksum ){
59978 /* If the checksum doesn't add up, then one or more of the disk sectors
59979 ** containing the super-journal filename is corrupted. This means
59980 ** definitely roll back, so just return SQLITE_OK and report a (nul)
59981 ** super-journal filename. */
59982 freeSuperJournal(zOut);
59983 zOut = 0;
59984 }
59985 }
59986
59987 *pzSuper = zOut;
59988 return rc;
59989 }
59990
59991 /*
59992 ** Return the offset of the sector boundary at or immediately
59993 ** following the value in pPager->journalOff, assuming a sector
@@ -61106,13 +61188,11 @@
61188 sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */
61189 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
61190 char *zSuperJournal = 0; /* Contents of super-journal file */
61191 i64 nSuperJournal; /* Size of super-journal file */
61192 char *zJournal; /* Pointer to one journal within MJ file */
 
61193 char *zFree = 0; /* Free this buffer */
 
61194
61195 /* Allocate space for both the pJournal and pSuper file descriptors.
61196 ** If successful, open the super-journal file for reading.
61197 */
61198 pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
@@ -61131,22 +61211,20 @@
61211 ** sufficient space (in zSuperPtr) to hold the names of super-journal
61212 ** files extracted from regular rollback-journals.
61213 */
61214 rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
61215 if( rc!=SQLITE_OK ) goto delsuper_out;
61216 assert( nSuperJournal>=0 );
61217 zFree = sqlite3Malloc(4 + nSuperJournal + 2);
 
61218 if( !zFree ){
61219 rc = SQLITE_NOMEM_BKPT;
61220 goto delsuper_out;
61221 }else{
61222 assert( nSuperJournal<=0x7fffffff );
61223 }
61224 zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;
61225 zSuperJournal = &zFree[4];
 
61226 rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
61227 if( rc!=SQLITE_OK ) goto delsuper_out;
61228 zSuperJournal[nSuperJournal] = 0;
61229 zSuperJournal[nSuperJournal+1] = 0;
61230
@@ -61156,10 +61234,12 @@
61234 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
61235 if( rc!=SQLITE_OK ){
61236 goto delsuper_out;
61237 }
61238 if( exists ){
61239 char *zSuperPtr = 0;
61240
61241 /* One of the journals pointed to by the super-journal exists.
61242 ** Open it and check if it points at the super-journal. If
61243 ** so, return without deleting the super-journal file.
61244 ** NB: zJournal is really a MAIN_JOURNAL. But call it a
61245 ** SUPER_JOURNAL here so that the VFS will not send the zJournal
@@ -61170,17 +61250,19 @@
61250 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
61251 if( rc!=SQLITE_OK ){
61252 goto delsuper_out;
61253 }
61254
61255 rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr);
61256 sqlite3OsClose(pJournal);
61257 if( rc!=SQLITE_OK ){
61258 assert( zSuperPtr==0 );
61259 goto delsuper_out;
61260 }
61261
61262 c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0;
61263 freeSuperJournal(zSuperPtr);
61264 if( c ){
61265 /* We have a match. Do not delete the super-journal file. */
61266 goto delsuper_out;
61267 }
61268 }
@@ -61391,23 +61473,15 @@
61473
61474 /* Read the super-journal name from the journal, if it is present.
61475 ** If a super-journal file name is specified, but the file is not
61476 ** present on disk, then the journal is not hot and does not need to be
61477 ** played back.
61478 */
61479 rc = readSuperJournal(pPager->jfd, 1+(i64)pPager->pVfs->mxPathname, &zSuper);
61480 if( rc==SQLITE_OK && zSuper ){
 
 
 
 
 
 
 
61481 rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
61482 }
 
61483 if( rc!=SQLITE_OK || !res ){
61484 goto end_playback;
61485 }
61486 pPager->journalOff = 0;
61487 needPagerReset = isHot;
@@ -61532,34 +61606,24 @@
61606 ** problems for other processes at some point in the future. So, just
61607 ** in case this has happened, clear the changeCountDone flag now.
61608 */
61609 pPager->changeCountDone = pPager->tempFile;
61610
 
 
 
 
 
 
 
 
 
61611 if( rc==SQLITE_OK
61612 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
61613 ){
61614 rc = sqlite3PagerSync(pPager, 0);
61615 }
61616 if( rc==SQLITE_OK ){
61617 rc = pager_end_transaction(pPager, zSuper!=0, 0);
61618 testcase( rc!=SQLITE_OK );
61619 }
61620 if( rc==SQLITE_OK && zSuper && res ){
61621 /* If there was a super-journal and this routine will return success,
61622 ** see if it is possible to delete the super-journal.
61623 */
61624 assert( memcmp(&zSuper[-4], "\0\0\0\0", 4)==0 );
 
61625 rc = pager_delsuper(pPager, zSuper);
61626 testcase( rc!=SQLITE_OK );
61627 }
61628 if( isHot && nPlayback ){
61629 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
@@ -61568,10 +61632,11 @@
61632
61633 /* The Pager.sectorSize variable may have been updated while rolling
61634 ** back a journal created by a process with a different sector size
61635 ** value. Reset it to the correct value for this process.
61636 */
61637 freeSuperJournal(zSuper);
61638 setSectorSize(pPager);
61639 return rc;
61640 }
61641
61642
@@ -67426,10 +67491,16 @@
67491 */
67492 pgno = sqlite3Get4byte(&aFrame[0]);
67493 if( pgno==0 ){
67494 return 0;
67495 }
67496
67497 /* Need a valid page size
67498 */
67499 if( !pWal->szPage ){
67500 return 0;
67501 }
67502
67503 /* A frame is only valid if a checksum of the WAL header,
67504 ** all prior frames, the first 16 bytes of this frame-header,
67505 ** and the frame-data matches the checksum in the last 8
67506 ** bytes of this frame-header.
@@ -69281,11 +69352,11 @@
69352 goto begin_unreliable_shm_out;
69353 }
69354
69355 /* Allocate a buffer to read frames into */
69356 assert( (pWal->szPage & (pWal->szPage-1))==0 );
69357 assert( (pWal->szPage>=512 && pWal->szPage<=65536) || pWal->szPage==0 );
69358 szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
69359 aFrame = (u8 *)sqlite3_malloc64(szFrame);
69360 if( aFrame==0 ){
69361 rc = SQLITE_NOMEM_BKPT;
69362 goto begin_unreliable_shm_out;
@@ -83086,10 +83157,15 @@
83157 if( pc+info.nSize>usableSize ){
83158 checkAppendMsg(pCheck, "Extends off end of page");
83159 doCoverageCheck = 0;
83160 continue;
83161 }
83162 if( info.nPayload && info.pPayload[0]<2 ){
83163 checkAppendMsg(pCheck, "Bad cell header size");
83164 doCoverageCheck = 0;
83165 continue;
83166 }
83167
83168 /* Check for integer primary key out of range */
83169 if( pPage->intKey ){
83170 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
83171 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
@@ -84596,12 +84672,12 @@
84672 /* Work-around for GCC bug or bugs:
84673 ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270
84674 ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114659
84675 ** The problem appears to be fixed in GCC 15 */
84676 i64 x;
84677 assert( (sqlite3Config.bSmallMalloc!=0xee)*8==sizeof(x) );
84678 memcpy(&x, (char*)&p->u.i, (sqlite3Config.bSmallMalloc!=0xee)*8);
84679 p->n = sqlite3Int64ToText(x, zBuf);
84680 #else
84681 p->n = sqlite3Int64ToText(p->u.i, zBuf);
84682 #endif
84683 if( p->flags & MEM_IntReal ){
@@ -95448,11 +95524,11 @@
95524 QueryPerformanceCounter(&tm);
95525 return (sqlite3_uint64)tm.QuadPart;
95526 }
95527
95528 #elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && \
95529 (defined(i586) || defined(__i586__) || defined(_M_IX86))
95530
95531 __inline__ sqlite_uint64 sqlite3Hwtime(void){
95532 unsigned int lo, hi;
95533 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
95534 return (sqlite_uint64)hi << 32 | lo;
@@ -103037,11 +103113,11 @@
103113 if( pFrame ) break;
103114 }
103115
103116 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
103117 rc = SQLITE_ERROR;
103118 sqlite3VdbeError(p, "triggers nested too deep");
103119 goto abort_due_to_error;
103120 }
103121
103122 /* Register pRt is used to store the memory required to save the state
103123 ** of the current program, and the memory required at runtime to execute
@@ -110164,11 +110240,11 @@
110240 /*
110241 ** cnt==0 means there was not match.
110242 ** cnt>1 means there were two or more matches.
110243 **
110244 ** cnt==0 is always an error. cnt>1 is often an error, but might
110245 ** be multiple matches for a NATURAL OUTER JOIN or a OUTER JOIN USING.
110246 */
110247 assert( pFJMatch==0 || cnt>0 );
110248 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
110249 if( cnt!=1 ){
110250 const char *zErr;
@@ -110247,12 +110323,21 @@
110323 pExpr->op = eNewExprOp;
110324 lookupname_end:
110325 if( cnt==1 ){
110326 assert( pNC!=0 );
110327 #ifndef SQLITE_OMIT_AUTHORIZATION
110328 if( db->xAuth ){
110329 if( pFJMatch ){
110330 assert( pExpr->op==TK_FUNCTION );
110331 assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 );
110332 assert( pExpr->x.pList==pFJMatch );
110333 assert( pFJMatch->nExpr>0 );
110334 pExpr = pFJMatch->a[0].pExpr;
110335 }
110336 if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
110337 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
110338 }
110339 }
110340 #endif
110341 /* Increment the nRef value on all name contexts from TopNC up to
110342 ** the point where the name matched. */
110343 for(;;){
@@ -115930,10 +116015,11 @@
116015 if( i!=nVector ){
116016 /* Need to reorder the LHS fields according to aiMap */
116017 int rLhsOrig = rLhs;
116018 rLhs = sqlite3GetTempRange(pParse, nVector);
116019 for(i=0; i<nVector; i++){
116020 testcase( aiMap[i]!=i );
116021 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
116022 }
116023 sqlite3ReleaseTempReg(pParse, rLhsOrig);
116024 }
116025 }
@@ -115950,11 +116036,12 @@
116036 }
116037 for(i=0; i<nVector; i++){
116038 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
116039 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
116040 if( sqlite3ExprCanBeNull(p) ){
116041 testcase( aiMap[i]!=i );
116042 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+aiMap[i], destStep2);
116043 VdbeCoverage(v);
116044 }
116045 }
116046
116047 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
@@ -116024,13 +116111,23 @@
116111 for(i=0; i<nVector; i++){
116112 Expr *p;
116113 CollSeq *pColl;
116114 int r3 = sqlite3GetTempReg(pParse);
116115 p = sqlite3VectorFieldSubexpr(pLeft, i);
116116 if( ExprUseXSelect(pExpr) ){
116117 Expr *pRhs = pExpr->x.pSelect->pEList->a[i].pExpr;
116118 pColl = sqlite3BinaryCompareCollSeq(pParse, p, pRhs);
116119 }else{
116120 /* If the RHS of the IN(...) expression are scalar expressions, do
116121 ** not consider their collation sequences. The documentation says
116122 ** "The collating sequence used for expressions of the form "x IN (y, z,
116123 ** ...)" is the collating sequence of x.". */
116124 pColl = sqlite3ExprCollSeq(pParse, p);
116125 }
116126 testcase( aiMap[i]!=i );
116127 sqlite3VdbeAddOp3(v, OP_Column, iTab, aiMap[i], r3);
116128 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+aiMap[i], destNotNull, r3,
116129 (void*)pColl, P4_COLLSEQ);
116130 VdbeCoverage(v);
116131 sqlite3ReleaseTempReg(pParse, r3);
116132 }
116133 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
@@ -124365,21 +124462,21 @@
124462 }else{
124463 nIdxCol = pIdx->nColumn;
124464 }
124465 pIdx->nSampleCol = nIdxCol;
124466 pIdx->mxSample = nSample;
124467 nByte = ROUND8(sizeof64(IndexSample) * nSample);
124468 nByte += sizeof64(tRowcnt) * nIdxCol * 3 * nSample;
124469 nByte += nIdxCol * sizeof64(tRowcnt); /* Space for Index.aAvgEq[] */
124470
124471 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
124472 if( pIdx->aSample==0 ){
124473 sqlite3_finalize(pStmt);
124474 return SQLITE_NOMEM_BKPT;
124475 }
124476 pPtr = (u8*)pIdx->aSample;
124477 pPtr += ROUND8(nSample*sizeof64(pIdx->aSample[0]));
124478 pSpace = (tRowcnt*)pPtr;
124479 assert( EIGHT_BYTE_ALIGNMENT( pSpace ) );
124480 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
124481 pIdx->pTable->tabFlags |= TF_HasStat4;
124482 for(i=0; i<nSample; i++){
@@ -133231,13 +133328,22 @@
133328 x.nUsed = 0;
133329 x.apArg = argv+1;
133330 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
133331 str.printfFlags = SQLITE_PRINTF_SQLFUNC;
133332 sqlite3_str_appendf(&str, zFormat, &x);
133333 if( str.accError==SQLITE_OK ){
133334 n = str.nChar;
133335 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
133336 SQLITE_DYNAMIC);
133337 }else{
133338 if( str.accError==SQLITE_NOMEM ){
133339 sqlite3_result_error_nomem(context);
133340 }else{
133341 sqlite3_result_error_toobig(context);
133342 }
133343 sqlite3_str_reset(&str);
133344 }
133345 }
133346 }
133347
133348 /*
133349 ** Implementation of the substr() function.
@@ -134405,11 +134511,11 @@
134511 int nStr; /* Size of zStr */
134512 int nPattern; /* Size of zPattern */
134513 int nRep; /* Size of zRep */
134514 i64 nOut; /* Maximum size of zOut */
134515 int loopLimit; /* Last zStr[] that might match zPattern[] */
134516 i64 i, j; /* Loop counters */
134517 unsigned cntExpand; /* Number zOut expansions */
134518 sqlite3 *db = sqlite3_context_db_handle(context);
134519
134520 assert( argc==3 );
134521 UNUSED_PARAMETER(argc);
@@ -135859,57 +135965,95 @@
135965 ** from the standard library because:
135966 **
135967 ** (1) To avoid a dependency on qsort()
135968 ** (2) To avoid the function call to the comparison routine for each
135969 ** comparison.
135970 **
135971 ** If parameter iReq is non-negative, then the caller will only access
135972 ** elements a[iReq] and a[iReq+1] (if it exists) of the sorted array and
135973 ** so it is not necessary to position any other elements. Or if iReq is
135974 ** negative, then the final array must be fully sorted.
135975 */
135976 static void percentSort(
135977 double *a, /* Array to sort */
135978 unsigned int n, /* Number of elements in array a[] */
135979 int iReq /* Element caller cares about (or -ve) */
135980 ){
135981 int iLt; /* Entries before a[iLt] are less than rPivot */
135982 int iGt; /* Entries at or after a[iGt] are greater than rPivot */
135983 int i; /* Loop counter */
135984 double rPivot; /* The pivot value */
135985
135986 assert( n>=2 );
135987 do{
135988 if( a[0]>a[n-1] ){
135989 SWAP_DOUBLE(a[0],a[n-1])
135990 }
135991 if( n==2 ) return;
135992 iGt = n-1;
135993 i = n/2;
135994 if( a[0]>a[i] ){
135995 SWAP_DOUBLE(a[0],a[i])
135996 }else if( a[i]>a[iGt] ){
135997 SWAP_DOUBLE(a[i],a[iGt])
135998 }
135999 if( n==3 ) return;
136000 rPivot = a[i];
136001 iLt = i = 1;
136002 do{
136003 if( a[i]<rPivot ){
136004 if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
136005 iLt++;
136006 i++;
136007 }else if( a[i]>rPivot ){
136008 do{
136009 iGt--;
136010 }while( iGt>i && a[iGt]>rPivot );
136011 SWAP_DOUBLE(a[i],a[iGt])
136012 }else{
136013 i++;
136014 }
136015 }while( i<iGt );
136016
136017 assert( a[iLt]==rPivot );
136018 assert( iGt>iLt );
136019
136020 if( iReq>=0 ){
136021 /* In this case, the only elements that the caller requires sorted into
136022 ** the correct positions are elements a[iReq] and a[iReq+1]. At this
136023 ** point we know that element a[iLt] is in the correct position and
136024 ** all elements smaller than a[iLt] are in the left-hand partition.
136025 ** So if (iReq<iLt), then it is only necessary to sort the left
136026 ** partition.
136027 **
136028 ** If (iReq>=iLt), then elements iReq and iReq+1 are either in the
136029 ** right partition or the equal partition (elements for which
136030 ** iLt<=iElem<iGt). Therefore it is always sufficient to sort only
136031 ** the right partition in this case. */
136032 if( iReq<iLt ){
136033 n = iLt;
136034 }else{
136035 a += iGt;
136036 n -= iGt;
136037 iReq = MAX(0, iReq-iGt);
136038 }
136039 }else{
136040 /* Recurse on the smaller partition only. The smaller partition
136041 ** will hold n/2 or fewer entries, which assures that the stack
136042 ** depth will not exceed O(log(n)), even for pathological cases.
136043 ** Loop without recursion for the larger partition. */
136044 if( iLt>(int)(n/2) ){
136045 if( n-iGt>=2 ) percentSort(a+iGt, n-iGt, -1);
136046 n = iLt;
136047 }else{
136048 if( iLt>=2 ) percentSort(a, iLt, -1);
136049 a += iGt;
136050 n -= iGt;
136051 }
136052 }
136053 }while( n>=2 );
136054 }
136055
136056 /*
136057 ** The "inverse" function for percentile(Y,P) is called to remove a
136058 ** row that was previously inserted by "step".
136059 */
@@ -135939,11 +136083,11 @@
136083 if( percentIsInfinity(y) ){
136084 return;
136085 }
136086 if( p->bSorted==0 ){
136087 assert( p->nUsed>1 );
136088 percentSort(p->a, p->nUsed, -1);
136089 p->bSorted = 1;
136090 }
136091 p->bKeepSorted = 1;
136092
136093 /* Find and remove the row */
@@ -135968,17 +136112,21 @@
136112 double ix, vx;
136113 p = (Percentile*)sqlite3_aggregate_context(pCtx, 0);
136114 if( p==0 ) return;
136115 if( p->a==0 ) return;
136116 if( p->nUsed ){
136117 ix = p->rPct*(p->nUsed-1);
136118 i1 = (unsigned)ix;
136119 if( p->bSorted==0 ){
136120 /* In cases where bIsFinal is non-zero, setting Percentile.bSorted
136121 ** after the percentSort() call here is not technically correct, as
136122 ** the array is not fully sorted. But in this case the object will be
136123 ** freed below anyway, so it doesn't matter. */
136124 assert( p->nUsed>1 );
136125 percentSort(p->a, p->nUsed, (bIsFinal ? (int)i1 : -1));
136126 p->bSorted = 1;
136127 }
 
 
136128 if( settings & 1 ){
136129 vx = p->a[i1];
136130 }else{
136131 i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1;
136132 v1 = p->a[i1];
@@ -150488,10 +150636,17 @@
150636 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
150637 Table *pTab;
150638 sqlite3 *db = pParse->db;
150639 u64 savedFlags;
150640
150641 pParse->nNestSel++;
150642 #if SQLITE_MAX_EXPR_DEPTH>0
150643 if( pParse->nNestSel >= db->aLimit[SQLITE_LIMIT_EXPR_DEPTH] ){
150644 sqlite3ErrorMsg(pParse, "VIEWs and/or subqueries nested too deep");
150645 return 0;
150646 }
150647 #endif
150648 savedFlags = db->flags;
150649 db->flags &= ~(u64)SQLITE_FullColNames;
150650 db->flags |= SQLITE_ShortColNames;
150651 sqlite3SelectPrep(pParse, pSelect, 0);
150652 db->flags = savedFlags;
@@ -150509,10 +150664,12 @@
150664 pTab->iPKey = -1;
150665 if( db->mallocFailed ){
150666 sqlite3DeleteTable(db, pTab);
150667 return 0;
150668 }
150669 pParse->nNestSel--;
150670 assert( pParse->nNestSel>=0 );
150671 return pTab;
150672 }
150673
150674 /*
150675 ** Get a VDBE for the given parser context. Create a new one if necessary.
@@ -155479,12 +155636,15 @@
155636 ** Then, if CheckOnCtx.iJoin indicates that this expression is part of an
155637 ** ON clause from that SrcList (i.e. if iJoin is non-zero), check that it
155638 ** does not refer to a table to the right of CheckOnCtx.iJoin. */
155639 do {
155640 SrcList *pSrc = pCtx->pSrc;
155641 int nSrc = pSrc->nSrc;
155642 int iTab = pExpr->iTable;
155643 int ii;
155644 for(ii=0; ii<nSrc && pSrc->a[ii].iCursor!=iTab; ii++){}
155645 if( ii<nSrc ){
155646 if( pCtx->iJoin && iTab>pCtx->iJoin ){
155647 sqlite3ErrorMsg(pWalker->pParse,
155648 "%s references tables to its right",
155649 (pCtx->bFuncArg ? "table-function argument" : "ON clause")
155650 );
@@ -158449,22 +158609,36 @@
158609 Parse *pParse, /* Current parse context */
158610 Trigger *pTrigger, /* Trigger to code */
158611 Table *pTab, /* The table pTrigger is attached to */
158612 int orconf /* ON CONFLICT policy to code trigger program with */
158613 ){
158614 Parse *pTop; /* Top level Parse object */
158615 sqlite3 *db = pParse->db; /* Database handle */
158616 TriggerPrg *pPrg; /* Value to return */
158617 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
158618 Vdbe *v; /* Temporary VM */
158619 NameContext sNC; /* Name context for sub-vdbe */
158620 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
158621 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
158622 Parse sSubParse; /* Parse context for sub-vdbe */
158623 int nDepth; /* Trigger depth */
158624
158625 /* Ensure that triggers are not chained too deep. This test is linear
158626 ** in the chaining depth, but sensible code ought not be chaining
158627 ** triggers excessively, so that shouldn't be a problem.
158628 */
158629 pTop = pParse;
158630 for(nDepth=0; pTop->pOuterParse; pTop = pTop->pOuterParse, nDepth++){}
158631 if( nDepth>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
158632 sqlite3ErrorMsg(pParse, "triggers nested too deep");
158633 return 0;
158634 }
158635
158636 pTop = sqlite3ParseToplevel(pParse);
158637 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
158638 assert( pTop->pVdbe );
158639
158640
158641 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
158642 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
158643 ** list of the top-level Parse object sooner rather than later. */
158644 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
@@ -160462,11 +160636,12 @@
160636 ** So we have to make a copy before passing it down into sqlite3Update() */
160637 pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
160638 /* excluded.* columns of type REAL need to be converted to a hard real */
160639 for(i=0; i<pTab->nCol; i++){
160640 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
160641 int iStorage = pTop->regData + sqlite3TableColumnToStorage(pTab, i);
160642 sqlite3VdbeAddOp1(v, OP_RealAffinity, iStorage);
160643 }
160644 }
160645 sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
160646 sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
160647 VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
@@ -165680,10 +165855,11 @@
165855 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
165856 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
165857 WO_EQ|WO_IN|WO_IS, 0);
165858 if( pAlt==0 ) continue;
165859 if( pAlt->wtFlags & (TERM_CODED) ) continue;
165860 if( ExprHasProperty(pAlt->pExpr, EP_Collate) ) continue;
165861 if( (pAlt->eOperator & WO_IN)
165862 && ExprUseXSelect(pAlt->pExpr)
165863 && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
165864 ){
165865 continue;
@@ -166433,11 +166609,14 @@
166609 ** Mark term iChild as being a child of term iParent
166610 */
166611 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
166612 pWC->a[iChild].iParent = iParent;
166613 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
166614 assert( pWC->a[iParent].nChild < UMXV(pWC->a[0].nChild) );
166615 pWC->a[iParent].nChild++;
166616 testcase( pWC->a[iParent].nChild == UMXV(pWC->a[0].nChild) );
166617
166618 }
166619
166620 /*
166621 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
166622 ** a conjunction, then return just pTerm when N==0. If N is exceeds
@@ -166872,21 +167051,22 @@
167051 ** 1. The SQLITE_Transitive optimization must be enabled
167052 ** 2. Must be either an == or an IS operator
167053 ** 3. Not originating in the ON clause of an OUTER JOIN
167054 ** 4. The operator is not IS or else the query does not contain RIGHT JOIN
167055 ** 5. The affinities of A and B must be compatible
167056 ** 6. Both operands use the same collating sequence, and they must not
167057 ** use explicit COLLATE clauses.
167058 ** If this routine returns TRUE, that means that the RHS can be substituted
167059 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
167060 ** This is an optimization. No harm comes from returning 0. But if 1 is
167061 ** returned when it should not be, then incorrect answers might result.
167062 */
167063 static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){
167064 char aff1, aff2;
167065 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; /* (1) */
167066 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; /* (2) */
167067 if( ExprHasProperty(pExpr, EP_OuterON|EP_Collate) ) return 0; /* (3) */
167068 assert( pSrc!=0 );
167069 if( pExpr->op==TK_IS
167070 && pSrc->nSrc>=2
167071 && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0
167072 ){
@@ -167209,10 +167389,11 @@
167389 static const u8 ops[] = {TK_GE, TK_LE};
167390 assert( ExprUseXList(pExpr) );
167391 pList = pExpr->x.pList;
167392 assert( pList!=0 );
167393 assert( pList->nExpr==2 );
167394 assert( pWC->a[idxTerm].nChild==0 );
167395 for(i=0; i<2; i++){
167396 Expr *pNewExpr;
167397 int idxNew;
167398 pNewExpr = sqlite3PExpr(pParse, ops[i],
167399 sqlite3ExprDup(db, pExpr->pLeft, 0),
@@ -167419,12 +167600,15 @@
167600 && (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
167601 #ifndef SQLITE_OMIT_WINDOWFUNC
167602 && pExpr->x.pSelect->pWin==0
167603 #endif
167604 && pWC->op==TK_AND
167605 && pExpr->x.pSelect->pEList->nExpr <= UMXV(pTerm->nChild)
167606 /* ^-- See bug 2026-06-04T10:00:49Z */
167607 ){
167608 int i;
167609 assert( pTerm->nChild==0 );
167610 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
167611 int idxNew;
167612 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE);
167613 pWC->a[idxNew].u.x.iField = i+1;
167614 exprAnalyze(pSrc, pWC, idxNew);
@@ -186978,11 +187162,11 @@
187162 ** or disables the collection of memory allocation statistics. */
187163 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
187164 break;
187165 }
187166 case SQLITE_CONFIG_SMALL_MALLOC: {
187167 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int)!=0;
187168 break;
187169 }
187170 case SQLITE_CONFIG_PAGECACHE: {
187171 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
187172 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
@@ -193287,10 +193471,16 @@
193471 #ifndef SQLITE_CORE
193472 /* # include "sqlite3ext.h" */
193473 SQLITE_EXTENSION_INIT1
193474 #endif
193475
193476
193477 /*
193478 ** Assume any b-tree layer with more levels than this is corrupt.
193479 */
193480 #define FTS3_MAX_BTREE_HEIGHT 48
193481
193482 typedef struct Fts3HashWrapper Fts3HashWrapper;
193483 struct Fts3HashWrapper {
193484 Fts3Hash hash; /* Hash table */
193485 int nRef; /* Number of pointers to this object */
193486 };
@@ -195003,11 +195193,15 @@
195193 int iHeight; /* Height of this node in tree */
195194
195195 assert( piLeaf || piLeaf2 );
195196
195197 fts3GetVarint32(zNode, &iHeight);
195198 if( iHeight>FTS3_MAX_BTREE_HEIGHT ){
195199 rc = FTS_CORRUPT_VTAB;
195200 }else{
195201 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
195202 }
195203 assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
195204
195205 if( rc==SQLITE_OK && iHeight>1 ){
195206 char *zBlob = 0; /* Blob read from %_segments table */
195207 int nBlob = 0; /* Size of zBlob in bytes */
@@ -195048,12 +195242,17 @@
195242 char **pp, /* IN/OUT: Output pointer */
195243 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
195244 sqlite3_int64 iVal /* Write this value to the list */
195245 ){
195246 assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
195247 if( iVal-(*piPrev)>=0 ){
195248 /* Refuse to write a negative delta integer. This only happens with a
195249 ** corrupt db (see the assert above) and can cause buffer overwrites
195250 ** in some cases. */
195251 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
195252 *piPrev = iVal;
195253 }
195254 }
195255
195256 /*
195257 ** When this function is called, *ppPoslist is assumed to point to the
195258 ** start of a position-list. After it returns, *ppPoslist points to the
@@ -199532,11 +199731,11 @@
199731 break;
199732
199733 /* State 3. The integer just read is a column number. */
199734 default: assert( eState==3 );
199735 iCol = (int)v;
199736 if( iCol<1 || iCol>(pFts3->nColumn+1) ){
199737 rc = SQLITE_CORRUPT_VTAB;
199738 break;
199739 }
199740 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
199741 pCsr->aStat[iCol+1].nDoc++;
@@ -206469,10 +206668,14 @@
206668 iMul = -1;
206669 }
206670 for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
206671 iVal = iVal*10 + (zText[i] - '0');
206672 }
206673
206674 /* This if() clause is just to avoid an integer overflow. The record is
206675 ** corrupt in this case. */
206676 if( (i64)iVal==SMALLEST_INT64 ) iMul = 1;
206677 *pnByte = ((i64)iVal * (i64)iMul);
206678 }
206679 }
206680
206681
@@ -209331,14 +209534,13 @@
209534 */
209535
209536 /*
209537 ** Allocate a two-slot MatchinfoBuffer object.
209538 */
209539 static MatchinfoBuffer *fts3MIBufferNew(i64 nElem, const char *zMatchinfo){
209540 MatchinfoBuffer *pRet;
209541 sqlite3_int64 nByte = sizeof(u32) * (2*(i64)nElem+1) + SZ_MATCHINFOBUFFER(1);
 
209542 sqlite3_int64 nStr = strlen(zMatchinfo);
209543
209544 pRet = sqlite3Fts3MallocZero(nByte + nStr+1);
209545 if( pRet ){
209546 pRet->aMI[0] = (u8*)(&pRet->aMI[1]) - (u8*)pRet;
@@ -210205,12 +210407,12 @@
210407 }
210408 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
210409 return SQLITE_ERROR;
210410 }
210411
210412 static i64 fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
210413 i64 nVal; /* Number of integers output by cArg */
210414
210415 switch( cArg ){
210416 case FTS3_MATCHINFO_NDOC:
210417 case FTS3_MATCHINFO_NPHRASE:
210418 case FTS3_MATCHINFO_NCOL:
@@ -210222,20 +210424,20 @@
210424 case FTS3_MATCHINFO_LCS:
210425 nVal = pInfo->nCol;
210426 break;
210427
210428 case FTS3_MATCHINFO_LHITS:
210429 nVal = (i64)pInfo->nCol * pInfo->nPhrase;
210430 break;
210431
210432 case FTS3_MATCHINFO_LHITS_BM:
210433 nVal = (i64)pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
210434 break;
210435
210436 default:
210437 assert( cArg==FTS3_MATCHINFO_HITS );
210438 nVal = (i64)pInfo->nCol * pInfo->nPhrase * 3;
210439 break;
210440 }
210441
210442 return nVal;
210443 }
@@ -210513,11 +210715,11 @@
210715 }
210716 break;
210717
210718 case FTS3_MATCHINFO_LHITS_BM:
210719 case FTS3_MATCHINFO_LHITS: {
210720 i64 nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
210721 memset(pInfo->aMatchinfo, 0, nZero);
210722 rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
210723 break;
210724 }
210725
@@ -210582,11 +210784,11 @@
210784 ** matchinfo function has been called for this query. In this case
210785 ** allocate the array used to accumulate the matchinfo data and
210786 ** initialize those elements that are constant for every row.
210787 */
210788 if( pCsr->pMIBuffer==0 ){
210789 i64 nMatchinfo = 0; /* Number of u32 elements in match-info */
210790 int i; /* Used to iterate through zArg */
210791
210792 /* Determine the number of phrases in the query */
210793 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
210794 sInfo.nPhrase = pCsr->nPhrase;
@@ -218269,10 +218471,13 @@
218471 ** be because the shadow tables hold erroneous data. */
218472 if( rc==SQLITE_ERROR ){
218473 rc = SQLITE_CORRUPT_VTAB;
218474 RTREE_IS_CORRUPT(pRtree);
218475 }
218476 }else if( iNode<=0 ){
218477 RTREE_IS_CORRUPT(pRtree);
218478 rc = SQLITE_CORRUPT_VTAB;
218479 }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
218480 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
218481 if( !pNode ){
218482 rc = SQLITE_NOMEM;
218483 }else{
@@ -218910,11 +219115,11 @@
219115 i64 iRowid,
219116 int *piIndex
219117 ){
219118 int ii;
219119 int nCell = NCELL(pNode);
219120 assert( nCell<65536 && nCell>=0 );
219121 for(ii=0; ii<nCell; ii++){
219122 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
219123 *piIndex = ii;
219124 return SQLITE_OK;
219125 }
@@ -223953,10 +224158,13 @@
224158 if( c>=0xc0 ){ \
224159 c = icuUtf8Trans1[c-0xc0]; \
224160 while( (*zIn & 0xc0)==0x80 ){ \
224161 c = (c<<6) + (0x3f & *(zIn++)); \
224162 } \
224163 if( c<0x80 \
224164 || (c&0xFFFFF800)==0xD800 \
224165 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
224166 }
224167
224168 #define SQLITE_ICU_SKIP_UTF8(zIn) \
224169 assert( *zIn ); \
224170 if( *(zIn++)>=0xc0 ){ \
@@ -225858,20 +226066,30 @@
226066 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
226067 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
226068 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
226069 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
226070 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
226071
226072 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226073 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226074 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226075 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226076 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226077 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226078 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226079 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226080 };
226081 unsigned int v = 0;
226082 int c;
226083 unsigned char *z = (unsigned char*)*pz;
226084 unsigned char *zEnd = z + (*pLen);
226085 while( z<zEnd && (c = zValue[*z])>=0 ){
226086 v = (v<<6) + c;
226087 z++;
226088 }
226089
226090 *pLen -= (int)(z - (unsigned char*)*pz);
226091 *pz = (char*)z;
226092 return v;
226093 }
226094
226095 #if RBU_ENABLE_DELTA_CKSUM
@@ -225943,23 +226161,24 @@
226161 #if RBU_ENABLE_DELTA_CKSUM
226162 char *zOrigOut = zOut;
226163 #endif
226164
226165 limit = rbuDeltaGetInt(&zDelta, &lenDelta);
226166 if( lenDelta<=0 || *zDelta!='\n' ){
226167 /* ERROR: size integer not terminated by "\n" */
226168 return -1;
226169 }
226170 zDelta++; lenDelta--;
226171 while( *zDelta && lenDelta>0 ){
226172 unsigned int cnt, ofst;
226173 cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
226174 if( lenDelta<=0 ) return -1;
226175 switch( zDelta[0] ){
226176 case '@': {
226177 zDelta++; lenDelta--;
226178 ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
226179 if( lenDelta>0 || zDelta[0]!=',' ){
226180 /* ERROR: copy command not terminated by ',' */
226181 return -1;
226182 }
226183 zDelta++; lenDelta--;
226184 total += cnt;
@@ -225980,11 +226199,11 @@
226199 total += cnt;
226200 if( total>limit ){
226201 /* ERROR: insert command gives an output larger than predicted */
226202 return -1;
226203 }
226204 if( (i64)cnt>(i64)lenDelta ){
226205 /* ERROR: insert count exceeds size of delta */
226206 return -1;
226207 }
226208 memcpy(zOut, zDelta, cnt);
226209 zOut += cnt;
@@ -226018,11 +226237,11 @@
226237 }
226238
226239 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
226240 int size;
226241 size = rbuDeltaGetInt(&zDelta, &lenDelta);
226242 if( lenDelta<=0 || *zDelta!='\n' ){
226243 /* ERROR: size integer not terminated by "\n" */
226244 return -1;
226245 }
226246 return size;
226247 }
@@ -226066,11 +226285,11 @@
226285 if( nOut<0 ){
226286 sqlite3_result_error(context, "corrupt fossil delta", -1);
226287 return;
226288 }
226289
226290 aOut = sqlite3_malloc64((i64)nOut+1);
226291 if( aOut==0 ){
226292 sqlite3_result_error_nomem(context);
226293 }else{
226294 nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
226295 if( nOut2!=nOut ){
@@ -244051,11 +244270,11 @@
244270 ){
244271 HighlightContext ctx;
244272 int rc = SQLITE_OK; /* Return code */
244273 int iCol; /* 1st argument to snippet() */
244274 const char *zEllips; /* 4th argument to snippet() */
244275 i64 nToken; /* 5th argument to snippet() */
244276 int nInst = 0; /* Number of instance matches this row */
244277 int i; /* Used to iterate through instances */
244278 int nPhrase; /* Number of phrases in query */
244279 unsigned char *aSeen; /* Array of "seen instance" flags */
244280 int iBestCol; /* Column containing best snippet */
@@ -244076,11 +244295,11 @@
244295 iCol = sqlite3_value_int(apVal[0]);
244296 ctx.zOpen = fts5ValueToText(apVal[1]);
244297 ctx.zClose = fts5ValueToText(apVal[2]);
244298 ctx.iRangeEnd = -1;
244299 zEllips = fts5ValueToText(apVal[3]);
244300 nToken = (int)(MIN( MAX(sqlite3_value_int64(apVal[4]), 0), 64));
244301
244302 iBestCol = (iCol>=0 ? iCol : 0);
244303 nPhrase = pApi->xPhraseCount(pFts);
244304 aSeen = sqlite3_malloc64(nPhrase);
244305 if( aSeen==0 ){
@@ -246792,11 +247011,11 @@
247011 /* Add an entry to each output position list */
247012 for(i=0; i<pNear->nPhrase; i++){
247013 i64 iPos = a[i].reader.iPos;
247014 Fts5PoslistWriter *pWriter = &a[i].writer;
247015 if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
247016 sqlite3Fts5PoslistSafeAppend(a[i].pOut, &pWriter->iPrev, iPos);
247017 }
247018 }
247019
247020 iAdv = 0;
247021 iMin = a[0].reader.iLookahead;
@@ -247743,14 +247962,14 @@
247962 rc = SQLITE_NOMEM;
247963 }else{
247964 memset(pSyn, 0, (size_t)nByte);
247965 pSyn->pTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
247966 pSyn->nFullTerm = pSyn->nQueryTerm = nToken;
247967 memcpy(pSyn->pTerm, pToken, nToken);
247968 if( pCtx->pConfig->bTokendata ){
247969 pSyn->nQueryTerm = (int)strlen(pSyn->pTerm);
247970 }
 
247971 pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
247972 pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
247973 }
247974 }else{
247975 Fts5ExprTerm *pTerm;
@@ -249595,11 +249814,11 @@
249814 ** + 1 byte for a "new column" byte,
249815 ** + 3 bytes for a new column number (16-bit max) as a varint,
249816 ** + 5 bytes for the new position offset (32-bit max).
249817 */
249818 if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
249819 sqlite3_int64 nNew = (i64)p->nAlloc * 2;
249820 Fts5HashEntry *pNew;
249821 Fts5HashEntry **pp;
249822 pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
249823 if( pNew==0 ) return SQLITE_NOMEM;
249824 pNew->nAlloc = (int)nNew;
@@ -251029,11 +251248,11 @@
251248 }else{
251249 i += fts5GetVarint32(&pData[i], pLvl->nMerge);
251250 i += fts5GetVarint32(&pData[i], nTotal);
251251 if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
251252 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
251253 (i64)nTotal * sizeof(Fts5StructureSegment)
251254 );
251255 nSegment -= nTotal;
251256 }
251257
251258 if( rc==SQLITE_OK ){
@@ -251558,19 +251777,20 @@
251777 assert( pLvl->bEof==0 );
251778 if( iOff<=pLvl->iFirstOff ){
251779 pLvl->bEof = 1;
251780 }else{
251781 u8 *a = pLvl->pData->p;
251782 int nn = pLvl->pData->nn;
251783
251784 pLvl->iOff = 0;
251785 fts5DlidxLvlNext(pLvl);
251786 while( 1 ){
251787 int nZero = 0;
251788 int ii = pLvl->iOff;
251789 u64 delta = 0;
251790
251791 while( ii<nn && a[ii]==0 ){
251792 nZero++;
251793 ii++;
251794 }
251795 ii += sqlite3Fts5GetVarint(&a[ii], &delta);
251796
@@ -251985,11 +252205,11 @@
252205 fts5DataRelease(pIter->pLeaf);
252206 pIter->pLeaf = 0;
252207 while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
252208 Fts5Data *pNew;
252209 pIter->iLeafPgno--;
252210 pNew = fts5LeafRead(p, FTS5_SEGMENT_ROWID(
252211 pIter->pSeg->iSegid, pIter->iLeafPgno
252212 ));
252213 if( pNew ){
252214 /* iTermLeafOffset may be equal to szLeaf if the term is the last
252215 ** thing on the page - i.e. the first rowid is on the following page.
@@ -253419,12 +253639,11 @@
253639 }
253640 }
253641
253642 do {
253643 while( i<nChunk && pChunk[i]!=0x01 ){
253644 fts5IndexSkipVarint(pChunk, i);
 
253645 }
253646 if( pCtx->eState ){
253647 fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
253648 }
253649 if( i<nChunk ){
@@ -255163,10 +255382,15 @@
255382 int iSOP; /* Start-Of-Position-list */
255383 if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
255384 iStart = pSeg->iTermLeafOffset;
255385 }else{
255386 iStart = fts5GetU16(&aPg[0]);
255387 }
255388 if( iStart>nPg ){
255389 FTS5_CORRUPT_IDX(p);
255390 sqlite3_free(aIdx);
255391 return;
255392 }
255393
255394 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
255395 assert_nc( iSOP<=pSeg->iLeafOffset );
255396
@@ -257849,12 +258073,12 @@
258073 int *pnOut, /* OUT: Number of output pages */
258074 Fts5Data ***papOut /* OUT: Output hash pages */
258075 ){
258076 const int MINSLOT = 32;
258077 int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey);
258078 i64 nSlot = 0; /* Number of slots in each output page */
258079 i64 nOut = 0;
258080
258081 /* Figure out how many output pages (nOut) and how many slots per
258082 ** page (nSlot). There are three possibilities:
258083 **
258084 ** 1. The hash table does not yet exist. In this case the new hash
@@ -257875,27 +258099,30 @@
258099 /* Case 1. */
258100 nOut = 1;
258101 nSlot = MINSLOT;
258102 }else if( pSeg->nPgTombstone==1 ){
258103 /* Case 2. */
258104 u32 nElem = fts5GetU32(&pData1->p[4]);
258105 assert( pData1 && iPg1==0 );
258106 if( nElem>((u32)nSlotPerPage/4) ){
258107 nOut = 0;
258108 }else{
258109 nOut = 1;
258110 nSlot = MAX((i64)nElem*4, MINSLOT);
258111 }
258112 }
258113 if( nOut==0 ){
258114 /* Case 3. */
258115 nOut = ((i64)pSeg->nPgTombstone * 2 + 1);
258116 nSlot = nSlotPerPage;
258117 }
258118
258119 /* Allocate the required array and output pages */
258120 while( 1 ){
258121 int res = 0;
258122 i64 ii = 0;
258123 i64 szPage = 0;
258124 Fts5Data **apOut = 0;
258125
258126 /* Allocate space for the new hash table */
258127 assert( nSlot>=MINSLOT );
258128 apOut = (Fts5Data**)sqlite3Fts5MallocZero(&p->rc, sizeof(Fts5Data*) * nOut);
@@ -258429,11 +258656,11 @@
258656 ){
258657
258658 /* Check any rowid-less pages that occur before the current leaf. */
258659 for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
258660 iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
258661 pLeaf = fts5LeafRead(p, iKey);
258662 if( pLeaf ){
258663 if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
258664 fts5DataRelease(pLeaf);
258665 }
258666 }
@@ -258440,11 +258667,11 @@
258667 iPrevLeaf = fts5DlidxIterPgno(pDlidx);
258668
258669 /* Check that the leaf page indicated by the iterator really does
258670 ** contain the rowid suggested by the same. */
258671 iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
258672 pLeaf = fts5LeafRead(p, iKey);
258673 if( pLeaf ){
258674 i64 iRowid;
258675 int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
258676 ASSERT_SZLEAF_OK(pLeaf);
258677 if( iRowidOff>=pLeaf->szLeaf ){
@@ -263040,11 +263267,11 @@
263267 int nArg, /* Number of args */
263268 sqlite3_value **apUnused /* Function arguments */
263269 ){
263270 assert( nArg==0 );
263271 UNUSED_PARAM2(nArg, apUnused);
263272 sqlite3_result_text(pCtx, "fts5: 2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06", -1, SQLITE_TRANSIENT);
263273 }
263274
263275 /*
263276 ** Implementation of fts5_locale(LOCALE, TEXT) function.
263277 **
263278
+19 -6
--- extsrc/sqlite3.h
+++ extsrc/sqlite3.h
@@ -146,14 +146,14 @@
146146
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
147147
** [sqlite_version()] and [sqlite_source_id()].
148148
*/
149149
#define SQLITE_VERSION "3.54.0"
150150
#define SQLITE_VERSION_NUMBER 3054000
151
-#define SQLITE_SOURCE_ID "2026-05-30 13:23:25 2c605bfb1562d7a3609ad6ffd7446def12f1ac7084e41b9c6723e998c156501d"
151
+#define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
152152
#define SQLITE_SCM_BRANCH "trunk"
153153
#define SQLITE_SCM_TAGS ""
154
-#define SQLITE_SCM_DATETIME "2026-05-30T13:23:25.636Z"
154
+#define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
155155
156156
/*
157157
** CAPI3REF: Run-Time Library Version Numbers
158158
** KEYWORDS: sqlite3_version sqlite3_sourceid
159159
**
@@ -4375,11 +4375,12 @@
43754375
** <dd>The maximum number of columns in a table definition or in the
43764376
** result set of a [SELECT] or the maximum number of columns in an index
43774377
** or in an ORDER BY or GROUP BY clause.</dd>)^
43784378
**
43794379
** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4380
-** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4380
+** <dd>The maximum depth of the parse tree on any expression and
4381
+** the maximum nesting depth for subqueries and VIEWs</dd>)^
43814382
**
43824383
** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
43834384
** <dd>The maximum depth of the LALR(1) parser stack used to analyze
43844385
** input SQL statements.</dd>)^
43854386
**
@@ -4406,11 +4407,12 @@
44064407
** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
44074408
** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
44084409
** <dd>The maximum index number of any [parameter] in an SQL statement.)^
44094410
**
44104411
** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4411
-** <dd>The maximum depth of recursion for triggers.</dd>)^
4412
+** <dd>The maximum depth of recursion for triggers, and the maximum
4413
+** nesting depth for separate triggers.</dd>)^
44124414
**
44134415
** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
44144416
** <dd>The maximum number of auxiliary worker threads that a single
44154417
** [prepared statement] may start.</dd>)^
44164418
** </dl>
@@ -11212,12 +11214,23 @@
1121211214
** reopen S as an in-memory database based on the serialization
1121311215
** contained in P. If S is a NULL pointer, the main database is
1121411216
** used. The serialized database P is N bytes in size. M is the size
1121511217
** of the buffer P, which might be larger than N. If M is larger than
1121611218
** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then
11217
-** SQLite is permitted to add content to the in-memory database as
11218
-** long as the total size does not exceed M bytes.
11219
+** SQLite is permitted to add content to the in-memory database, in
11220
+** page-sized chunks, as long as the total size does not exceed M bytes.
11221
+**
11222
+** The parameter M must be greater than or equal to N. Ideally, M
11223
+** should have a value which is N+(512&times;K)+20 where K determines how
11224
+** must extra space is available to hold new content as the database
11225
+** grows. K can be 0 if the database is read-only.
11226
+**
11227
+** If the database content in P is malformed in a malicious way then
11228
+** it is possible that SQLite might try to read a few more than N bytes
11229
+** from P. If the veracity of the database content P is uncertain,
11230
+** then applications are advised to allocate about 20 extra bytes on
11231
+** the end of the P buffer to avoid a memory error.
1121911232
**
1122011233
** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
1122111234
** invoke sqlite3_free() on the serialization buffer when the database
1122211235
** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
1122311236
** SQLite will try to increase the buffer size using sqlite3_realloc64()
1122411237
--- extsrc/sqlite3.h
+++ extsrc/sqlite3.h
@@ -146,14 +146,14 @@
146 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
147 ** [sqlite_version()] and [sqlite_source_id()].
148 */
149 #define SQLITE_VERSION "3.54.0"
150 #define SQLITE_VERSION_NUMBER 3054000
151 #define SQLITE_SOURCE_ID "2026-05-30 13:23:25 2c605bfb1562d7a3609ad6ffd7446def12f1ac7084e41b9c6723e998c156501d"
152 #define SQLITE_SCM_BRANCH "trunk"
153 #define SQLITE_SCM_TAGS ""
154 #define SQLITE_SCM_DATETIME "2026-05-30T13:23:25.636Z"
155
156 /*
157 ** CAPI3REF: Run-Time Library Version Numbers
158 ** KEYWORDS: sqlite3_version sqlite3_sourceid
159 **
@@ -4375,11 +4375,12 @@
4375 ** <dd>The maximum number of columns in a table definition or in the
4376 ** result set of a [SELECT] or the maximum number of columns in an index
4377 ** or in an ORDER BY or GROUP BY clause.</dd>)^
4378 **
4379 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4380 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
 
4381 **
4382 ** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
4383 ** <dd>The maximum depth of the LALR(1) parser stack used to analyze
4384 ** input SQL statements.</dd>)^
4385 **
@@ -4406,11 +4407,12 @@
4406 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4407 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4408 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4409 **
4410 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4411 ** <dd>The maximum depth of recursion for triggers.</dd>)^
 
4412 **
4413 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4414 ** <dd>The maximum number of auxiliary worker threads that a single
4415 ** [prepared statement] may start.</dd>)^
4416 ** </dl>
@@ -11212,12 +11214,23 @@
11212 ** reopen S as an in-memory database based on the serialization
11213 ** contained in P. If S is a NULL pointer, the main database is
11214 ** used. The serialized database P is N bytes in size. M is the size
11215 ** of the buffer P, which might be larger than N. If M is larger than
11216 ** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then
11217 ** SQLite is permitted to add content to the in-memory database as
11218 ** long as the total size does not exceed M bytes.
 
 
 
 
 
 
 
 
 
 
 
11219 **
11220 ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
11221 ** invoke sqlite3_free() on the serialization buffer when the database
11222 ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
11223 ** SQLite will try to increase the buffer size using sqlite3_realloc64()
11224
--- extsrc/sqlite3.h
+++ extsrc/sqlite3.h
@@ -146,14 +146,14 @@
146 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
147 ** [sqlite_version()] and [sqlite_source_id()].
148 */
149 #define SQLITE_VERSION "3.54.0"
150 #define SQLITE_VERSION_NUMBER 3054000
151 #define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
152 #define SQLITE_SCM_BRANCH "trunk"
153 #define SQLITE_SCM_TAGS ""
154 #define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
155
156 /*
157 ** CAPI3REF: Run-Time Library Version Numbers
158 ** KEYWORDS: sqlite3_version sqlite3_sourceid
159 **
@@ -4375,11 +4375,12 @@
4375 ** <dd>The maximum number of columns in a table definition or in the
4376 ** result set of a [SELECT] or the maximum number of columns in an index
4377 ** or in an ORDER BY or GROUP BY clause.</dd>)^
4378 **
4379 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4380 ** <dd>The maximum depth of the parse tree on any expression and
4381 ** the maximum nesting depth for subqueries and VIEWs</dd>)^
4382 **
4383 ** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
4384 ** <dd>The maximum depth of the LALR(1) parser stack used to analyze
4385 ** input SQL statements.</dd>)^
4386 **
@@ -4406,11 +4407,12 @@
4407 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4408 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4409 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4410 **
4411 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4412 ** <dd>The maximum depth of recursion for triggers, and the maximum
4413 ** nesting depth for separate triggers.</dd>)^
4414 **
4415 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4416 ** <dd>The maximum number of auxiliary worker threads that a single
4417 ** [prepared statement] may start.</dd>)^
4418 ** </dl>
@@ -11212,12 +11214,23 @@
11214 ** reopen S as an in-memory database based on the serialization
11215 ** contained in P. If S is a NULL pointer, the main database is
11216 ** used. The serialized database P is N bytes in size. M is the size
11217 ** of the buffer P, which might be larger than N. If M is larger than
11218 ** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then
11219 ** SQLite is permitted to add content to the in-memory database, in
11220 ** page-sized chunks, as long as the total size does not exceed M bytes.
11221 **
11222 ** The parameter M must be greater than or equal to N. Ideally, M
11223 ** should have a value which is N+(512&times;K)+20 where K determines how
11224 ** must extra space is available to hold new content as the database
11225 ** grows. K can be 0 if the database is read-only.
11226 **
11227 ** If the database content in P is malformed in a malicious way then
11228 ** it is possible that SQLite might try to read a few more than N bytes
11229 ** from P. If the veracity of the database content P is uncertain,
11230 ** then applications are advised to allocate about 20 extra bytes on
11231 ** the end of the P buffer to avoid a memory error.
11232 **
11233 ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
11234 ** invoke sqlite3_free() on the serialization buffer when the database
11235 ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
11236 ** SQLite will try to increase the buffer size using sqlite3_realloc64()
11237
--- skins/ardoise/css.txt
+++ skins/ardoise/css.txt
@@ -154,24 +154,19 @@
154154
button,
155155
select {
156156
text-transform: none
157157
}
158158
button,
159
-html input[type=button],
159
+input[type=button],
160160
input[type=reset],
161
-input[type=submit] {
161
+input[type=submit]{
162162
cursor: pointer
163163
}
164
-button[disabled],
165
-html input[disabled] {
164
+button:disabled,
165
+input:disabled {
166166
cursor: default
167167
}
168
-button::-moz-focus-inner,
169
-input::-moz-focus-inner {
170
- border: 0;
171
- padding: 0
172
-}
173168
input {
174169
line-height: normal
175170
}
176171
input[type=checkbox],
177172
input[type=radio] {
@@ -307,11 +302,11 @@
307302
text-decoration: none;
308303
text-align: center;
309304
white-space: nowrap;
310305
cursor: pointer
311306
}
312
-input[type=submit]:disabled {
307
+input:disabled {
313308
color: rgb(70,70,70);
314309
background-color: rgb(153,153,153);
315310
}
316311
317312
@media (min-width:550px) {
@@ -416,30 +411,20 @@
416411
.offset-by-eleven.columns {
417412
margin-left: 95.33333%
418413
}
419414
}
420415
.button,
421
-button {
422
- color: #aaa;
423
- background-color: #444;
424
- border-radius: 5px;
425
- border: 0
426
-}
416
+button,
427417
input[type=button],
428418
input[type=reset],
429419
input[type=submit] {
430420
color: #ddd;
431421
background-color: #446979;
432422
border: 0;
433423
border-radius: 5px
434424
}
435
-.button:hover,
436
-button:hover {
437
- color: #444;
438
- background-color: #aaa;
439
- outline: 0
440
-}
425
+button:hover,
441426
input[type=button]:hover,
442427
input[type=reset]:hover,
443428
input[type=submit]:hover {
444429
color: #446979;
445430
background-color: #ddd;
@@ -452,29 +437,20 @@
452437
input[type=submit]:focus {
453438
color: #333;
454439
border-color: #888;
455440
outline: 0
456441
}
457
-.button.button-primary,
458
-.button.button-primary:focus,
459
-.button.button-primary:hover,
460
-button.button-primary,
461
-button.button-primary:focus,
462
-button.button-primary:hover,
463
-input[type=button].button-primary,
464
-input[type=button].button-primary:focus,
465
-input[type=button].button-primary:hover,
466
-input[type=reset].button-primary,
467
-input[type=reset].button-primary:focus,
468
-input[type=reset].button-primary:hover,
469
-input[type=submit].button-primary,
470
-input[type=submit].button-primary:focus,
471
-input[type=submit].button-primary:hover {
472
- color: #303536;
473
- background-color: #ff8000;
474
- border-color: #ff8000
475
-}
442
+
443
+button:disabled,
444
+input[type=button]:disabled,
445
+input[type=reset]:disabled,
446
+input[type=submit]:disabled{
447
+ color: #ddd;
448
+ background-color: #7f7f7f;
449
+ opacity: 0.8;
450
+}
451
+
476452
input[type=email],
477453
input[type=number],
478454
input[type=password],
479455
input[type=search],
480456
input[type=tel],
481457
--- skins/ardoise/css.txt
+++ skins/ardoise/css.txt
@@ -154,24 +154,19 @@
154 button,
155 select {
156 text-transform: none
157 }
158 button,
159 html input[type=button],
160 input[type=reset],
161 input[type=submit] {
162 cursor: pointer
163 }
164 button[disabled],
165 html input[disabled] {
166 cursor: default
167 }
168 button::-moz-focus-inner,
169 input::-moz-focus-inner {
170 border: 0;
171 padding: 0
172 }
173 input {
174 line-height: normal
175 }
176 input[type=checkbox],
177 input[type=radio] {
@@ -307,11 +302,11 @@
307 text-decoration: none;
308 text-align: center;
309 white-space: nowrap;
310 cursor: pointer
311 }
312 input[type=submit]:disabled {
313 color: rgb(70,70,70);
314 background-color: rgb(153,153,153);
315 }
316
317 @media (min-width:550px) {
@@ -416,30 +411,20 @@
416 .offset-by-eleven.columns {
417 margin-left: 95.33333%
418 }
419 }
420 .button,
421 button {
422 color: #aaa;
423 background-color: #444;
424 border-radius: 5px;
425 border: 0
426 }
427 input[type=button],
428 input[type=reset],
429 input[type=submit] {
430 color: #ddd;
431 background-color: #446979;
432 border: 0;
433 border-radius: 5px
434 }
435 .button:hover,
436 button:hover {
437 color: #444;
438 background-color: #aaa;
439 outline: 0
440 }
441 input[type=button]:hover,
442 input[type=reset]:hover,
443 input[type=submit]:hover {
444 color: #446979;
445 background-color: #ddd;
@@ -452,29 +437,20 @@
452 input[type=submit]:focus {
453 color: #333;
454 border-color: #888;
455 outline: 0
456 }
457 .button.button-primary,
458 .button.button-primary:focus,
459 .button.button-primary:hover,
460 button.button-primary,
461 button.button-primary:focus,
462 button.button-primary:hover,
463 input[type=button].button-primary,
464 input[type=button].button-primary:focus,
465 input[type=button].button-primary:hover,
466 input[type=reset].button-primary,
467 input[type=reset].button-primary:focus,
468 input[type=reset].button-primary:hover,
469 input[type=submit].button-primary,
470 input[type=submit].button-primary:focus,
471 input[type=submit].button-primary:hover {
472 color: #303536;
473 background-color: #ff8000;
474 border-color: #ff8000
475 }
476 input[type=email],
477 input[type=number],
478 input[type=password],
479 input[type=search],
480 input[type=tel],
481
--- skins/ardoise/css.txt
+++ skins/ardoise/css.txt
@@ -154,24 +154,19 @@
154 button,
155 select {
156 text-transform: none
157 }
158 button,
159 input[type=button],
160 input[type=reset],
161 input[type=submit]{
162 cursor: pointer
163 }
164 button:disabled,
165 input:disabled {
166 cursor: default
167 }
 
 
 
 
 
168 input {
169 line-height: normal
170 }
171 input[type=checkbox],
172 input[type=radio] {
@@ -307,11 +302,11 @@
302 text-decoration: none;
303 text-align: center;
304 white-space: nowrap;
305 cursor: pointer
306 }
307 input:disabled {
308 color: rgb(70,70,70);
309 background-color: rgb(153,153,153);
310 }
311
312 @media (min-width:550px) {
@@ -416,30 +411,20 @@
411 .offset-by-eleven.columns {
412 margin-left: 95.33333%
413 }
414 }
415 .button,
416 button,
 
 
 
 
 
417 input[type=button],
418 input[type=reset],
419 input[type=submit] {
420 color: #ddd;
421 background-color: #446979;
422 border: 0;
423 border-radius: 5px
424 }
425 button:hover,
 
 
 
 
 
426 input[type=button]:hover,
427 input[type=reset]:hover,
428 input[type=submit]:hover {
429 color: #446979;
430 background-color: #ddd;
@@ -452,29 +437,20 @@
437 input[type=submit]:focus {
438 color: #333;
439 border-color: #888;
440 outline: 0
441 }
442
443 button:disabled,
444 input[type=button]:disabled,
445 input[type=reset]:disabled,
446 input[type=submit]:disabled{
447 color: #ddd;
448 background-color: #7f7f7f;
449 opacity: 0.8;
450 }
451
 
 
 
 
 
 
 
 
 
452 input[type=email],
453 input[type=number],
454 input[type=password],
455 input[type=search],
456 input[type=tel],
457
--- skins/blitz/css.txt
+++ skins/blitz/css.txt
@@ -1,17 +1,9 @@
11
/*! normalize.css v3.0.2 | MIT License | git.io/normalize */
22
3
-/**
4
- * 1. Set default font family to sans-serif.
5
- * 2. Prevent iOS text size adjust after orientation change, without disabling
6
- * user zoom.
7
- */
8
-
93
html {
104
font-family: sans-serif; /* 1 */
11
- -ms-text-size-adjust: 100%; /* 2 */
12
- -webkit-text-size-adjust: 100%; /* 2 */
135
}
146
157
/**
168
* Remove default margin.
179
*/
@@ -207,11 +199,10 @@
207199
/**
208200
* Address differences between Firefox and other browsers.
209201
*/
210202
211203
hr {
212
- -moz-box-sizing: content-box;
213204
box-sizing: content-box;
214205
height: 0;
215206
}
216207
217208
/**
@@ -277,47 +268,27 @@
277268
button,
278269
select {
279270
text-transform: none;
280271
}
281272
282
-/**
283
- * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
284
- * and `video` controls.
285
- * 2. Correct inability to style clickable `input` types in iOS.
286
- * 3. Improve usability and consistency of cursor style between image-type
287
- * `input` and others.
288
- */
289
-
290273
button,
291
-html input[type="button"], /* 1 */
292
-input[type="reset"],
293
-input[type="submit"],
294
-input[type="button"].submit,
295
-button.submit{
296
- -webkit-appearance: button; /* 2 */
297
- cursor: pointer; /* 3 */
274
+input[type=button],
275
+input[type=reset],
276
+input[type=submit]{
277
+ cursor: pointer;
298278
}
299279
300280
/**
301281
* Re-set default cursor for disabled elements.
302282
*/
303
-
304
-button[disabled],
305
-html input[disabled] {
283
+button:disabled,
284
+input[type=button]:disabled,
285
+input[type=reset]:disabled,
286
+input[type=submit]:disabled{
306287
cursor: default;
307288
}
308289
309
-/**
310
- * Remove inner padding and border in Firefox 4+.
311
- */
312
-
313
-button::-moz-focus-inner,
314
-input::-moz-focus-inner {
315
- border: 0;
316
- padding: 0;
317
-}
318
-
319290
/**
320291
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
321292
* the UA stylesheet.
322293
*/
323294
@@ -348,20 +319,11 @@
348319
input[type="number"]::-webkit-inner-spin-button,
349320
input[type="number"]::-webkit-outer-spin-button {
350321
height: auto;
351322
}
352323
353
-/**
354
- * 1. Address `appearance` set to `searchfield` in Safari and Chrome.
355
- * 2. Address `box-sizing` set to `border-box` in Safari and Chrome
356
- * (include `-moz` to future-proof).
357
- */
358
-
359324
input[type="search"] {
360
- -webkit-appearance: textfield; /* 1 */
361
- -moz-box-sizing: content-box;
362
- -webkit-box-sizing: content-box; /* 2 */
363325
box-sizing: content-box;
364326
}
365327
366328
/**
367329
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
@@ -517,73 +479,65 @@
517479
518480
/* Buttons
519481
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
520482
.button,
521483
button,
522
-input[type="button"],
523
-input[type="reset"],
524
-input[type="submit"],
525
-input[type="button"].submit,
526
-button.submit{
484
+input[type=button],
485
+input[type=reset],
486
+input[type=submit]{
527487
display: inline-block;
528488
height: 3.3rem;
529489
padding: 0 2.2rem;
530
- color: #555 !important;
490
+ color: #444;
491
+ background-color: #f8f8f8;;
492
+ border-color: #446979;
531493
text-align: center;
532494
font-size: 1.1rem;
533495
font-weight: 700;
534496
line-height: 3.3rem;
535497
letter-spacing: .08rem;
536498
text-transform: uppercase;
537499
text-decoration: none;
538500
white-space: nowrap;
539
- background-color: transparent;
540501
border-radius: 4px;
541
- border: 1px solid #ccc;
502
+ /*border: 1px solid #ccc;*/
503
+ border: 1px solid #446979;
542504
cursor: pointer;
543505
box-sizing: border-box;
544506
}
545507
546508
.button:hover,
547509
button:hover,
548
-input[type="button"]:hover,
549
-input[type="reset"]:hover,
550
-.button:focus,
510
+input[type=button]:hover,
511
+input[type=reset]:hover,
512
+input[type=submit]:hover,
513
+.button:hover,
551514
button:focus,
552
-input[type="button"]:focus,
553
-input[type="reset"]:focus {
554
- color: #444 !important;
555
- background-color: #eee;
556
- border-color: #aaa;
515
+input[type=button]:focus,
516
+input[type=reset]:focus,
517
+input[type=submit]:focus{
557518
outline: 0;
558
-}
559
-
560
-input[type="submit"],
561
-input[type="button"].submit,
562
-button.submit{
563
- color: white !important;
564
- background-color: #446979;
565
- border-color: #446979;
566
-}
567
-
568
-input[type="submit"]:hover,
569
-input[type="submit"]:focus,
570
-input[type="button"].submit:hover,
571
-input[type="button"].submit:focus,
572
-button.submit:hover,
573
-button.submit:focus{
574
- color: white !important;
519
+ color: white;
575520
background-color: #648898;
576521
border-color: #648898;
577522
}
578523
579
-input[type="submit"]:disabled,
580
-input[type="button"].submit:disabled,
581
-button.submit:disabled{
582
- color: rgb(128,128,128);
524
+.button:disabled,
525
+button:disabled,
526
+input[type=button]:disabled,
527
+input[type=reset]:disabled,
528
+input[type=submit]:disabled{
529
+ color: #444;
583530
background-color: rgb(153,153,153);
584531
}
532
+
533
+.content a.button,
534
+.submenu a.button,
535
+.submenu a.button:visited {
536
+ color: #444;
537
+ background: #f8f8f8;
538
+}
585539
586540
587541
/* Forms
588542
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
589543
input[type="email"],
@@ -611,12 +565,10 @@
611565
input[type="text"],
612566
input[type="tel"],
613567
input[type="url"],
614568
input[type="password"],
615569
textarea {
616
- -webkit-appearance: none;
617
- -moz-appearance: none;
618570
appearance: none;
619571
}
620572
621573
textarea {
622574
height: inherit;
@@ -1293,5 +1245,11 @@
12931245
}
12941246
12951247
body.forum .forumPosts.fileage a:visited {
12961248
color: #648999;
12971249
}
1250
+
1251
+/* Chat
1252
+––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
1253
+body.chat .chat-input-field:focus {
1254
+ border-color: #446979;
1255
+}
12981256
--- skins/blitz/css.txt
+++ skins/blitz/css.txt
@@ -1,17 +1,9 @@
1 /*! normalize.css v3.0.2 | MIT License | git.io/normalize */
2
3 /**
4 * 1. Set default font family to sans-serif.
5 * 2. Prevent iOS text size adjust after orientation change, without disabling
6 * user zoom.
7 */
8
9 html {
10 font-family: sans-serif; /* 1 */
11 -ms-text-size-adjust: 100%; /* 2 */
12 -webkit-text-size-adjust: 100%; /* 2 */
13 }
14
15 /**
16 * Remove default margin.
17 */
@@ -207,11 +199,10 @@
207 /**
208 * Address differences between Firefox and other browsers.
209 */
210
211 hr {
212 -moz-box-sizing: content-box;
213 box-sizing: content-box;
214 height: 0;
215 }
216
217 /**
@@ -277,47 +268,27 @@
277 button,
278 select {
279 text-transform: none;
280 }
281
282 /**
283 * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
284 * and `video` controls.
285 * 2. Correct inability to style clickable `input` types in iOS.
286 * 3. Improve usability and consistency of cursor style between image-type
287 * `input` and others.
288 */
289
290 button,
291 html input[type="button"], /* 1 */
292 input[type="reset"],
293 input[type="submit"],
294 input[type="button"].submit,
295 button.submit{
296 -webkit-appearance: button; /* 2 */
297 cursor: pointer; /* 3 */
298 }
299
300 /**
301 * Re-set default cursor for disabled elements.
302 */
303
304 button[disabled],
305 html input[disabled] {
 
306 cursor: default;
307 }
308
309 /**
310 * Remove inner padding and border in Firefox 4+.
311 */
312
313 button::-moz-focus-inner,
314 input::-moz-focus-inner {
315 border: 0;
316 padding: 0;
317 }
318
319 /**
320 * Address Firefox 4+ setting `line-height` on `input` using `!important` in
321 * the UA stylesheet.
322 */
323
@@ -348,20 +319,11 @@
348 input[type="number"]::-webkit-inner-spin-button,
349 input[type="number"]::-webkit-outer-spin-button {
350 height: auto;
351 }
352
353 /**
354 * 1. Address `appearance` set to `searchfield` in Safari and Chrome.
355 * 2. Address `box-sizing` set to `border-box` in Safari and Chrome
356 * (include `-moz` to future-proof).
357 */
358
359 input[type="search"] {
360 -webkit-appearance: textfield; /* 1 */
361 -moz-box-sizing: content-box;
362 -webkit-box-sizing: content-box; /* 2 */
363 box-sizing: content-box;
364 }
365
366 /**
367 * Remove inner padding and search cancel button in Safari and Chrome on OS X.
@@ -517,73 +479,65 @@
517
518 /* Buttons
519 ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
520 .button,
521 button,
522 input[type="button"],
523 input[type="reset"],
524 input[type="submit"],
525 input[type="button"].submit,
526 button.submit{
527 display: inline-block;
528 height: 3.3rem;
529 padding: 0 2.2rem;
530 color: #555 !important;
 
 
531 text-align: center;
532 font-size: 1.1rem;
533 font-weight: 700;
534 line-height: 3.3rem;
535 letter-spacing: .08rem;
536 text-transform: uppercase;
537 text-decoration: none;
538 white-space: nowrap;
539 background-color: transparent;
540 border-radius: 4px;
541 border: 1px solid #ccc;
 
542 cursor: pointer;
543 box-sizing: border-box;
544 }
545
546 .button:hover,
547 button:hover,
548 input[type="button"]:hover,
549 input[type="reset"]:hover,
550 .button:focus,
 
551 button:focus,
552 input[type="button"]:focus,
553 input[type="reset"]:focus {
554 color: #444 !important;
555 background-color: #eee;
556 border-color: #aaa;
557 outline: 0;
558 }
559
560 input[type="submit"],
561 input[type="button"].submit,
562 button.submit{
563 color: white !important;
564 background-color: #446979;
565 border-color: #446979;
566 }
567
568 input[type="submit"]:hover,
569 input[type="submit"]:focus,
570 input[type="button"].submit:hover,
571 input[type="button"].submit:focus,
572 button.submit:hover,
573 button.submit:focus{
574 color: white !important;
575 background-color: #648898;
576 border-color: #648898;
577 }
578
579 input[type="submit"]:disabled,
580 input[type="button"].submit:disabled,
581 button.submit:disabled{
582 color: rgb(128,128,128);
 
 
583 background-color: rgb(153,153,153);
584 }
 
 
 
 
 
 
 
585
586
587 /* Forms
588 ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
589 input[type="email"],
@@ -611,12 +565,10 @@
611 input[type="text"],
612 input[type="tel"],
613 input[type="url"],
614 input[type="password"],
615 textarea {
616 -webkit-appearance: none;
617 -moz-appearance: none;
618 appearance: none;
619 }
620
621 textarea {
622 height: inherit;
@@ -1293,5 +1245,11 @@
1293 }
1294
1295 body.forum .forumPosts.fileage a:visited {
1296 color: #648999;
1297 }
 
 
 
 
 
 
1298
--- skins/blitz/css.txt
+++ skins/blitz/css.txt
@@ -1,17 +1,9 @@
1 /*! normalize.css v3.0.2 | MIT License | git.io/normalize */
2
 
 
 
 
 
 
3 html {
4 font-family: sans-serif; /* 1 */
 
 
5 }
6
7 /**
8 * Remove default margin.
9 */
@@ -207,11 +199,10 @@
199 /**
200 * Address differences between Firefox and other browsers.
201 */
202
203 hr {
 
204 box-sizing: content-box;
205 height: 0;
206 }
207
208 /**
@@ -277,47 +268,27 @@
268 button,
269 select {
270 text-transform: none;
271 }
272
 
 
 
 
 
 
 
 
273 button,
274 input[type=button],
275 input[type=reset],
276 input[type=submit]{
277 cursor: pointer;
 
 
 
278 }
279
280 /**
281 * Re-set default cursor for disabled elements.
282 */
283 button:disabled,
284 input[type=button]:disabled,
285 input[type=reset]:disabled,
286 input[type=submit]:disabled{
287 cursor: default;
288 }
289
 
 
 
 
 
 
 
 
 
 
290 /**
291 * Address Firefox 4+ setting `line-height` on `input` using `!important` in
292 * the UA stylesheet.
293 */
294
@@ -348,20 +319,11 @@
319 input[type="number"]::-webkit-inner-spin-button,
320 input[type="number"]::-webkit-outer-spin-button {
321 height: auto;
322 }
323
 
 
 
 
 
 
324 input[type="search"] {
 
 
 
325 box-sizing: content-box;
326 }
327
328 /**
329 * Remove inner padding and search cancel button in Safari and Chrome on OS X.
@@ -517,73 +479,65 @@
479
480 /* Buttons
481 ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
482 .button,
483 button,
484 input[type=button],
485 input[type=reset],
486 input[type=submit]{
 
 
487 display: inline-block;
488 height: 3.3rem;
489 padding: 0 2.2rem;
490 color: #444;
491 background-color: #f8f8f8;;
492 border-color: #446979;
493 text-align: center;
494 font-size: 1.1rem;
495 font-weight: 700;
496 line-height: 3.3rem;
497 letter-spacing: .08rem;
498 text-transform: uppercase;
499 text-decoration: none;
500 white-space: nowrap;
 
501 border-radius: 4px;
502 /*border: 1px solid #ccc;*/
503 border: 1px solid #446979;
504 cursor: pointer;
505 box-sizing: border-box;
506 }
507
508 .button:hover,
509 button:hover,
510 input[type=button]:hover,
511 input[type=reset]:hover,
512 input[type=submit]:hover,
513 .button:hover,
514 button:focus,
515 input[type=button]:focus,
516 input[type=reset]:focus,
517 input[type=submit]:focus{
 
 
518 outline: 0;
519 color: white;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520 background-color: #648898;
521 border-color: #648898;
522 }
523
524 .button:disabled,
525 button:disabled,
526 input[type=button]:disabled,
527 input[type=reset]:disabled,
528 input[type=submit]:disabled{
529 color: #444;
530 background-color: rgb(153,153,153);
531 }
532
533 .content a.button,
534 .submenu a.button,
535 .submenu a.button:visited {
536 color: #444;
537 background: #f8f8f8;
538 }
539
540
541 /* Forms
542 ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
543 input[type="email"],
@@ -611,12 +565,10 @@
565 input[type="text"],
566 input[type="tel"],
567 input[type="url"],
568 input[type="password"],
569 textarea {
 
 
570 appearance: none;
571 }
572
573 textarea {
574 height: inherit;
@@ -1293,5 +1245,11 @@
1245 }
1246
1247 body.forum .forumPosts.fileage a:visited {
1248 color: #648999;
1249 }
1250
1251 /* Chat
1252 ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– */
1253 body.chat .chat-input-field:focus {
1254 border-color: #446979;
1255 }
1256
--- skins/darkmode/css.txt
+++ skins/darkmode/css.txt
@@ -98,50 +98,56 @@
9898
}
9999
.fileage tr:hover,
100100
div.filetreeline:hover {
101101
background-color: #333;
102102
}
103
-div.file-change-line button {
103
+div.file-change-line button{
104104
background-color: #484848
105105
}
106
+button,
107
+input,
108
+optgroup,
109
+select,
110
+textarea {
111
+ background: inherit;
112
+ color: inherit;
113
+ font: inherit;
114
+ margin: 0
115
+}
106116
.button,
107
-button {
108
- color: #aaa;
109
- background-color: #484848;
110
- border-radius: 5px;
111
- border: 0
112
-}
113
-.button:hover,
114
-button:hover {
115
- background-color: #FF4500f0;
116
- color: rgba(24,24,24,0.8);
117
- outline: 0
118
-}
117
+button,
119118
input[type=button],
120
-input[type=reset],
121
-input[type=submit] {
119
+input[type=submit],
120
+input[type=reset]{
122121
color: #ddd;
123122
background-color: #446979;
123
+ border-radius: 5px;
124124
border: 0;
125
- border-radius: 5px
126125
}
126
+.button:hover,
127
+button:hover,
127128
input[type=button]:hover,
128
-input[type=reset]:hover,
129
-input[type=submit]:hover {
129
+input[type=submit]:hover,
130
+input[type=reset]:hover {
130131
background-color: #FF4500f0;
131132
color: rgba(24,24,24,0.8);
132
- outline: 0
133
+ outline: 0;
133134
}
134
-input[type=submit]:disabled {
135
- color: #363636;
136
- background-color: #707070;
135
+.button:disabled,
136
+button:disabled,
137
+input[type=button]:disabled,
138
+input[type=submit]:disabled,
139
+input[type=reset]:disabled{
140
+ color: #222;
141
+ background-color: #b0b0b0;
142
+ opacity: 0.8;
137143
}
138144
.button:focus,
139145
button:focus,
140146
input[type=button]:focus,
141
-input[type=reset]:focus,
142
-input[type=submit]:focus {
147
+input[type=submit]:focus,
148
+input[type=reset]:focus {
143149
outline: 2px outset #333;
144150
border-color: #888;
145151
}
146152
147153
/* All page content from the bottom of the menu or submenu down to
@@ -529,23 +535,10 @@
529535
}
530536
span.snippet>mark {
531537
color: white;
532538
font-weight: bold;
533539
}
534
-button,
535
-input,
536
-optgroup,
537
-select,
538
-textarea {
539
- background: inherit;
540
- color: inherit;
541
- font: inherit;
542
- margin: 0
543
-}
544
-button {
545
- background-color: rgba(45,45,45,0.75);
546
-}
547540
input, textarea, select {
548541
border: 1px solid rgba(127, 201, 255, 0.9);
549542
padding: 1px;
550543
}
551544
select {
552545
--- skins/darkmode/css.txt
+++ skins/darkmode/css.txt
@@ -98,50 +98,56 @@
98 }
99 .fileage tr:hover,
100 div.filetreeline:hover {
101 background-color: #333;
102 }
103 div.file-change-line button {
104 background-color: #484848
105 }
 
 
 
 
 
 
 
 
 
 
106 .button,
107 button {
108 color: #aaa;
109 background-color: #484848;
110 border-radius: 5px;
111 border: 0
112 }
113 .button:hover,
114 button:hover {
115 background-color: #FF4500f0;
116 color: rgba(24,24,24,0.8);
117 outline: 0
118 }
119 input[type=button],
120 input[type=reset],
121 input[type=submit] {
122 color: #ddd;
123 background-color: #446979;
 
124 border: 0;
125 border-radius: 5px
126 }
 
 
127 input[type=button]:hover,
128 input[type=reset]:hover,
129 input[type=submit]:hover {
130 background-color: #FF4500f0;
131 color: rgba(24,24,24,0.8);
132 outline: 0
133 }
134 input[type=submit]:disabled {
135 color: #363636;
136 background-color: #707070;
 
 
 
 
 
137 }
138 .button:focus,
139 button:focus,
140 input[type=button]:focus,
141 input[type=reset]:focus,
142 input[type=submit]:focus {
143 outline: 2px outset #333;
144 border-color: #888;
145 }
146
147 /* All page content from the bottom of the menu or submenu down to
@@ -529,23 +535,10 @@
529 }
530 span.snippet>mark {
531 color: white;
532 font-weight: bold;
533 }
534 button,
535 input,
536 optgroup,
537 select,
538 textarea {
539 background: inherit;
540 color: inherit;
541 font: inherit;
542 margin: 0
543 }
544 button {
545 background-color: rgba(45,45,45,0.75);
546 }
547 input, textarea, select {
548 border: 1px solid rgba(127, 201, 255, 0.9);
549 padding: 1px;
550 }
551 select {
552
--- skins/darkmode/css.txt
+++ skins/darkmode/css.txt
@@ -98,50 +98,56 @@
98 }
99 .fileage tr:hover,
100 div.filetreeline:hover {
101 background-color: #333;
102 }
103 div.file-change-line button{
104 background-color: #484848
105 }
106 button,
107 input,
108 optgroup,
109 select,
110 textarea {
111 background: inherit;
112 color: inherit;
113 font: inherit;
114 margin: 0
115 }
116 .button,
117 button,
 
 
 
 
 
 
 
 
 
 
 
118 input[type=button],
119 input[type=submit],
120 input[type=reset]{
121 color: #ddd;
122 background-color: #446979;
123 border-radius: 5px;
124 border: 0;
 
125 }
126 .button:hover,
127 button:hover,
128 input[type=button]:hover,
129 input[type=submit]:hover,
130 input[type=reset]:hover {
131 background-color: #FF4500f0;
132 color: rgba(24,24,24,0.8);
133 outline: 0;
134 }
135 .button:disabled,
136 button:disabled,
137 input[type=button]:disabled,
138 input[type=submit]:disabled,
139 input[type=reset]:disabled{
140 color: #222;
141 background-color: #b0b0b0;
142 opacity: 0.8;
143 }
144 .button:focus,
145 button:focus,
146 input[type=button]:focus,
147 input[type=submit]:focus,
148 input[type=reset]:focus {
149 outline: 2px outset #333;
150 border-color: #888;
151 }
152
153 /* All page content from the bottom of the menu or submenu down to
@@ -529,23 +535,10 @@
535 }
536 span.snippet>mark {
537 color: white;
538 font-weight: bold;
539 }
 
 
 
 
 
 
 
 
 
 
 
 
 
540 input, textarea, select {
541 border: 1px solid rgba(127, 201, 255, 0.9);
542 padding: 1px;
543 }
544 select {
545
+72 -10
--- src/ajax.c
+++ src/ajax.c
@@ -191,23 +191,52 @@
191191
** {error: formatted message}
192192
**
193193
** If httpCode<=0 then it defaults to 500.
194194
**
195195
** After calling this, the caller should immediately return.
196
+**
197
+** Returns the resulting http code.
196198
*/
197
-void ajax_route_error(int httpCode, const char * zFmt, ...){
199
+int ajax_route_error(int httpCode, const char * zFmt, ...){
198200
Blob msg = empty_blob;
199201
Blob content = empty_blob;
200202
va_list vargs;
203
+
204
+ if( httpCode<=0 ) httpCode=500;
201205
va_start(vargs,zFmt);
202206
blob_vappendf(&msg, zFmt, vargs);
203207
va_end(vargs);
204208
blob_appendf(&content,"{\"error\":%!j}", blob_str(&msg));
205209
blob_reset(&msg);
206210
cgi_set_content(&content);
207
- cgi_set_status(httpCode>0 ? httpCode : 500, "Error");
211
+ cgi_set_status(httpCode, "Error");
208212
cgi_set_content_type("application/json");
213
+ return httpCode;
214
+}
215
+
216
+void ajax_route_error_forbidden(){
217
+ ajax_route_error(403, "Permission denied.");
218
+}
219
+
220
+void ajax_route_error_captcha(){
221
+ ajax_route_error(400, "Invalid captcha response.");
222
+}
223
+
224
+void ajax_route_error_csrf(){
225
+ ajax_route_error(403, "Invalid CSRF signature.");
226
+}
227
+
228
+void ajax_route_error_404(const char *zMsg){
229
+ ajax_route_error(404, "%s", zMsg ? zMsg : "Resource not found.");
230
+}
231
+
232
+int ajax_check_csrf(int level){
233
+ if( 0==cgi_csrf_safe(level) ){
234
+ ajax_route_error_csrf();
235
+ return 0;
236
+ }
237
+ return 1;
209238
}
210239
211240
/*
212241
** Performs bootstrapping common to the /ajax/xyz AJAX routes, such as
213242
** logging in the user.
@@ -224,17 +253,18 @@
224253
int ajax_route_bootstrap(int requireWrite, int requirePost){
225254
login_check_credentials();
226255
if( requireWrite!=0 && g.perm.Write==0 ){
227256
ajax_route_error(403,"Write permissions required.");
228257
return 0;
229
- }else if(0==cgi_csrf_safe(requirePost)){
258
+ }else if(requirePost && 0==cgi_csrf_safe(requirePost)){
230259
ajax_route_error(403,
231260
"CSRF violation (make sure sending of HTTP "
232261
"Referer headers is enabled for XHR "
233262
"connections).");
234263
return 0;
235264
}
265
+ cgi_set_content_type("application/json");
236266
return 1;
237267
}
238268
239269
/*
240270
** Helper for collecting filename/check-in request parameters.
@@ -283,12 +313,10 @@
283313
** AJAX_RENDER_PLAIN_TEXT mode.
284314
**
285315
** iframe_height=integer (default=40) Height, in EMs of HTML preview
286316
** iframe.
287317
**
288
-** User must have Write access to use this page.
289
-**
290318
** Responds with the HTML content of the preview. On error it produces
291319
** a JSON response as documented for ajax_route_error().
292320
**
293321
** Extra response headers:
294322
**
@@ -341,10 +369,37 @@
341369
}
342370
if(zRenderMode!=0){
343371
cgi_printf_header("x-ajax-render-mode: %s\r\n", zRenderMode);
344372
}
345373
}
374
+
375
+/*
376
+** AJAX route /ajax/artifact.json.
377
+** URL arguments:
378
+**
379
+** uuid=ARTIFACT_ID REQUIRED
380
+**
381
+** and emits either:
382
+**
383
+** { error: "..." }
384
+**
385
+** with a non-200 response code or the artifact's manifest in JSON
386
+** form with a 200 response code.
387
+*/
388
+void ajax_route_artifact_json(void){
389
+ const char *zUuid = P("uuid");
390
+ Blob json = BLOB_INITIALIZER;
391
+ login_check_credentials();
392
+ if( ! g.perm.Read ){
393
+ ajax_route_error_forbidden();
394
+ }else if( artifact_to_json_by_name(zUuid, &json) ){
395
+ @ %b(&json)
396
+ }else{
397
+ ajax_route_error_404("Cannot resolve artifact ID.");
398
+ }
399
+ blob_reset(&json);
400
+}
346401
347402
#if INTERFACE
348403
/*
349404
** Internal mapping of ajax sub-route names to various metadata.
350405
*/
@@ -351,11 +406,12 @@
351406
struct AjaxRoute {
352407
const char *zName; /* Name part of the route after "ajax/" */
353408
void (*xCallback)(); /* Impl function for the route. */
354409
int bWriteMode; /* True if requires write mode */
355410
int bPost; /* True if requires POST (i.e. CSRF
356
- ** verification) */
411
+ ** verification). Value is passed to
412
+ ** cgi_csrf_safe(). */
357413
};
358414
typedef struct AjaxRoute AjaxRoute;
359415
#endif /*INTERFACE*/
360416
361417
/*
@@ -392,20 +448,26 @@
392448
const char * zName = P("name");
393449
AjaxRoute routeName = {0,0,0,0};
394450
const AjaxRoute * pRoute = 0;
395451
const AjaxRoute routes[] = {
396452
/* Keep these sorted by zName (for bsearch()) */
453
+ {"artifact.json", ajax_route_artifact_json, 0, 0},
397454
{"preview-text", ajax_route_preview_text, 0, 1
398
- /* Note that this does not require write permissions in the repo.
399
- ** It should arguably require write permissions but doing means
400
- ** that /chat does not work without check-in permissions:
455
+ /* Preview does not require write permissions in the repo. It
456
+ ** should arguably require write permissions simply to limit abuse
457
+ ** but doing means that /chat does not work without check-in
458
+ ** permissions:
401459
**
402460
** https://fossil-scm.org/forum/forumpost/ed4a762b3a557898
403461
**
404462
** This particular route is used by /fileedit and /chat, whereas
405463
** /wikiedit uses a simpler wiki-specific route.
406
- */ }
464
+ */
465
+ /* TODO (2026-06-09): preview.txt, preview.md, preview.wiki as
466
+ ** shorthand for preview-text?filename=X.(txt|md|wiki), noting that
467
+ ** the filename is only used for mimetype determination. */
468
+ }
407469
};
408470
409471
if(zName==0 || zName[0]==0){
410472
ajax_route_error(400,"Missing required [route] 'name' parameter.");
411473
return;
412474
--- src/ajax.c
+++ src/ajax.c
@@ -191,23 +191,52 @@
191 ** {error: formatted message}
192 **
193 ** If httpCode<=0 then it defaults to 500.
194 **
195 ** After calling this, the caller should immediately return.
 
 
196 */
197 void ajax_route_error(int httpCode, const char * zFmt, ...){
198 Blob msg = empty_blob;
199 Blob content = empty_blob;
200 va_list vargs;
 
 
201 va_start(vargs,zFmt);
202 blob_vappendf(&msg, zFmt, vargs);
203 va_end(vargs);
204 blob_appendf(&content,"{\"error\":%!j}", blob_str(&msg));
205 blob_reset(&msg);
206 cgi_set_content(&content);
207 cgi_set_status(httpCode>0 ? httpCode : 500, "Error");
208 cgi_set_content_type("application/json");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209 }
210
211 /*
212 ** Performs bootstrapping common to the /ajax/xyz AJAX routes, such as
213 ** logging in the user.
@@ -224,17 +253,18 @@
224 int ajax_route_bootstrap(int requireWrite, int requirePost){
225 login_check_credentials();
226 if( requireWrite!=0 && g.perm.Write==0 ){
227 ajax_route_error(403,"Write permissions required.");
228 return 0;
229 }else if(0==cgi_csrf_safe(requirePost)){
230 ajax_route_error(403,
231 "CSRF violation (make sure sending of HTTP "
232 "Referer headers is enabled for XHR "
233 "connections).");
234 return 0;
235 }
 
236 return 1;
237 }
238
239 /*
240 ** Helper for collecting filename/check-in request parameters.
@@ -283,12 +313,10 @@
283 ** AJAX_RENDER_PLAIN_TEXT mode.
284 **
285 ** iframe_height=integer (default=40) Height, in EMs of HTML preview
286 ** iframe.
287 **
288 ** User must have Write access to use this page.
289 **
290 ** Responds with the HTML content of the preview. On error it produces
291 ** a JSON response as documented for ajax_route_error().
292 **
293 ** Extra response headers:
294 **
@@ -341,10 +369,37 @@
341 }
342 if(zRenderMode!=0){
343 cgi_printf_header("x-ajax-render-mode: %s\r\n", zRenderMode);
344 }
345 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
347 #if INTERFACE
348 /*
349 ** Internal mapping of ajax sub-route names to various metadata.
350 */
@@ -351,11 +406,12 @@
351 struct AjaxRoute {
352 const char *zName; /* Name part of the route after "ajax/" */
353 void (*xCallback)(); /* Impl function for the route. */
354 int bWriteMode; /* True if requires write mode */
355 int bPost; /* True if requires POST (i.e. CSRF
356 ** verification) */
 
357 };
358 typedef struct AjaxRoute AjaxRoute;
359 #endif /*INTERFACE*/
360
361 /*
@@ -392,20 +448,26 @@
392 const char * zName = P("name");
393 AjaxRoute routeName = {0,0,0,0};
394 const AjaxRoute * pRoute = 0;
395 const AjaxRoute routes[] = {
396 /* Keep these sorted by zName (for bsearch()) */
 
397 {"preview-text", ajax_route_preview_text, 0, 1
398 /* Note that this does not require write permissions in the repo.
399 ** It should arguably require write permissions but doing means
400 ** that /chat does not work without check-in permissions:
 
401 **
402 ** https://fossil-scm.org/forum/forumpost/ed4a762b3a557898
403 **
404 ** This particular route is used by /fileedit and /chat, whereas
405 ** /wikiedit uses a simpler wiki-specific route.
406 */ }
 
 
 
 
407 };
408
409 if(zName==0 || zName[0]==0){
410 ajax_route_error(400,"Missing required [route] 'name' parameter.");
411 return;
412
--- src/ajax.c
+++ src/ajax.c
@@ -191,23 +191,52 @@
191 ** {error: formatted message}
192 **
193 ** If httpCode<=0 then it defaults to 500.
194 **
195 ** After calling this, the caller should immediately return.
196 **
197 ** Returns the resulting http code.
198 */
199 int ajax_route_error(int httpCode, const char * zFmt, ...){
200 Blob msg = empty_blob;
201 Blob content = empty_blob;
202 va_list vargs;
203
204 if( httpCode<=0 ) httpCode=500;
205 va_start(vargs,zFmt);
206 blob_vappendf(&msg, zFmt, vargs);
207 va_end(vargs);
208 blob_appendf(&content,"{\"error\":%!j}", blob_str(&msg));
209 blob_reset(&msg);
210 cgi_set_content(&content);
211 cgi_set_status(httpCode, "Error");
212 cgi_set_content_type("application/json");
213 return httpCode;
214 }
215
216 void ajax_route_error_forbidden(){
217 ajax_route_error(403, "Permission denied.");
218 }
219
220 void ajax_route_error_captcha(){
221 ajax_route_error(400, "Invalid captcha response.");
222 }
223
224 void ajax_route_error_csrf(){
225 ajax_route_error(403, "Invalid CSRF signature.");
226 }
227
228 void ajax_route_error_404(const char *zMsg){
229 ajax_route_error(404, "%s", zMsg ? zMsg : "Resource not found.");
230 }
231
232 int ajax_check_csrf(int level){
233 if( 0==cgi_csrf_safe(level) ){
234 ajax_route_error_csrf();
235 return 0;
236 }
237 return 1;
238 }
239
240 /*
241 ** Performs bootstrapping common to the /ajax/xyz AJAX routes, such as
242 ** logging in the user.
@@ -224,17 +253,18 @@
253 int ajax_route_bootstrap(int requireWrite, int requirePost){
254 login_check_credentials();
255 if( requireWrite!=0 && g.perm.Write==0 ){
256 ajax_route_error(403,"Write permissions required.");
257 return 0;
258 }else if(requirePost && 0==cgi_csrf_safe(requirePost)){
259 ajax_route_error(403,
260 "CSRF violation (make sure sending of HTTP "
261 "Referer headers is enabled for XHR "
262 "connections).");
263 return 0;
264 }
265 cgi_set_content_type("application/json");
266 return 1;
267 }
268
269 /*
270 ** Helper for collecting filename/check-in request parameters.
@@ -283,12 +313,10 @@
313 ** AJAX_RENDER_PLAIN_TEXT mode.
314 **
315 ** iframe_height=integer (default=40) Height, in EMs of HTML preview
316 ** iframe.
317 **
 
 
318 ** Responds with the HTML content of the preview. On error it produces
319 ** a JSON response as documented for ajax_route_error().
320 **
321 ** Extra response headers:
322 **
@@ -341,10 +369,37 @@
369 }
370 if(zRenderMode!=0){
371 cgi_printf_header("x-ajax-render-mode: %s\r\n", zRenderMode);
372 }
373 }
374
375 /*
376 ** AJAX route /ajax/artifact.json.
377 ** URL arguments:
378 **
379 ** uuid=ARTIFACT_ID REQUIRED
380 **
381 ** and emits either:
382 **
383 ** { error: "..." }
384 **
385 ** with a non-200 response code or the artifact's manifest in JSON
386 ** form with a 200 response code.
387 */
388 void ajax_route_artifact_json(void){
389 const char *zUuid = P("uuid");
390 Blob json = BLOB_INITIALIZER;
391 login_check_credentials();
392 if( ! g.perm.Read ){
393 ajax_route_error_forbidden();
394 }else if( artifact_to_json_by_name(zUuid, &json) ){
395 @ %b(&json)
396 }else{
397 ajax_route_error_404("Cannot resolve artifact ID.");
398 }
399 blob_reset(&json);
400 }
401
402 #if INTERFACE
403 /*
404 ** Internal mapping of ajax sub-route names to various metadata.
405 */
@@ -351,11 +406,12 @@
406 struct AjaxRoute {
407 const char *zName; /* Name part of the route after "ajax/" */
408 void (*xCallback)(); /* Impl function for the route. */
409 int bWriteMode; /* True if requires write mode */
410 int bPost; /* True if requires POST (i.e. CSRF
411 ** verification). Value is passed to
412 ** cgi_csrf_safe(). */
413 };
414 typedef struct AjaxRoute AjaxRoute;
415 #endif /*INTERFACE*/
416
417 /*
@@ -392,20 +448,26 @@
448 const char * zName = P("name");
449 AjaxRoute routeName = {0,0,0,0};
450 const AjaxRoute * pRoute = 0;
451 const AjaxRoute routes[] = {
452 /* Keep these sorted by zName (for bsearch()) */
453 {"artifact.json", ajax_route_artifact_json, 0, 0},
454 {"preview-text", ajax_route_preview_text, 0, 1
455 /* Preview does not require write permissions in the repo. It
456 ** should arguably require write permissions simply to limit abuse
457 ** but doing means that /chat does not work without check-in
458 ** permissions:
459 **
460 ** https://fossil-scm.org/forum/forumpost/ed4a762b3a557898
461 **
462 ** This particular route is used by /fileedit and /chat, whereas
463 ** /wikiedit uses a simpler wiki-specific route.
464 */
465 /* TODO (2026-06-09): preview.txt, preview.md, preview.wiki as
466 ** shorthand for preview-text?filename=X.(txt|md|wiki), noting that
467 ** the filename is only used for mimetype determination. */
468 }
469 };
470
471 if(zName==0 || zName[0]==0){
472 ajax_route_error(400,"Missing required [route] 'name' parameter.");
473 return;
474
+931 -109
--- src/attach.c
+++ src/attach.c
@@ -22,41 +22,188 @@
2222
#include <assert.h>
2323
2424
/*
2525
** Given a presumedly legal attachment target name, this guesses the
2626
** target type and returns one of CFTYPE_FORUM, CFTYPE_WIKI,
27
-** CFTYPE_TICKET, or CFTYPE_EVENT. Returns 0 if it cannot
28
-** distinguish the target type.
27
+** CFTYPE_TICKET, or CFTYPE_EVENT. Returns 0 if it cannot distinguish
28
+** the target type.
29
+**
30
+** zTarget is an attachment target name: wiki page name, tech-note ID,
31
+** ticket ID, or forumpost hash.
32
+**
33
+** If bFull is true then it requires zTarget to be a full ID for
34
+** tech-notes and tickets, otherwise such IDs may be prefixes. If
35
+** bFull is false then tech-notes and tickets will perform a prefix
36
+** match, but it is up to the caller to provide enough of a prefix to
37
+** rule out ambiguity[^1]. When called repeatedly, this routine can
38
+** run a bit faster and more efficiently if bFull is true, but some
39
+** historical use cases call for prefix matches.
40
+**
41
+** Wiki page names always require an exact match.
42
+**
43
+** Forum posts are a special case:
44
+**
45
+** - They ignore the bFull flag. That is, they will do prefix matches
46
+** but will not match an ambiguous prefix.
47
+**
48
+** - It is up to the caller to, if needed, resolve zTarget using
49
+** forumpost_head_rid2() to resolve the RID of the earliest version
50
+** of the post, as that is the only one which attachments should
51
+** target.
2952
**
30
-** In the case of CFTYPE_FORUM, it is up to the caller to ensure that,
31
-** if needed, they resolve zTarget using forumpost_head_rid2() so that
32
-** they get the RID of the earliest version of the post, as that is
33
-** the only one which attachments should target.
53
+** [^1]: Historically (from the perspective of 2026-06) attachment
54
+** target lookups have used GLOB prefix matching but have taken no
55
+** measures to ensure that the prefix is unambiguous. Ergo we do the
56
+** same here. It is assumed that the caller passes enough of a prefix
57
+** to be unambiguous and that's worked out fine so far.
3458
*/
35
-int attachment_target_type(const char *zTarget){
36
- static Stmt q = empty_Stmt_m;
37
- int rc = 0;
38
- if( forumpost_head_rid2(zTarget)>0 ){
59
+int attachment_target_type(const char *zTarget, int bFull){
60
+ if( !zTarget || !zTarget[0] || strlen(zTarget)>64/*vs. abuse*/ ){
61
+ return 0;
62
+ }
63
+ if( symbolic_name_to_rid(zTarget, "f")>0 ){
64
+ /* Check forum posts first because they are the most likely target
65
+ ** as of 2026. We should arguably use something more
66
+ ** specialized/efficient than symbolic_name_to_rid(). */
3967
return CFTYPE_FORUM;
4068
}
41
- if( !q.pStmt ){
42
- db_static_prepare(
43
- &q,
69
+ if( bFull ){
70
+ static Stmt q = empty_Stmt_m;
71
+ int rc = 0;
72
+ if( !q.pStmt ){
73
+ db_static_prepare(
74
+ &q,
75
+ "SELECT CASE "
76
+ /* Ordered by presumed likelihood of attachments. */
77
+ "WHEN (SELECT 1 FROM tag WHERE tagname='tkt-'||:tgt) THEN %d\n"
78
+ "WHEN (SELECT 1 FROM tag WHERE tagname='wiki-'||:tgt) THEN %d\n"
79
+ "WHEN (SELECT 1 FROM tag WHERE tagname='event-'||:tgt) THEN %d\n"
80
+ "ELSE 0 END",
81
+ CFTYPE_TICKET, CFTYPE_WIKI, CFTYPE_EVENT
82
+ );
83
+ }
84
+ db_bind_text(&q, ":tgt", zTarget);
85
+ if( SQLITE_ROW==db_step(&q) ){
86
+ rc = db_column_int(&q, 0);
87
+ }
88
+ db_reset(&q);
89
+ return rc;
90
+ }else{
91
+ return db_int(
92
+ 0,
4493
"SELECT CASE "
45
- "WHEN 'tkt-'||:tgt IN (SELECT tagname FROM tag) THEN %d "
46
- "WHEN 'event-'||:tgt IN (SELECT tagname FROM tag) THEN %d "
47
- "WHEN 'wiki-'||:tgt IN (SELECT tagname FROM tag) THEN %d "
94
+ "WHEN (SELECT tagid FROM tag WHERE tagname GLOB 'tkt-%q*')"
95
+ " THEN %d\n"
96
+ "WHEN (SELECT tagid FROM tag WHERE tagname='wiki-%q')"
97
+ " THEN %d\n"
98
+ "WHEN (SELECT tagid FROM tag WHERE tagname GLOB 'event-%q*')"
99
+ " THEN %d\n"
48100
"ELSE 0 END",
49
- CFTYPE_TICKET, CFTYPE_EVENT, CFTYPE_WIKI
101
+ zTarget, CFTYPE_TICKET,
102
+ zTarget, CFTYPE_WIKI,
103
+ zTarget, CFTYPE_EVENT
50104
);
51105
}
52
- db_bind_text(&q, ":tgt", zTarget);
53
- if( SQLITE_ROW==db_step(&q) ){
54
- rc = db_column_int(&q, 0);
106
+}
107
+
108
+/*
109
+** Given an attachment target name, returns the target's blob.rid.
110
+** zTarget and bFull work as described for attachment_target_type().
111
+**
112
+** For forum posts, this always returns the RID of the first version
113
+** of the post, as attachments should always target that instance.
114
+*/
115
+int attachment_target_rid(const char *zTarget, int bFull){
116
+ int rid = 0;
117
+ const int eType = attachment_target_type(zTarget, bFull);
118
+ switch(eType){
119
+ case CFTYPE_TICKET:
120
+ case CFTYPE_EVENT:{
121
+ const char *zTagPrefix = (eType==CFTYPE_EVENT) ? "event" : "tkt";
122
+ rid = db_int(
123
+ 0, "SELECT b.rid FROM blob b, tag t, tagxref x\n"
124
+ "WHERE tagname %s '%s-%q%s'\n"
125
+ "AND x.tagtype>0\n"
126
+ "AND x.tagid=t.tagid\n"
127
+ "AND x.rid=b.rid\n"
128
+ "ORDER BY x.mtime DESC",
129
+ bFull ? "=" : "GLOB"/*safe-for-%s*/,
130
+ zTagPrefix/*safe-for-%s*/,
131
+ zTarget,
132
+ bFull ? "" : "*"/*safe-for-%s*/
133
+ );
134
+ break;
135
+ }
136
+ case CFTYPE_FORUM:
137
+ rid = db_int(
138
+ 0, "SELECT f.fpid FROM forumpost f, blob b\n"
139
+ "WHERE f.fpid=b.rid\n"
140
+ "AND b.uuid %s '%q%s'",
141
+ bFull ? "=" : "GLOB"/*safe-for-%s*/,
142
+ zTarget,
143
+ bFull ? "" : "*"/*safe-for-%s*/
144
+ );
145
+ if( rid>0 ){
146
+ rid = forumpost_head_rid(rid);
147
+ }
148
+ break;
149
+ case CFTYPE_WIKI:
150
+ rid = db_int(
151
+ 0, "SELECT b.rid FROM blob b, tag t, tagxref x\n"
152
+ "WHERE tagname='wiki-%q'\n"
153
+ "AND x.tagtype>0\n"
154
+ "AND x.tagid=t.tagid\n"
155
+ "AND x.rid=b.rid\n"
156
+ "ORDER BY x.mtime DESC",
157
+ zTarget
158
+ );
159
+ break;
160
+ default:
161
+ break;
162
+ }
163
+ return rid;
164
+}
165
+
166
+/*
167
+** For a given aritfact ID and type (from the CFTYPE_xyz enum),
168
+** returns true if the current user could hypothetically apply and
169
+** attachment to it, else returns 0.
170
+**
171
+** The rid is currently only relevant when eArtifactType is
172
+** CFTYPE_FORUM. For forum posts, it checks precisely the rid given,
173
+** not the head RID, to keep non-admins from attaching files to
174
+** threads which have since been taken over by another user (this
175
+** happens when an admin edits another user's post).
176
+*/
177
+int attach_user_may(int rid, int eArtifactType){
178
+ if( g.perm.Admin ) return 1;
179
+ if( !login_is_individual() ) return 0;
180
+ switch(eArtifactType){
181
+ case CFTYPE_FORUM:
182
+ return g.perm.AttachForum && forumpost_is_owner(rid, 0);
183
+ case CFTYPE_WIKI:
184
+ return g.perm.ApndWiki && g.perm.Attach;
185
+ case CFTYPE_TICKET:
186
+ return g.perm.ApndTkt && g.perm.Attach;
187
+ case CFTYPE_EVENT:
188
+ return g.perm.Write && g.perm.ApndWiki && g.perm.Attach;
189
+ default:
190
+ return 0;
55191
}
56
- db_reset(&q);
57
- return rc;
192
+}
193
+
194
+/*
195
+** Emits a single-button FORM which invokes
196
+** /attachadd with target=$zTarget.
197
+*/
198
+void attach_render_attachadd_button(const char *zTarget){
199
+ /* This could be changed from POST to GET, and arguably should so
200
+ ** that the target=X part becomes part of the resulting URL. */
201
+ @ <form method="post" action="%R/attachadd">\
202
+ @ <input type="hidden" name="target" value="%T(zTarget)">\
203
+ @ <input type="submit" value="Attach...">
204
+ @ </form>\
58205
}
59206
60207
/*
61208
** WEBPAGE: attachlist
62209
** List attachments.
@@ -69,20 +216,21 @@
69216
** At most one of technote=, tkt=, forumpost=, or page= may be supplied.
70217
**
71218
** If none are given, all attachments are listed. If one is given, only
72219
** attachments for the designated technote, ticket or wiki page are shown.
73220
**
74
-** HASH may be just a prefix of the relevant technical note or ticket
75
-** artifact hash, in which case all attachments of all technical notes or
76
-** tickets with the prefix will be listed. Forum posts, on the other hand,
77
-** require a unique hash prefix.
221
+** HASH may be just a prefix of the relevant forum post, technical
222
+** note, or ticket artifact hash, in which case all attachments of all
223
+** technical notes or tickets with the prefix will be listed. Forum
224
+** posts, on the other hand, require a unique hash or hash prefix.
78225
*/
79226
void attachlist_page(void){
80227
const char *zPage = P("page");
81228
const char *zTkt = P("tkt");
82229
const char *zTechNote = P("technote");
83230
const char *zForumPost = P("forumpost");
231
+ char *zLink = 0;
84232
Blob sql;
85233
Stmt q;
86234
87235
if( zPage && zTkt ) zTkt = 0;
88236
login_check_credentials();
@@ -102,32 +250,47 @@
102250
if( fnid<=0 ){
103251
webpage_error("Invalid forum post ID: %h", zForumPost);
104252
}
105253
blob_append_sql(&sql, " WHERE target="
106254
"(SELECT uuid FROM blob WHERE rid=%d)", fnid);
255
+ zLink = mprintf("forum post <a href='%R/forumpost/%t'>%#h</a>",
256
+ zForumPost, hash_digits(0), zForumPost);
107257
}else if( zPage ){
108258
if( g.perm.RdWiki==0 ){ login_needed(g.anon.RdWiki); return; }
109259
style_header("Attachments To Wiki page %h", zPage);
110260
blob_append_sql(&sql, " WHERE target=%Q", zPage);
261
+ zLink = mprintf("wiki page <a href='%R/wiki?name=%t'>%h</a>",
262
+ zPage, zPage);
111263
}else if( zTkt ){
112264
if( g.perm.RdTkt==0 ){ login_needed(g.anon.RdTkt); return; }
113265
style_header("Attachments To Ticket %S", zTkt);
114266
blob_append_sql(&sql, " WHERE target GLOB '%q*'", zTkt);
267
+ zLink = mprintf("ticket <a href='%R/tktview?name=%t'>%#h</a>",
268
+ zTkt, hash_digits(0), zTkt);
115269
}else if( zTechNote ){
116270
if( g.perm.RdWiki==0 ){ login_needed(g.anon.RdWiki); return; }
117271
style_header("Attachments To Tech Note %S", zTechNote);
118272
blob_append_sql(&sql, " WHERE target GLOB '%q*'",
119273
zTechNote);
274
+ zLink = mprintf("tech-note <a href='%R/technote?name=%t'>%#h</a>",
275
+ zTechNote, hash_digits(0), zTechNote);
120276
}else{
121277
if( g.perm.RdTkt==0 && g.perm.RdWiki==0 ){
122278
login_needed(g.anon.RdTkt || g.anon.RdWiki);
123279
return;
124280
}
125281
style_header("All Attachments");
126282
}
127283
blob_append_sql(&sql, " ORDER BY mtime DESC");
128284
db_prepare(&q, "%s", blob_sql_text(&sql));
285
+
286
+ if( zLink ){
287
+ @ <h2>Attachments for %s(zLink)</h2>
288
+ fossil_free(zLink);
289
+ zLink = 0;
290
+ }
291
+
129292
@ <ol>
130293
while( db_step(&q)==SQLITE_ROW ){
131294
const char *zDate;
132295
const char *zSrc;
133296
const char *zTarget;
@@ -137,10 +300,11 @@
137300
const char *zUuid;
138301
const char *zDispUser;
139302
const int attachid = db_column_int(&q, 7);
140303
int type;
141304
int i;
305
+ int bDeleted;
142306
char *zUrlTail = 0;
143307
144308
if( moderation_pending(attachid)
145309
&& !moderation_user_could(attachid, 1, 0) ){
146310
/* Elide entries which are currently pending moderation unless
@@ -160,11 +324,12 @@
160324
if( zFilename[i]=='/' && zFilename[i+1]!=0 ){
161325
zFilename = &zFilename[i+1];
162326
i = -1;
163327
}
164328
}
165
- type = attachment_target_type(zTarget);
329
+ bDeleted = 0==zSrc || 0==zSrc[0];
330
+ type = attachment_target_type(zTarget, 1);
166331
switch( type ){
167332
case CFTYPE_TICKET:
168333
zUrlTail = mprintf("tkt=%s&file=%t", zTarget, zFilename);
169334
break;
170335
case CFTYPE_EVENT:
@@ -176,20 +341,32 @@
176341
case CFTYPE_WIKI:
177342
zUrlTail = mprintf("page=%t&file=%t", zTarget, zFilename);
178343
break;
179344
}
180345
@ <li><p>
181
- @ Attachment %z(href("%R/ainfo/%!S",zUuid))%S(zUuid)</a>
346
+ if( bDeleted ){
347
+ @ <s>\
348
+ }
349
+ @ Attachment %z(href("%R/ainfo/%!S",zUuid))%S(zUuid)</a>\
182350
moderation_pending_www(attachid);
183
- @ <br><a href="%R/attachview?%s(zUrlTail)">%h(zFilename)</a>
184
- @ [<a href="%R/attachdownload/%t(zFilename)?%s(zUrlTail)">download</a>]<br>
351
+ @ <br>\
352
+ @ <a href="%R/attachview?%s(zUrlTail)">%h(zFilename)</a>
353
+ @ [<a href="%R/attachdownload/%t(zFilename)?%s(zUrlTail)">download</a>]\
354
+ if( bDeleted ){
355
+ @ </s>
356
+ }
357
+ @ <br>
185358
if( zComment ) while( fossil_isspace(zComment[0]) ) zComment++;
186359
if( zComment && zComment[0] ){
187
- @ %!W(zComment)<br>
360
+ /* FIXME (2026-06-05): Honor the N-card (comment mimetype). %W
361
+ ** (historically used here) assumes fossil-wiki and the
362
+ ** fileformat.wiki doc has always claimed that it defaults to
363
+ ** text/plain. /ainfo assumes it is plain text. */
364
+ @ %h(zComment)<br>
188365
}
189366
if( zForumPost==0 && zPage==0 && zTkt==0 && zTechNote==0 ){
190
- if( zSrc==0 || zSrc[0]==0 ){
367
+ if( bDeleted ){
191368
zSrc = "Deleted from";
192369
}else {
193370
zSrc = "Added to";
194371
}
195372
switch( type ){
@@ -362,41 +539,81 @@
362539
Manifest *pManifest;
363540
364541
db_begin_transaction();
365542
blob_init(&content, aContent, szContent);
366543
pManifest = manifest_parse(&content, 0, 0);
544
+ addCompress = pManifest!=0;
367545
manifest_destroy(pManifest);
368546
blob_init(&content, aContent, szContent);
369
- if( pManifest ){
547
+ if( addCompress ){
370548
blob_compress(&content, &content);
371
- addCompress = 1;
372549
}
373550
rid = content_put_ex(&content, 0, 0, 0, needModerator);
374
- zUUID = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", rid);
551
+ zUUID = rid_to_uuid(rid);
375552
blob_zero(&manifest);
376553
for(i=n=0; zName[i]; i++){
377554
if( zName[i]=='/' || zName[i]=='\\' ) n = i+1;
378555
}
379556
zName += n;
380557
if( zName[0]==0 ) zName = "unknown";
381558
blob_appendf(&manifest, "A %F%s %F %s\n",
382559
zName, addCompress ? ".gz" : "", zTarget, zUUID);
383
- while( fossil_isspace(zComment[0]) ) zComment++;
384
- n = strlen(zComment);
385
- while( n>0 && fossil_isspace(zComment[n-1]) ){ n--; }
386
- if( n>0 ){
387
- blob_appendf(&manifest, "C %#F\n", n, zComment);
560
+ if( zComment!=0 && zComment[0]!=0 ){
561
+ while( fossil_isspace(zComment[0]) ) zComment++;
562
+ n = strlen(zComment);
563
+ while( n>0 && fossil_isspace(zComment[n-1]) ){ n--; }
564
+ if( n>0 ){
565
+ blob_appendf(&manifest, "C %#F\n", n, zComment);
566
+ }
388567
}
389568
zDate = date_in_standard_format("now");
390
- blob_appendf(&manifest, "D %s\n", zDate);
569
+ blob_appendf(&manifest, "D %z\n", zDate);
391570
blob_appendf(&manifest, "U %F\n", login_name());
392571
md5sum_blob(&manifest, &cksum);
393572
blob_appendf(&manifest, "Z %b\n", &cksum);
394573
attach_put(&manifest, rid, needModerator);
395574
assert( blob_is_reset(&manifest) );
396575
db_end_transaction(0);
397576
}
577
+
578
+/*
579
+** Renders the "legacy" (static) /attachadd form. One of the first
580
+** four arguments must be non-NULL and the other three must be NULL.
581
+** zComment may be NULL, as may zFrom. See the call sites for more
582
+** context.
583
+*/
584
+static void attach_render_legacy_form(const char *zForumPost,
585
+ const char *zTechNote,
586
+ const char *zTicket,
587
+ const char *zWikiPage,
588
+ const char *zComment,
589
+ const char *zFrom){
590
+ form_begin("enctype='multipart/form-data' id='attachadd-legacy-form'",
591
+ "%R/attachadd");
592
+ @ <div>\
593
+ @ File to Attach:
594
+ @ <input type="file" name="f" size="60"><br>
595
+ @ Description:<br>
596
+ @ <textarea name="comment" cols="80" rows="5" wrap="virtual"\
597
+ @ >%h(zComment)</textarea><br>
598
+ if( zForumPost ){
599
+ @ <input type="hidden" name="forumpost" value="%h(zForumPost)">\
600
+ }else if( zTicket ){
601
+ @ <input type="hidden" name="tkt" value="%h(zTicket)">\
602
+ }else if( zTechNote ){
603
+ @ <input type="hidden" name="technote" value="%h(zTechNote)">\
604
+ }else if( zWikiPage ){
605
+ @ <input type="hidden" name="page" value="%h(zWikiPage)">\
606
+ }
607
+ @ <input type="hidden" name="from" value="%h(zFrom)">\
608
+ @ <input type="submit" name="ok" value="Add Attachment">\
609
+ @ <input type="submit" name="cancel" value="Cancel">\
610
+ @ </div>
611
+ captcha_generate(0);
612
+ login_insert_csrf_secret();
613
+ @ </form>
614
+}
398615
399616
/*
400617
** WEBPAGE: attachadd
401618
** Add a new attachment.
402619
**
@@ -404,33 +621,54 @@
404621
** page=WIKIPAGE
405622
** technote=HASH
406623
** forumpost=HASH
407624
** from=URL
408625
**
626
+** Adds a POSTed file attachment to the given target.
627
+**
628
+** Or the "version 2" interface:
629
+**
630
+** target=ATTACHMENT_TARGET
631
+**
632
+** Behaves as documented for attachaddV2_page().
409633
*/
410634
void attachadd_page(void){
411
- const char *zPage = P("page");
412
- const char *zForumPost = P("forumpost");
413
- const char *zTkt = P("tkt");
414
- const char *zTechNote = P("technote");
415
- const char *zFrom = P("from");
416
- const char *aContent = P("f");
417
- const char *zName = PD("f:filename","unknown");
418
- const char *zComment = PD("comment", "");
635
+ const char *zPage;
636
+ const char *zForumPost;
637
+ const char *zTkt;
638
+ const char *zTechNote;
639
+ const char *aContent;
640
+ const char *zName;
641
+ const char *zComment;
419642
const char *zTarget;
420
- char * zTo = 0;
643
+ const char *zFrom; /* Origin page - redirect here after saving */
644
+ char *zTo = 0; /* Optionally redirect here after saving */
421645
char *zTargetType = 0;
422646
char *zExtraFree = 0;
423
- int szContent = atoi(PD("f:bytes","0"));
647
+ int szContent;
424648
int goodCaptcha = 1;
425649
int szLimit = 0;
426650
651
+ if( P("target")!=0 ){
652
+ attachaddV2_page();
653
+ return;
654
+ }
655
+ zPage = P("page");
656
+ zForumPost = P("forumpost");
657
+ zTkt = P("tkt");
658
+ zTechNote = P("technote");
659
+ zFrom = P("from");
660
+ aContent = P("f");
661
+ zName = PD("f:filename","unknown");
662
+ zComment = PD("comment", "");
663
+ szContent = atoi(PD("f:bytes","0"));
664
+
427665
if( zFrom==0 ) zFrom = mprintf("%R/home");
428666
if( P("cancel") ) cgi_redirect(zFrom);
429667
if( (!!zPage + !!zTkt + !!zTechNote + !!zForumPost)!=1 ){
430668
webpage_error("Requires exactly one one: page=X, tkt=X, forumpost=X,"
431
- " or technote=X");
669
+ " technote=X, or target=X");
432670
}
433671
login_check_credentials();
434672
if( zForumPost ){
435673
int fpid;
436674
if( g.perm.AttachForum==0 ){
@@ -445,26 +683,23 @@
445683
"forum posts.");
446684
}
447685
zTarget = zExtraFree = rid_to_uuid(fpid);
448686
zTargetType = mprintf("Forum post <a href=\"%R/forumpost/%S\">%h</a>",
449687
zTarget, zForumPost);
450
- zTo = 1
451
- ? mprintf("%R/forumpost/%S", zTarget)
452
- : mprintf("%R/attachview?forumpost=%T&file=%T",
453
- zTarget, zName)
454
- /* Or we could return directly to the forum post. */;
688
+ zTo = zFrom ? 0 : mprintf("%R/forumpost/%S", zTarget);
455689
}else if( zPage ){
456690
if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
457691
login_needed(g.anon.ApndWiki && g.anon.Attach);
458692
return;
459693
}
460694
if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'", zPage) ){
461695
fossil_redirect_home();
462696
}
463697
zTarget = zPage;
464
- zTargetType = mprintf("Wiki Page <a href=\"%R/wiki?name=%h\">%h</a>",
698
+ zTargetType = mprintf("Wiki Page <a href=\"%R/wiki?name=%t\">%h</a>",
465699
zPage, zPage);
700
+ zTo = zFrom ? 0 : mprintf("%R/wiki?name=%T", zTarget);
466701
}else if ( zTechNote ){
467702
if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
468703
login_needed(g.anon.Write && g.anon.ApndWiki && g.anon.Attach);
469704
return;
470705
}
@@ -474,11 +709,11 @@
474709
if( zTechNote==0) fossil_redirect_home();
475710
}
476711
zTarget = zTechNote;
477712
zTargetType = mprintf("Tech Note <a href=\"%R/technote/%s\">%S</a>",
478713
zTechNote, zTechNote);
479
-
714
+ zTo = zFrom ? 0 : mprintf("%R/technote/%S", zTarget);
480715
}else{
481716
assert( zTkt );
482717
if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
483718
login_needed(g.anon.ApndTkt && g.anon.Attach);
484719
return;
@@ -487,21 +722,25 @@
487722
zTkt = db_text(0, "SELECT substr(tagname,5) FROM tag"
488723
" WHERE tagname GLOB 'tkt-%q*'", zTkt);
489724
if( zTkt==0 ) fossil_redirect_home();
490725
}
491726
zTarget = zTkt;
492
- zTargetType = mprintf("Ticket <a href=\"%R/tktview/%s\">%S</a>",
727
+ zTargetType = mprintf("Ticket <a href=\"%R/tktview/%S\">%S</a>",
493728
zTkt, zTkt);
729
+ zTo = zFrom ? 0 : mprintf("%R/tktview/%S", zTarget);
494730
}
495731
szLimit = db_get_int("attachment-size-limit", 0);
496732
if( szContent<0 || (szLimit && szContent>szLimit) ){
497733
/* This check must be done late so that zTargetType is set up. */
498734
@ <p class="generalError">Attachment %h(zName) is too large.
499735
@ <a href="%R/help/attachment-size-limit">Limit</a> is
500736
@ %d(szLimit ? szLimit : 0x7fffffff) bytes</p>
501737
/* Fall through and render form. */
502
- }else if( P("ok") && szContent>0 && (goodCaptcha = captcha_is_correct(0)) ){
738
+ }else if( P("ok")
739
+ && cgi_csrf_safe(2)
740
+ && szContent>0
741
+ && (goodCaptcha = captcha_is_correct(0)) ){
503742
int needModerator = (zForumPost!=0 && forum_need_moderation()) ||
504743
(zTkt!=0 && ticket_need_moderation(0)) ||
505744
(zPage!=0 && wiki_need_moderation(0));
506745
attach_commit(zName, zTarget, aContent, szContent, needModerator, zComment);
507746
cgi_redirect(zTo ? zTo : zFrom);
@@ -511,35 +750,374 @@
511750
style_header("Add Attachment");
512751
if( !goodCaptcha ){
513752
@ <p class="generalError">Error: Incorrect security code.</p>
514753
}
515754
@ <h2>Add Attachment To %s(zTargetType)</h2>
516
- form_begin("enctype='multipart/form-data'", "%R/attachadd");
517
- @ <div>
518
- @ File to Attach:
519
- @ <input type="file" name="f" size="60"><br>
520
- @ Description:<br>
521
- @ <textarea name="comment" cols="80" rows="5" wrap="virtual"\
522
- @ >%h(zComment)</textarea><br>
523
- if( zForumPost ){
524
- @ <input type="hidden" name="forumpost" value="%h(zTarget)">
525
- }else if( zTkt ){
526
- @ <input type="hidden" name="tkt" value="%h(zTkt)">
527
- }else if( zTechNote ){
528
- @ <input type="hidden" name="technote" value="%h(zTechNote)">
755
+ attach_render_legacy_form(zForumPost, zTechNote, zTkt, zPage,
756
+ zComment, zFrom);
757
+ builtin_fossil_js_bundle_or("attach", NULL);
758
+ style_finish_page();
759
+ fossil_free(zTargetType);
760
+ fossil_free(zExtraFree);
761
+}
762
+
763
+/*
764
+** WEBPAGE: attachadd_ajax_post hidden
765
+**
766
+** Used by attachadd V2 to handle attachments via POST requests with:
767
+**
768
+** target=ATTACHMENT_TARGET
769
+** file1..fileN=FILE_OBJECTS
770
+** dryrun=0|1
771
+**
772
+** Each posted file in the set file1..fileN gets attached to the given
773
+** target, permissions permitting. If dryrun>0 then the change is
774
+** rolled back instead of committed. target=X must refer to a full
775
+** target ID, not a prefix.
776
+**
777
+** Responds with JSON: an empty object on success and
778
+** {error:"message"} on error. The on-success response structure is
779
+** subject to amendment.
780
+*/
781
+void attachadd_ajax_post(void){
782
+ const char *zTarget;
783
+ char *zExtraFree = 0;
784
+ int eTgtType = 0;
785
+ int bNeedsModeration = 0;
786
+ int goodCaptcha = 1;
787
+ int bRollback = 0; /* Roll back if true. */
788
+
789
+ if( ! ajax_route_bootstrap(0, 1) ){
790
+ return;
791
+ }else if( !(goodCaptcha = captcha_is_correct(0)) ){
792
+ goto ajax_err_403;
793
+ }else if( !ajax_check_csrf(2) ){
794
+ return;
795
+ }
796
+ db_begin_transaction();
797
+ zTarget = P("target");
798
+ eTgtType = attachment_target_type(zTarget, 1);
799
+ CX("{");
800
+ switch( eTgtType ){
801
+ default:
802
+ case 0:
803
+ ajax_route_error(400, "Invalid attachment target.");
804
+ db_rollback_transaction();
805
+ return;
806
+ case CFTYPE_FORUM:{
807
+ int fpid;
808
+ if( g.perm.AttachForum==0 ){
809
+ goto ajax_err_403;
810
+ }
811
+ fpid = forumpost_head_rid2(zTarget);
812
+ if( fpid<=0 ){
813
+ goto ajax_err_404;
814
+ }else if( !g.perm.Admin && !forumpost_is_owner(fpid, 0) ){
815
+ ajax_route_error(403, "Only admins can attach files to "
816
+ "other users' forum posts.");
817
+ db_rollback_transaction();
818
+ return;
819
+ }
820
+ zTarget = zExtraFree = rid_to_uuid(fpid);
821
+ bNeedsModeration = forum_need_moderation();
822
+ break;
823
+ }
824
+ case CFTYPE_EVENT:{
825
+ if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
826
+ goto ajax_err_403;
827
+ }
828
+ if( !db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",
829
+ zTarget) ){
830
+ zTarget = zExtraFree =
831
+ db_text(0, "SELECT substr(tagname,7) FROM tag"
832
+ " WHERE tagname GLOB 'event-%q*'", zTarget);
833
+ if( zTarget==0){
834
+ goto ajax_err_404;
835
+ }
836
+ }
837
+ bNeedsModeration = 0;
838
+ break;
839
+ }
840
+ case CFTYPE_TICKET:{
841
+ if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
842
+ goto ajax_err_403;
843
+ }
844
+ if( !db_exists("SELECT 1 FROM tag WHERE tagname='tkt-%q'",
845
+ zTarget) ){
846
+ zTarget = db_text(0, "SELECT substr(tagname,5) FROM tag"
847
+ " WHERE tagname GLOB 'tkt-%q*'", zTarget);
848
+ if( zTarget==0 ){
849
+ goto ajax_err_404;
850
+ }
851
+ }
852
+ bNeedsModeration = ticket_need_moderation(0);
853
+ break;
854
+ }
855
+ case CFTYPE_WIKI:{
856
+ if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
857
+ goto ajax_err_403;
858
+ }
859
+ if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",
860
+ zTarget) ){
861
+ goto ajax_err_404;
862
+ }
863
+ bNeedsModeration = wiki_need_moderation(0);
864
+ break;
865
+ }
866
+ }
867
+
868
+ if( attachments_ajax_from_POST(zTarget, bNeedsModeration)>=0 ){
869
+ CX("}");
870
+ if( atoi(PD("dryrun","0"))>0 ){
871
+ bRollback = 1;
872
+ }
873
+ }/*else error response was set up*/
874
+ fossil_free(zExtraFree);
875
+ db_end_transaction(bRollback);
876
+ return;
877
+ajax_err_403:
878
+ if( db_transaction_nesting_depth()>0 ){
879
+ db_rollback_transaction();
880
+ }
881
+ ajax_route_error_forbidden();
882
+ return;
883
+ajax_err_404:
884
+ assert( db_transaction_nesting_depth()>0 );
885
+ db_rollback_transaction();
886
+ ajax_route_error(404, "Target not found.");
887
+ return;
888
+}
889
+
890
+/*
891
+** A helper for AJAX-style routines which accept file attachments via
892
+** POST. zTarget must be a full attachment target. bNeedsModeration
893
+** must be true if the attachment requires moderation.
894
+**
895
+** It is up to the caller to have validated all security measures
896
+** before calling this.
897
+**
898
+** This looks for POSTed files names "file1".."fileN", stopping when
899
+** it finds no entry. Returns the number of entries attached to the
900
+** target or a negative value on error (in which case the current db
901
+** transaction will be in a rollback state).
902
+**
903
+** The only errors are currently attachment size limit violations:
904
+** attachments must have a non-0 size and if the attachment-size-limit
905
+** setting is >0 then each file's size must be <= that.
906
+**
907
+** If this returns a negative value, it will have populated an error
908
+** response using ajax_route_error(). On success it produces no
909
+** output.
910
+**
911
+** ACHTUNG: if zTarget is a forum post, it "really should" be the ID
912
+** of the first version of that post, as that's where attachments are
913
+** intended to be applied so that they can be found and removed
914
+** consistently. Potential TODO is have this function do that if
915
+** attachment_target_type(zTarget,1)!=0 but it would (for current
916
+** uses) require duplicating work already done in the callers.
917
+*/
918
+int attachments_ajax_from_POST(const char *zTarget, int bNeedsModeration){
919
+ int i;
920
+ int rc = 0;
921
+ int n = 0;
922
+ int szLimit; /* attachment-max-size setting */
923
+ char aKeyPrefix[20]; /* Buffer for key "file%d" */
924
+ char aKeySize[30]; /* Buffer for key "file%d:bytes" */
925
+ char aKeyName[30]; /* Buffer for key "file%d:filename" */
926
+ char aKeyDesc[30]; /* Buffer for key "file%d_desc" */
927
+
928
+ db_begin_transaction();
929
+ szLimit = db_get_int("attachment-size-limit", 0);
930
+
931
+ for(i = 1; ; ++i, ++n){
932
+ /* Look for P("fileN"), where N=1..n */
933
+ const char *zContent;
934
+ const char *zFilename;
935
+ int szContent;
936
+ sqlite3_snprintf(sizeof(aKeyPrefix), aKeyPrefix, "file%d", i);
937
+ zContent = P(aKeyPrefix);
938
+ if( !zContent ){
939
+ /* End of the list. */
940
+ break;
941
+ }
942
+ sqlite3_snprintf(sizeof(aKeySize), aKeySize, "%s:bytes",
943
+ aKeyPrefix);
944
+ szContent = atoi(PD(aKeySize,"-1"));
945
+ if( szContent<=0 ){
946
+ rc = -ajax_route_error(400,"Invalid file size: %d", szContent);
947
+ break;
948
+ }else if( szLimit>0 && szContent>szLimit ){
949
+ rc = -ajax_route_error(413, "File size limit is %d bytes.", szLimit);
950
+ break;
951
+ }else{
952
+ sqlite3_snprintf(sizeof(aKeyName), aKeyName, "%s:filename",
953
+ aKeyPrefix);
954
+ sqlite3_snprintf(sizeof(aKeyDesc), aKeyDesc, "%s_desc",
955
+ aKeyPrefix);
956
+ if( 0==(zFilename=P(aKeyName)) ){
957
+ rc = -ajax_route_error(400, "Missing filename.");
958
+ break;
959
+ }
960
+ attach_commit(zFilename, zTarget, zContent, szContent,
961
+ bNeedsModeration, P(aKeyDesc));
962
+ }
963
+ }
964
+ if( rc<0 ){
965
+ db_rollback_transaction();
966
+ return rc;
529967
}else{
530
- @ <input type="hidden" name="page" value="%h(zPage)">
968
+ db_commit_transaction();
969
+ return n;
970
+ }
971
+}
972
+
973
+/*
974
+** Proxy for /attachadd?target=X
975
+**
976
+** Lists attachments for, and can add them to, a target artifact.
977
+**
978
+** target=TKT_HASH|WIKIPAGE_NAME|TECHNOTE_HASH|FORUMPOST_HASH
979
+** from=ORIGINATING_URL
980
+**
981
+** Works like /attachadd but uses a JS-based interactive attachment
982
+** selector.
983
+**
984
+** from=X tells it where to redirect to when it's done.
985
+**
986
+** This page requires a post-2018-ish JS-capable browser.
987
+*/
988
+void attachaddV2_page(void){
989
+ const char *zFrom = P("from");
990
+ const char *zTarget = P("target");
991
+ char *zTo = 0;
992
+ char *zTargetType = 0;
993
+ char *zExtraFree = 0;
994
+ int eTgtType = 0;
995
+ int goodCaptcha = 1;
996
+ char const * noJsArgs[] = {0,0,0,0}; /* Args for noscript form */
997
+
998
+ if( P("cancel") ) cgi_redirect(zFrom);
999
+ if( 0==zTarget ){
1000
+ webpage_error("Requires target=X");
1001
+ }
1002
+ login_check_credentials();
1003
+ eTgtType = attachment_target_type(zTarget, 1);
1004
+ switch( eTgtType ){
1005
+ default:
1006
+ case 0:
1007
+ webpage_error("Cannot resolve target=%h.", zTarget);
1008
+ break;
1009
+ case CFTYPE_FORUM:{
1010
+ int fpid;
1011
+ if( g.perm.AttachForum==0 ){
1012
+ login_needed(g.anon.AttachForum);
1013
+ return;
1014
+ }
1015
+ fpid = forumpost_head_rid2(zTarget);
1016
+ if( fpid<=0 ){
1017
+ webpage_error("Invalid forum post ID: %h", zTarget);
1018
+ }else if( !g.perm.Admin && !forumpost_is_owner(fpid, 0) ){
1019
+ webpage_error("Only admins can attach files to other users' "
1020
+ "forum posts.");
1021
+ }
1022
+ zTarget = zExtraFree = rid_to_uuid(fpid);
1023
+ noJsArgs[0] = zTarget;
1024
+ zTargetType = mprintf(
1025
+ "Forum post <a href=\"%R/forumpost/%S\">%.16h</a>",
1026
+ zTarget, zTarget
1027
+ );
1028
+ zTo = mprintf("%R/forumpost/%S", zTarget);
1029
+ break;
1030
+ }
1031
+ case CFTYPE_EVENT:{
1032
+ if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
1033
+ login_needed(g.anon.Write && g.anon.ApndWiki && g.anon.Attach);
1034
+ return;
1035
+ }
1036
+ if( !db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",
1037
+ zTarget) ){
1038
+ zTarget = db_text(0, "SELECT substr(tagname,7) FROM tag"
1039
+ " WHERE tagname GLOB 'event-%q*'",
1040
+ zTarget);
1041
+ if( zTarget==0) fossil_redirect_home();
1042
+ }
1043
+ zTo = zFrom ? 0 : mprintf("%R/technote?name=%T", zTarget);
1044
+ zTargetType = mprintf("Tech-note <a href=\"%R/technote/%s\">%S</a>",
1045
+ zTarget, zTarget);
1046
+ noJsArgs[1] = zTarget;
1047
+ break;
1048
+ }
1049
+ case CFTYPE_TICKET:{
1050
+ if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
1051
+ login_needed(g.anon.ApndTkt && g.anon.Attach);
1052
+ return;
1053
+ }
1054
+ if( !db_exists("SELECT 1 FROM tag WHERE tagname='tkt-%q'",
1055
+ zTarget) ){
1056
+ zTarget = db_text(0, "SELECT substr(tagname,5) FROM tag"
1057
+ " WHERE tagname GLOB 'tkt-%q*'", zTarget);
1058
+ if( zTarget==0 ) fossil_redirect_home();
1059
+ }
1060
+ zTo = zFrom ? 0 : mprintf("%R/tktview/%t", zTarget);
1061
+ zTargetType = mprintf("Ticket <a href=\"%R/tktview/%s\">%S</a>",
1062
+ zTarget, zTarget);
1063
+ noJsArgs[2] = zTarget;
1064
+ break;
1065
+ }
1066
+ case CFTYPE_WIKI:{
1067
+ if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
1068
+ login_needed(g.anon.ApndWiki && g.anon.Attach);
1069
+ return;
1070
+ }
1071
+ if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",
1072
+ zTarget) ){
1073
+ fossil_redirect_home();
1074
+ }
1075
+ zTo = zFrom ? 0 : mprintf("%R/wiki?name=%T", zTarget);
1076
+ zTargetType = mprintf(
1077
+ "Wiki page <a href=\"%R/wiki?name=%h\">%h</a>",
1078
+ zTarget, zTarget
1079
+ );
1080
+ noJsArgs[3] = zTarget;
1081
+ break;
1082
+ }
1083
+ }
1084
+
1085
+ db_begin_transaction();
1086
+
1087
+ style_set_current_feature("attach");
1088
+ style_header("Add Attachment");
1089
+ if( !goodCaptcha ){
1090
+ @ <p class="generalError">Error: Incorrect security code.</p>
1091
+ }
1092
+ @ <h2>Attachments for %s(zTargetType)</h2>
1093
+ attachment_list(zTarget, NULL,
1094
+ ATTACHLIST_SIZE | ATTACHLIST_HIDE_UNAPPROVED);
1095
+ attach_render_legacy_form(
1096
+ noJsArgs[0], noJsArgs[1], noJsArgs[2],
1097
+ noJsArgs[3], 0,
1098
+ zFrom ? zFrom : (zTo ? zTo : (zTo=mprintf("%R/home")))
1099
+ );
1100
+ @ <div id='attachadd-form-wrapper' class='hidden'>
1101
+ /* fossil.attach.js populates this DIV with the attachment widget,
1102
+ ** imports these hidden fields, and removes the legacy form. */
1103
+ @ <input type="hidden" name="target" value="%h(zTarget)">
1104
+ if( zFrom ){
1105
+ @ <input type="hidden" name="from" value="%h(zFrom)">
5311106
}
532
- @ <input type="hidden" name="from" value="%h(zFrom)">
533
- @ <input type="submit" name="ok" value="Add Attachment">
534
- @ <input type="submit" name="cancel" value="Cancel">
535
- @ </div>
1107
+ if( zTo ){
1108
+ @ <input type="hidden" name="to" value="%h(zTo)">
1109
+ }
5361110
captcha_generate(0);
537
- @ </form>
1111
+ login_insert_csrf_secret();
1112
+ @ </div>
1113
+ builtin_fossil_js_bundle_or("attach", NULL);
1114
+ db_end_transaction(0);
5381115
style_finish_page();
5391116
fossil_free(zTargetType);
5401117
fossil_free(zExtraFree);
1118
+ fossil_free(zTo);
5411119
}
5421120
5431121
/*
5441122
** WEBPAGE: ainfo
5451123
** URL: /ainfo?name=ARTIFACTID
@@ -600,15 +1178,17 @@
6001178
&& db_exists("SELECT 1 FROM ticket WHERE tkt_uuid='%q'", zTarget)
6011179
){
6021180
if( !g.perm.RdTkt ){ login_needed(g.anon.RdTkt); return; }
6031181
zTktUuid = zTarget;
6041182
showDelMenu = g.perm.WrTkt;
605
- }else if( db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",zTarget) ){
1183
+ }else if( db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",
1184
+ zTarget) ){
6061185
if( !g.perm.RdWiki ){ login_needed(g.anon.RdWiki); return; }
6071186
zWikiName = zTarget;
6081187
showDelMenu = g.perm.WrWiki;
609
- }else if( db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",zTarget) ){
1188
+ }else if( db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",
1189
+ zTarget) ){
6101190
if( !g.perm.RdWiki ){ login_needed(g.anon.RdWiki); return; }
6111191
zTNUuid = zTarget;
6121192
showDelMenu = g.perm.Write && g.perm.WrWiki;
6131193
}
6141194
if( showDelMenu ){
@@ -632,11 +1212,13 @@
6321212
Blob cksum;
6331213
const char *zFile = zName;
6341214
6351215
if( !bUserIsOwner ){
6361216
if( zForumPost ? !forumpost_may_close() : !g.perm.Admin ){
637
- webpage_error("Only admins can delete other users' attachments.");
1217
+ webpage_error(
1218
+ "Only admins can delete other users' attachments."
1219
+ );
6381220
}
6391221
}
6401222
db_begin_transaction();
6411223
blob_zero(&manifest);
6421224
for(i=n=0; zFile[i]; i++){
@@ -656,14 +1238,14 @@
6561238
@ <p>The attachment below has been deleted.</p>
6571239
fossil_free(zNewDate);
6581240
}
6591241
6601242
if( P("del")
661
- && ((zForumPost && (bUserIsOwner || forumpost_may_close())) ||
662
- (zTktUuid && g.perm.WrTkt) ||
663
- (zWikiName && g.perm.WrWiki) ||
664
- (zTNUuid && g.perm.Write && g.perm.WrWiki))
1243
+ && ((zForumPost && (bUserIsOwner || forumpost_may_close()))
1244
+ || (zTktUuid && g.perm.WrTkt)
1245
+ || (zWikiName && g.perm.WrWiki)
1246
+ || (zTNUuid && g.perm.Write && g.perm.WrWiki))
6651247
){
6661248
form_begin(0, "%R/ainfo/%!S", zUuid);
6671249
@ <p>Confirm you want to delete the attachment shown below.
6681250
@ <input type="submit" name="confirm" value="Confirm">
6691251
login_insert_csrf_secret();
@@ -711,20 +1293,22 @@
7111293
@ (%d(rid))
7121294
}
7131295
modPending = moderation_pending_www(rid);
7141296
if( zForumPost ){
7151297
@ <tr><th>Forum&nbsp;Post:</th>
716
- @ <td>%z(href("%R/forumpost/%s",zForumPost))%h(zForumPost)</a></td></tr>
1298
+ @ <td>%z(href("%R/forumpost/%s",zForumPost))%h(zForumPost)</a>\
1299
+ @ </td></tr>
7171300
}else if( zTktUuid ){
7181301
@ <tr><th>Ticket:</th>
7191302
@ <td>%z(href("%R/tktview/%s",zTktUuid))%s(zTktUuid)</a></td></tr>
7201303
}else if( zTNUuid ){
7211304
@ <tr><th>Tech Note:</th>
7221305
@ <td>%z(href("%R/technote/%s",zTNUuid))%s(zTNUuid)</a></td></tr>
7231306
}else if( zWikiName ){
7241307
@ <tr><th>Wiki&nbsp;Page:</th>
725
- @ <td>%z(href("%R/wiki?name=%t",zWikiName))%h(zWikiName)</a></td></tr>
1308
+ @ <td>%z(href("%R/wiki?name=%t",zWikiName))%h(zWikiName)</a>\
1309
+ @ </td></tr>
7261310
}
7271311
@ <tr><th>Date:</th><td>
7281312
hyperlink_to_date(zDate, "</td></tr>");
7291313
@ <tr><th>User:</th><td>
7301314
hyperlink_to_user(pAttach->zUser, zDate, "</td></tr>");
@@ -735,22 +1319,42 @@
7351319
}
7361320
@ <tr><th>Filename:</th><td>%h(zName)</td></tr>
7371321
if( g.perm.Setup ){
7381322
@ <tr><th>MIME-Type:</th><td>%h(zMime)</td></tr>
7391323
}
740
- @ <tr><th valign="top">Description:</th><td valign="top">%h(zDesc)</td></tr>
1324
+ @ <tr><th valign="top">Description:</th>\
1325
+ /* FIXME (2026-06-05): Honor the N-card (comment mimetype). */
1326
+ @ <td valign="top">%h(zDesc)</td></tr>
7411327
@ </table>
7421328
7431329
if( modPending && (isModerator || bUserIsOwner) ){
7441330
@ <div class="section">Moderation</div>
7451331
@ <blockquote>
7461332
form_begin(0, "%R/ainfo/%s", zUuid);
7471333
@ <label><input type="radio" name="modaction" value="delete">
7481334
@ Delete this attachment</label><br>
7491335
if( isModerator ){
750
- @ <label><input type="radio" name="modaction" value="approve">
751
- @ Approve this attachment</label><br>
1336
+#if 0
1337
+ /* TODO/FIXME (2026-06-03): only allow approval of an attachment
1338
+ ** if its target has been approved. Without this, we can end up
1339
+ ** with stale attachments which refer to rejected targets. We
1340
+ ** need a type-specific RID/UUID here, which requires
1341
+ ** refactoring above to get it. */
1342
+ const int tgtid = 0;
1343
+ if( moderation_pending(tgtid) ){
1344
+ @ <label><input type="radio" name="modaction" \
1345
+ @ disabled value="approve">
1346
+ @ <span class='modpending'>Cannot approve:
1347
+ @ target is pending moderation</span>\
1348
+ @ </label><br>
1349
+ }else
1350
+#else
1351
+ {
1352
+ @ <label><input type="radio" name="modaction" value="approve">
1353
+ @ Approve this attachment</label><br>
1354
+ }
1355
+#endif
7521356
}
7531357
@ <input type="submit" value="Submit">
7541358
login_insert_csrf_secret();
7551359
@ </form>
7561360
@ </blockquote>
@@ -767,11 +1371,12 @@
7671371
const char *z;
7681372
content_get(ridSrc, &attach);
7691373
blob_to_utf8_no_bom(&attach, 0);
7701374
z = blob_str(&attach);
7711375
if( zLn ){
772
- output_text_with_line_numbers(z, blob_size(&attach), zName, zLn, 1);
1376
+ output_text_with_line_numbers(z, blob_size(&attach),
1377
+ zName, zLn, 1);
7731378
}else{
7741379
@ <pre>
7751380
@ %h(z)
7761381
@ </pre>
7771382
}
@@ -798,10 +1403,13 @@
7981403
*/
7991404
#define ATTACHLIST_HRULE_ABOVE 0x01 /* Insert <hr> above header */
8001405
#define ATTACHLIST_TARGET_BLANK 0x02 /* use target=_blank for links */
8011406
#define ATTACHLIST_SIZE 0x04 /* add size */
8021407
#define ATTACHLIST_HIDE_UNAPPROVED 0x08 /* Hide pending-moderation files */
1408
+#define ATTACHLIST_DETAILS_CLOSED 0x10 /* Wrap in a closed DETAILS element */
1409
+#define ATTACHLIST_DETAILS_OPEN 0x20 /* Wrap in an open DETAILS element */
1410
+#define ATTACHLIST_HIDE_EMPTY 0x40 /* Skip if size<1 */
8031411
#endif
8041412
8051413
/*
8061414
** Output HTML to show a list of attachments.
8071415
*/
@@ -810,19 +1418,25 @@
8101418
const char *zHeader, /* Header to display with attachments */
8111419
const int flags /* ATTACHLIST_... flags */
8121420
){
8131421
int cnt = 0;
8141422
char szBuf[36] = {0}; /* scratchpad for attachment size value */
815
- const char * zLinkTgt = (ATTACHLIST_TARGET_BLANK & flags)
1423
+ const char *zLinkTgt = (ATTACHLIST_TARGET_BLANK & flags)
8161424
? " target=\"_blank\"" : "";
1425
+ const int bUseDetail = flags &
1426
+ (ATTACHLIST_DETAILS_CLOSED | ATTACHLIST_DETAILS_OPEN);
8171427
Stmt q;
1428
+
8181429
db_prepare(&q,
819
- "SELECT datetime(mtime,toLocal()), filename, user,"
820
- " (SELECT uuid FROM blob WHERE rid=attachid), src, target, "
821
- " attachid "
822
- " FROM attachment"
823
- " WHERE isLatest AND src!='' AND target=%Q"
1430
+ "SELECT datetime(mtime,toLocal()), a.filename, a.user,"
1431
+ " b1.uuid, a.src, a.target, a.attachid, b2.size\n"
1432
+ " FROM attachment a, blob b1, blob b2\n"
1433
+ " WHERE a.isLatest\n"
1434
+ " AND a.src IS NOT NULL\n"
1435
+ " AND a.target=%Q\n"
1436
+ " AND b1.rid=a.attachid\n"
1437
+ " AND b2.uuid=a.src\n"
8241438
" ORDER BY mtime DESC",
8251439
zTarget
8261440
);
8271441
while( db_step(&q)==SQLITE_ROW ){
8281442
const char *zDate = db_column_text(&q, 0);
@@ -832,36 +1446,51 @@
8321446
const char *zSrc = db_column_text(&q, 4);
8331447
const char *zTarget = db_column_text(&q, 5);
8341448
const char *zDispUser = zUser && zUser[0] ? zUser : "anonymous";
8351449
const char *zTypeArg = 0; /* URL arg name for /attachdownload */
8361450
const int aid = db_column_int(&q, 6);
837
- const int iAType = attachment_target_type(zTarget);
1451
+ const int sz = db_column_int(&q, 7);
8381452
if( (flags & ATTACHLIST_HIDE_UNAPPROVED)
8391453
&& moderation_pending(aid)
8401454
&& !moderation_user_could(aid, 1, 0) ){
8411455
continue;
1456
+ }
1457
+ if( sz<1 && (flags & ATTACHLIST_HIDE_EMPTY) ){
1458
+ /* Deleted or phantom items. */
1459
+ continue;
8421460
}
8431461
if( cnt==0 ){
844
- @ <section class='attachlist'>
1462
+ if( bUseDetail ){
1463
+ @ <details class='attachlist'
1464
+ if( ATTACHLIST_DETAILS_OPEN & flags ){
1465
+ @ open
1466
+ }
1467
+ @ >
1468
+ }else{
1469
+ @ <section class='attachlist'>
1470
+ }
8451471
if( flags & ATTACHLIST_HRULE_ABOVE ){
8461472
@ <hr>
8471473
}
848
- @ %s(zHeader)
1474
+ if( bUseDetail ){
1475
+ @ <summary>%s(zHeader)</summary>
1476
+ }else{
1477
+ @ %s(zHeader)
1478
+ }
8491479
@ <ul>
8501480
}
8511481
cnt++;
852
- switch( iAType ){
1482
+ switch( attachment_target_type(zTarget, 1) ){
8531483
case CFTYPE_TICKET: zTypeArg = "tkt"; break;
8541484
case CFTYPE_FORUM: zTypeArg = "forumpost"; break;
8551485
case CFTYPE_EVENT: zTypeArg = "technote"; break;
8561486
case CFTYPE_WIKI:
8571487
default: zTypeArg = "page"; break;
8581488
}
8591489
@ <li>
8601490
@ <a href="%R/artifact/%!S(zSrc)"%s(zLinkTgt)>%h(zFile)</a>
8611491
if( flags & ATTACHLIST_SIZE ){
862
- const int sz = db_int(0,"SELECT size FROM blob WHERE uuid=%Q", zSrc);
8631492
sqlite3_snprintf(sizeof(szBuf), szBuf, " %d bytes", sz);
8641493
}
8651494
@ [<a href="%R/attachdownload/%t(zFile)?%s(zTypeArg)=%t(zTarget)\
8661495
@&file=%t(zFile)%s(zLinkTgt)">download</a>%s(szBuf)]
8671496
@ added by %h(zDispUser) on
@@ -870,11 +1499,15 @@
8701499
moderation_pending_www(aid);
8711500
@ </li>
8721501
}
8731502
if( cnt ){
8741503
@ </ul>
875
- @ </section>
1504
+ if( bUseDetail ){
1505
+ @ </details>
1506
+ }else{
1507
+ @ </section>
1508
+ }
8761509
}
8771510
db_finalize(&q);
8781511
}
8791512
8801513
/*
@@ -1023,15 +1656,204 @@
10231656
}
10241657
for(i = 2; i < g.argc; ++i){
10251658
const char *zPage = g.argv[i];
10261659
db_bind_text(&q, ":tgtname", zPage);
10271660
while(SQLITE_ROW == db_step(&q)){
1028
- const char * zTime = db_column_text(&q, 0);
1029
- const char * zSrc = db_column_text(&q, 1);
1030
- const char * zTarget = db_column_text(&q, 2);
1031
- const char * zName = db_column_text(&q, 3);
1661
+ const char *zTime = db_column_text(&q, 0);
1662
+ const char *zSrc = db_column_text(&q, 1);
1663
+ const char *zTarget = db_column_text(&q, 2);
1664
+ const char *zName = db_column_text(&q, 3);
10321665
printf("%-20s %s %.12s %s\n", zTarget, zTime, zSrc, zName);
10331666
}
10341667
db_reset(&q);
10351668
}
10361669
db_finalize(&q);
10371670
}
1671
+
1672
+/*
1673
+** Renders the list of attachments for artifact pManifest as JSON to
1674
+** blob pOut. If pManifest->type is not one of (CFTYPE_TICKET,
1675
+** CFTYPE_FORUM, CFTYPE_EVENT, CFTYPE_WIKI) then it behaves as if the
1676
+** result set is empty.
1677
+**
1678
+** If there are no matching attachments then its behavior depends on
1679
+** emptyPolicy:
1680
+**
1681
+** <0 = emit a JSON NULL
1682
+** 0 = emit no output
1683
+** >0 = emit an empty JSON array
1684
+**
1685
+** If bLatestOnly is true then only the most recent entry for a given
1686
+** attachment is emitted, else all versions are emitted in descending
1687
+** mtime order.
1688
+**
1689
+** Returns the number of attachments.
1690
+**
1691
+** Output format:
1692
+**
1693
+** [{
1694
+** "uuid": attachment artifact hash,
1695
+** "src": hash of the attachment blob,
1696
+** "target": wiki page name or ticket/event ID,
1697
+** "filename": filename of attachment,
1698
+** "mtime": ISO-8601 timestamp UTC,
1699
+** "isLatest": true if this is the latest version of this file
1700
+** else false,
1701
+** }, ...once per attachment]
1702
+**
1703
+*/
1704
+int attachments_to_json(const Manifest *pManifest,
1705
+ Blob *pOut, int bLatestOnly,
1706
+ int emptyPolicy){
1707
+ int i = 0;
1708
+ Stmt q = empty_Stmt;
1709
+ char *zToFree = 0;
1710
+ const char *zTgt = 0;
1711
+ switch(pManifest->type){
1712
+ case CFTYPE_FORUM: zTgt = zToFree = rid_to_uuid(pManifest->rid);
1713
+ break;
1714
+ case CFTYPE_WIKI: zTgt = pManifest->zWikiTitle; break;
1715
+ case CFTYPE_EVENT: zTgt = pManifest->zEventId; break;
1716
+ case CFTYPE_TICKET: zTgt = pManifest->zTicketUuid; break;
1717
+ default:
1718
+ goto empty_result;
1719
+ }
1720
+ db_prepare(&q,
1721
+ "SELECT datetime(mtime), a.src, a.target, a.filename, a.isLatest,\n"
1722
+ " b2.size, b1.uuid, a.user, a.comment\n"
1723
+ " FROM attachment a, blob b1, blob b2\n"
1724
+ " WHERE a.target=%Q\n"
1725
+ " AND a.src IS NOT NULL\n"
1726
+ " AND b1.rid=a.attachid\n"
1727
+ " AND b2.uuid=a.src\n"
1728
+ " AND (a.isLatest OR %d)\n"
1729
+ " ORDER BY a.target, a.isLatest DESC, a.mtime DESC\n",
1730
+ zTgt, !bLatestOnly
1731
+ );
1732
+ while(SQLITE_ROW == db_step(&q)){
1733
+ const char *zTime = db_column_text(&q, 0);
1734
+ const char *zSrc = db_column_text(&q, 1);
1735
+ const char *zTarget = db_column_text(&q, 2);
1736
+ const char *zName = db_column_text(&q, 3);
1737
+ const int isLatest = db_column_int(&q, 4);
1738
+ const int sz = db_column_int(&q, 5);
1739
+ const char *zUuid = db_column_text(&q, 6);
1740
+ const char *zUser = db_column_text(&q, 7);
1741
+ const char *zComment = db_column_text(&q, 8);
1742
+ if(!i++){
1743
+ blob_append_char(pOut, '[');
1744
+ }else{
1745
+ blob_append_char(pOut, ',');
1746
+ }
1747
+ blob_appendf(
1748
+ pOut,
1749
+ "{\"uuid\": %!j, \"src\": %!j, \"target\": %!j, "
1750
+ "\"filename\": %!j, \"size\":%d, \"mtime\": %!j, "
1751
+ "\"isLatest\": %s, \"user\": %!j, \"comment\": ",
1752
+ zUuid, zSrc, zTarget,
1753
+ zName, sz, zTime, isLatest ? "true" : "false",
1754
+ zUser
1755
+ );
1756
+ if( zComment && zComment[0] ){
1757
+ blob_appendf(pOut, "%!j", zComment);
1758
+ }else{
1759
+ blob_append_literal(pOut, "null");
1760
+ }
1761
+ blob_append_char(pOut, '}');
1762
+ }
1763
+ fossil_free(zToFree);
1764
+ db_finalize(&q);
1765
+ if(!i){
1766
+ empty_result:
1767
+ if( emptyPolicy>0 ){
1768
+ blob_append_literal(pOut, "[]");
1769
+ }else if( emptyPolicy<0 ){
1770
+ blob_append_literal(pOut, "null");
1771
+ }
1772
+ }else{
1773
+ blob_append_char(pOut, ']');
1774
+ }
1775
+ return i;
1776
+}
1777
+
1778
+/*
1779
+** COMMAND: test-attachment-target
1780
+**
1781
+** Usage: %fossil test-attachment-target TARGET_ID...
1782
+*/
1783
+void test_attachment_target_type_cmd(void){
1784
+ int i;
1785
+ verify_all_options();
1786
+ db_find_and_open_repository(0, 0);
1787
+ if( g.argc<3 ){
1788
+ usage("test-attachment-target TARGET_ID");
1789
+ return;
1790
+ }
1791
+ for( i = 2; i < g.argc; ++i ){
1792
+ const char *zTarget = g.argv[i];
1793
+ const int rid = attachment_target_rid(zTarget, 0);
1794
+ const int type = attachment_target_type(zTarget, 0);
1795
+ const char *zType = "<invalid>";
1796
+ switch(type){
1797
+ case CFTYPE_EVENT: zType = "technote"; break;
1798
+ case CFTYPE_FORUM: zType = "forumpost"; break;
1799
+ case CFTYPE_TICKET: zType = "ticket"; break;
1800
+ case CFTYPE_WIKI: zType = "wiki"; break;
1801
+ }
1802
+ fossil_print("%-20s = %-9s #%d %z\n",
1803
+ zTarget, zType, rid,
1804
+ rid>0 ? rid_to_uuid(rid) : 0);
1805
+ }
1806
+}
1807
+
1808
+
1809
+/*
1810
+** COMMAND: test-attachments-to-json
1811
+**
1812
+** Usage: %fossil test-attachments-to-json TARGET_ID...
1813
+**
1814
+** Options:
1815
+** --old List all versions of attachments. Default is to
1816
+** list only the latest.
1817
+** --full Require a full target ID, not a prefix.
1818
+**
1819
+** Emits a JSON array of attachments for the given attachment targets.
1820
+** The given IDs must be wiki page names, ticket hashes, tech-note
1821
+** hashes, or forum post hashes. By default it accepts hash prefixes
1822
+** but does no detection of ambiguity or cross-type prefix collisions
1823
+** so may emit curious results if given short, colliding IDs.
1824
+*/
1825
+void test_attachments_to_json_cmd(void){
1826
+ const int emptyPolicy = 1;
1827
+ const int bLatestOnly = find_option("old",0,0)==0;
1828
+ const int bFullId = find_option("full",0,0)!=0;
1829
+ int i;
1830
+
1831
+ verify_all_options();
1832
+ db_find_and_open_repository(0, 0);
1833
+ if( g.argc<3 ){
1834
+ usage("test-attachments-to-json TARGET_ID");
1835
+ return;
1836
+ }
1837
+ for( i = 2; i < g.argc; ++i ){
1838
+ const char *zTarget = g.argv[i];
1839
+ const int rid = attachment_target_rid(zTarget, bFullId);
1840
+ if( 0==rid ){
1841
+ fossil_print("** cannot resolve %s\n", zTarget);
1842
+ }else{
1843
+ Blob b = BLOB_INITIALIZER;
1844
+ Manifest *pManifest = manifest_get(rid, CFTYPE_ANY, NULL);
1845
+ assert( pManifest );
1846
+ attachments_to_json(pManifest, &b, bLatestOnly, emptyPolicy);
1847
+ fossil_print("Attachments for %s: ", zTarget);
1848
+ if( b.nUsed ){
1849
+ char *zPretty = db_text(0,"SELECT json_pretty(%B)", &b);
1850
+ fossil_print("%s\n", zPretty);
1851
+ fossil_free(zPretty);
1852
+ }else{
1853
+ fossil_print("none\n");
1854
+ }
1855
+ blob_reset(&b);
1856
+ manifest_destroy(pManifest);
1857
+ }
1858
+ }
1859
+}
10381860
--- src/attach.c
+++ src/attach.c
@@ -22,41 +22,188 @@
22 #include <assert.h>
23
24 /*
25 ** Given a presumedly legal attachment target name, this guesses the
26 ** target type and returns one of CFTYPE_FORUM, CFTYPE_WIKI,
27 ** CFTYPE_TICKET, or CFTYPE_EVENT. Returns 0 if it cannot
28 ** distinguish the target type.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29 **
30 ** In the case of CFTYPE_FORUM, it is up to the caller to ensure that,
31 ** if needed, they resolve zTarget using forumpost_head_rid2() so that
32 ** they get the RID of the earliest version of the post, as that is
33 ** the only one which attachments should target.
 
34 */
35 int attachment_target_type(const char *zTarget){
36 static Stmt q = empty_Stmt_m;
37 int rc = 0;
38 if( forumpost_head_rid2(zTarget)>0 ){
 
 
 
 
39 return CFTYPE_FORUM;
40 }
41 if( !q.pStmt ){
42 db_static_prepare(
43 &q,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44 "SELECT CASE "
45 "WHEN 'tkt-'||:tgt IN (SELECT tagname FROM tag) THEN %d "
46 "WHEN 'event-'||:tgt IN (SELECT tagname FROM tag) THEN %d "
47 "WHEN 'wiki-'||:tgt IN (SELECT tagname FROM tag) THEN %d "
 
 
 
48 "ELSE 0 END",
49 CFTYPE_TICKET, CFTYPE_EVENT, CFTYPE_WIKI
 
 
50 );
51 }
52 db_bind_text(&q, ":tgt", zTarget);
53 if( SQLITE_ROW==db_step(&q) ){
54 rc = db_column_int(&q, 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55 }
56 db_reset(&q);
57 return rc;
 
 
 
 
 
 
 
 
 
 
 
58 }
59
60 /*
61 ** WEBPAGE: attachlist
62 ** List attachments.
@@ -69,20 +216,21 @@
69 ** At most one of technote=, tkt=, forumpost=, or page= may be supplied.
70 **
71 ** If none are given, all attachments are listed. If one is given, only
72 ** attachments for the designated technote, ticket or wiki page are shown.
73 **
74 ** HASH may be just a prefix of the relevant technical note or ticket
75 ** artifact hash, in which case all attachments of all technical notes or
76 ** tickets with the prefix will be listed. Forum posts, on the other hand,
77 ** require a unique hash prefix.
78 */
79 void attachlist_page(void){
80 const char *zPage = P("page");
81 const char *zTkt = P("tkt");
82 const char *zTechNote = P("technote");
83 const char *zForumPost = P("forumpost");
 
84 Blob sql;
85 Stmt q;
86
87 if( zPage && zTkt ) zTkt = 0;
88 login_check_credentials();
@@ -102,32 +250,47 @@
102 if( fnid<=0 ){
103 webpage_error("Invalid forum post ID: %h", zForumPost);
104 }
105 blob_append_sql(&sql, " WHERE target="
106 "(SELECT uuid FROM blob WHERE rid=%d)", fnid);
 
 
107 }else if( zPage ){
108 if( g.perm.RdWiki==0 ){ login_needed(g.anon.RdWiki); return; }
109 style_header("Attachments To Wiki page %h", zPage);
110 blob_append_sql(&sql, " WHERE target=%Q", zPage);
 
 
111 }else if( zTkt ){
112 if( g.perm.RdTkt==0 ){ login_needed(g.anon.RdTkt); return; }
113 style_header("Attachments To Ticket %S", zTkt);
114 blob_append_sql(&sql, " WHERE target GLOB '%q*'", zTkt);
 
 
115 }else if( zTechNote ){
116 if( g.perm.RdWiki==0 ){ login_needed(g.anon.RdWiki); return; }
117 style_header("Attachments To Tech Note %S", zTechNote);
118 blob_append_sql(&sql, " WHERE target GLOB '%q*'",
119 zTechNote);
 
 
120 }else{
121 if( g.perm.RdTkt==0 && g.perm.RdWiki==0 ){
122 login_needed(g.anon.RdTkt || g.anon.RdWiki);
123 return;
124 }
125 style_header("All Attachments");
126 }
127 blob_append_sql(&sql, " ORDER BY mtime DESC");
128 db_prepare(&q, "%s", blob_sql_text(&sql));
 
 
 
 
 
 
 
129 @ <ol>
130 while( db_step(&q)==SQLITE_ROW ){
131 const char *zDate;
132 const char *zSrc;
133 const char *zTarget;
@@ -137,10 +300,11 @@
137 const char *zUuid;
138 const char *zDispUser;
139 const int attachid = db_column_int(&q, 7);
140 int type;
141 int i;
 
142 char *zUrlTail = 0;
143
144 if( moderation_pending(attachid)
145 && !moderation_user_could(attachid, 1, 0) ){
146 /* Elide entries which are currently pending moderation unless
@@ -160,11 +324,12 @@
160 if( zFilename[i]=='/' && zFilename[i+1]!=0 ){
161 zFilename = &zFilename[i+1];
162 i = -1;
163 }
164 }
165 type = attachment_target_type(zTarget);
 
166 switch( type ){
167 case CFTYPE_TICKET:
168 zUrlTail = mprintf("tkt=%s&file=%t", zTarget, zFilename);
169 break;
170 case CFTYPE_EVENT:
@@ -176,20 +341,32 @@
176 case CFTYPE_WIKI:
177 zUrlTail = mprintf("page=%t&file=%t", zTarget, zFilename);
178 break;
179 }
180 @ <li><p>
181 @ Attachment %z(href("%R/ainfo/%!S",zUuid))%S(zUuid)</a>
 
 
 
182 moderation_pending_www(attachid);
183 @ <br><a href="%R/attachview?%s(zUrlTail)">%h(zFilename)</a>
184 @ [<a href="%R/attachdownload/%t(zFilename)?%s(zUrlTail)">download</a>]<br>
 
 
 
 
 
185 if( zComment ) while( fossil_isspace(zComment[0]) ) zComment++;
186 if( zComment && zComment[0] ){
187 @ %!W(zComment)<br>
 
 
 
 
188 }
189 if( zForumPost==0 && zPage==0 && zTkt==0 && zTechNote==0 ){
190 if( zSrc==0 || zSrc[0]==0 ){
191 zSrc = "Deleted from";
192 }else {
193 zSrc = "Added to";
194 }
195 switch( type ){
@@ -362,41 +539,81 @@
362 Manifest *pManifest;
363
364 db_begin_transaction();
365 blob_init(&content, aContent, szContent);
366 pManifest = manifest_parse(&content, 0, 0);
 
367 manifest_destroy(pManifest);
368 blob_init(&content, aContent, szContent);
369 if( pManifest ){
370 blob_compress(&content, &content);
371 addCompress = 1;
372 }
373 rid = content_put_ex(&content, 0, 0, 0, needModerator);
374 zUUID = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", rid);
375 blob_zero(&manifest);
376 for(i=n=0; zName[i]; i++){
377 if( zName[i]=='/' || zName[i]=='\\' ) n = i+1;
378 }
379 zName += n;
380 if( zName[0]==0 ) zName = "unknown";
381 blob_appendf(&manifest, "A %F%s %F %s\n",
382 zName, addCompress ? ".gz" : "", zTarget, zUUID);
383 while( fossil_isspace(zComment[0]) ) zComment++;
384 n = strlen(zComment);
385 while( n>0 && fossil_isspace(zComment[n-1]) ){ n--; }
386 if( n>0 ){
387 blob_appendf(&manifest, "C %#F\n", n, zComment);
 
 
388 }
389 zDate = date_in_standard_format("now");
390 blob_appendf(&manifest, "D %s\n", zDate);
391 blob_appendf(&manifest, "U %F\n", login_name());
392 md5sum_blob(&manifest, &cksum);
393 blob_appendf(&manifest, "Z %b\n", &cksum);
394 attach_put(&manifest, rid, needModerator);
395 assert( blob_is_reset(&manifest) );
396 db_end_transaction(0);
397 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
399 /*
400 ** WEBPAGE: attachadd
401 ** Add a new attachment.
402 **
@@ -404,33 +621,54 @@
404 ** page=WIKIPAGE
405 ** technote=HASH
406 ** forumpost=HASH
407 ** from=URL
408 **
 
 
 
 
 
 
 
409 */
410 void attachadd_page(void){
411 const char *zPage = P("page");
412 const char *zForumPost = P("forumpost");
413 const char *zTkt = P("tkt");
414 const char *zTechNote = P("technote");
415 const char *zFrom = P("from");
416 const char *aContent = P("f");
417 const char *zName = PD("f:filename","unknown");
418 const char *zComment = PD("comment", "");
419 const char *zTarget;
420 char * zTo = 0;
 
421 char *zTargetType = 0;
422 char *zExtraFree = 0;
423 int szContent = atoi(PD("f:bytes","0"));
424 int goodCaptcha = 1;
425 int szLimit = 0;
426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427 if( zFrom==0 ) zFrom = mprintf("%R/home");
428 if( P("cancel") ) cgi_redirect(zFrom);
429 if( (!!zPage + !!zTkt + !!zTechNote + !!zForumPost)!=1 ){
430 webpage_error("Requires exactly one one: page=X, tkt=X, forumpost=X,"
431 " or technote=X");
432 }
433 login_check_credentials();
434 if( zForumPost ){
435 int fpid;
436 if( g.perm.AttachForum==0 ){
@@ -445,26 +683,23 @@
445 "forum posts.");
446 }
447 zTarget = zExtraFree = rid_to_uuid(fpid);
448 zTargetType = mprintf("Forum post <a href=\"%R/forumpost/%S\">%h</a>",
449 zTarget, zForumPost);
450 zTo = 1
451 ? mprintf("%R/forumpost/%S", zTarget)
452 : mprintf("%R/attachview?forumpost=%T&file=%T",
453 zTarget, zName)
454 /* Or we could return directly to the forum post. */;
455 }else if( zPage ){
456 if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
457 login_needed(g.anon.ApndWiki && g.anon.Attach);
458 return;
459 }
460 if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'", zPage) ){
461 fossil_redirect_home();
462 }
463 zTarget = zPage;
464 zTargetType = mprintf("Wiki Page <a href=\"%R/wiki?name=%h\">%h</a>",
465 zPage, zPage);
 
466 }else if ( zTechNote ){
467 if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
468 login_needed(g.anon.Write && g.anon.ApndWiki && g.anon.Attach);
469 return;
470 }
@@ -474,11 +709,11 @@
474 if( zTechNote==0) fossil_redirect_home();
475 }
476 zTarget = zTechNote;
477 zTargetType = mprintf("Tech Note <a href=\"%R/technote/%s\">%S</a>",
478 zTechNote, zTechNote);
479
480 }else{
481 assert( zTkt );
482 if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
483 login_needed(g.anon.ApndTkt && g.anon.Attach);
484 return;
@@ -487,21 +722,25 @@
487 zTkt = db_text(0, "SELECT substr(tagname,5) FROM tag"
488 " WHERE tagname GLOB 'tkt-%q*'", zTkt);
489 if( zTkt==0 ) fossil_redirect_home();
490 }
491 zTarget = zTkt;
492 zTargetType = mprintf("Ticket <a href=\"%R/tktview/%s\">%S</a>",
493 zTkt, zTkt);
 
494 }
495 szLimit = db_get_int("attachment-size-limit", 0);
496 if( szContent<0 || (szLimit && szContent>szLimit) ){
497 /* This check must be done late so that zTargetType is set up. */
498 @ <p class="generalError">Attachment %h(zName) is too large.
499 @ <a href="%R/help/attachment-size-limit">Limit</a> is
500 @ %d(szLimit ? szLimit : 0x7fffffff) bytes</p>
501 /* Fall through and render form. */
502 }else if( P("ok") && szContent>0 && (goodCaptcha = captcha_is_correct(0)) ){
 
 
 
503 int needModerator = (zForumPost!=0 && forum_need_moderation()) ||
504 (zTkt!=0 && ticket_need_moderation(0)) ||
505 (zPage!=0 && wiki_need_moderation(0));
506 attach_commit(zName, zTarget, aContent, szContent, needModerator, zComment);
507 cgi_redirect(zTo ? zTo : zFrom);
@@ -511,35 +750,374 @@
511 style_header("Add Attachment");
512 if( !goodCaptcha ){
513 @ <p class="generalError">Error: Incorrect security code.</p>
514 }
515 @ <h2>Add Attachment To %s(zTargetType)</h2>
516 form_begin("enctype='multipart/form-data'", "%R/attachadd");
517 @ <div>
518 @ File to Attach:
519 @ <input type="file" name="f" size="60"><br>
520 @ Description:<br>
521 @ <textarea name="comment" cols="80" rows="5" wrap="virtual"\
522 @ >%h(zComment)</textarea><br>
523 if( zForumPost ){
524 @ <input type="hidden" name="forumpost" value="%h(zTarget)">
525 }else if( zTkt ){
526 @ <input type="hidden" name="tkt" value="%h(zTkt)">
527 }else if( zTechNote ){
528 @ <input type="hidden" name="technote" value="%h(zTechNote)">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529 }else{
530 @ <input type="hidden" name="page" value="%h(zPage)">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531 }
532 @ <input type="hidden" name="from" value="%h(zFrom)">
533 @ <input type="submit" name="ok" value="Add Attachment">
534 @ <input type="submit" name="cancel" value="Cancel">
535 @ </div>
536 captcha_generate(0);
537 @ </form>
 
 
 
538 style_finish_page();
539 fossil_free(zTargetType);
540 fossil_free(zExtraFree);
 
541 }
542
543 /*
544 ** WEBPAGE: ainfo
545 ** URL: /ainfo?name=ARTIFACTID
@@ -600,15 +1178,17 @@
600 && db_exists("SELECT 1 FROM ticket WHERE tkt_uuid='%q'", zTarget)
601 ){
602 if( !g.perm.RdTkt ){ login_needed(g.anon.RdTkt); return; }
603 zTktUuid = zTarget;
604 showDelMenu = g.perm.WrTkt;
605 }else if( db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",zTarget) ){
 
606 if( !g.perm.RdWiki ){ login_needed(g.anon.RdWiki); return; }
607 zWikiName = zTarget;
608 showDelMenu = g.perm.WrWiki;
609 }else if( db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",zTarget) ){
 
610 if( !g.perm.RdWiki ){ login_needed(g.anon.RdWiki); return; }
611 zTNUuid = zTarget;
612 showDelMenu = g.perm.Write && g.perm.WrWiki;
613 }
614 if( showDelMenu ){
@@ -632,11 +1212,13 @@
632 Blob cksum;
633 const char *zFile = zName;
634
635 if( !bUserIsOwner ){
636 if( zForumPost ? !forumpost_may_close() : !g.perm.Admin ){
637 webpage_error("Only admins can delete other users' attachments.");
 
 
638 }
639 }
640 db_begin_transaction();
641 blob_zero(&manifest);
642 for(i=n=0; zFile[i]; i++){
@@ -656,14 +1238,14 @@
656 @ <p>The attachment below has been deleted.</p>
657 fossil_free(zNewDate);
658 }
659
660 if( P("del")
661 && ((zForumPost && (bUserIsOwner || forumpost_may_close())) ||
662 (zTktUuid && g.perm.WrTkt) ||
663 (zWikiName && g.perm.WrWiki) ||
664 (zTNUuid && g.perm.Write && g.perm.WrWiki))
665 ){
666 form_begin(0, "%R/ainfo/%!S", zUuid);
667 @ <p>Confirm you want to delete the attachment shown below.
668 @ <input type="submit" name="confirm" value="Confirm">
669 login_insert_csrf_secret();
@@ -711,20 +1293,22 @@
711 @ (%d(rid))
712 }
713 modPending = moderation_pending_www(rid);
714 if( zForumPost ){
715 @ <tr><th>Forum&nbsp;Post:</th>
716 @ <td>%z(href("%R/forumpost/%s",zForumPost))%h(zForumPost)</a></td></tr>
 
717 }else if( zTktUuid ){
718 @ <tr><th>Ticket:</th>
719 @ <td>%z(href("%R/tktview/%s",zTktUuid))%s(zTktUuid)</a></td></tr>
720 }else if( zTNUuid ){
721 @ <tr><th>Tech Note:</th>
722 @ <td>%z(href("%R/technote/%s",zTNUuid))%s(zTNUuid)</a></td></tr>
723 }else if( zWikiName ){
724 @ <tr><th>Wiki&nbsp;Page:</th>
725 @ <td>%z(href("%R/wiki?name=%t",zWikiName))%h(zWikiName)</a></td></tr>
 
726 }
727 @ <tr><th>Date:</th><td>
728 hyperlink_to_date(zDate, "</td></tr>");
729 @ <tr><th>User:</th><td>
730 hyperlink_to_user(pAttach->zUser, zDate, "</td></tr>");
@@ -735,22 +1319,42 @@
735 }
736 @ <tr><th>Filename:</th><td>%h(zName)</td></tr>
737 if( g.perm.Setup ){
738 @ <tr><th>MIME-Type:</th><td>%h(zMime)</td></tr>
739 }
740 @ <tr><th valign="top">Description:</th><td valign="top">%h(zDesc)</td></tr>
 
 
741 @ </table>
742
743 if( modPending && (isModerator || bUserIsOwner) ){
744 @ <div class="section">Moderation</div>
745 @ <blockquote>
746 form_begin(0, "%R/ainfo/%s", zUuid);
747 @ <label><input type="radio" name="modaction" value="delete">
748 @ Delete this attachment</label><br>
749 if( isModerator ){
750 @ <label><input type="radio" name="modaction" value="approve">
751 @ Approve this attachment</label><br>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752 }
753 @ <input type="submit" value="Submit">
754 login_insert_csrf_secret();
755 @ </form>
756 @ </blockquote>
@@ -767,11 +1371,12 @@
767 const char *z;
768 content_get(ridSrc, &attach);
769 blob_to_utf8_no_bom(&attach, 0);
770 z = blob_str(&attach);
771 if( zLn ){
772 output_text_with_line_numbers(z, blob_size(&attach), zName, zLn, 1);
 
773 }else{
774 @ <pre>
775 @ %h(z)
776 @ </pre>
777 }
@@ -798,10 +1403,13 @@
798 */
799 #define ATTACHLIST_HRULE_ABOVE 0x01 /* Insert <hr> above header */
800 #define ATTACHLIST_TARGET_BLANK 0x02 /* use target=_blank for links */
801 #define ATTACHLIST_SIZE 0x04 /* add size */
802 #define ATTACHLIST_HIDE_UNAPPROVED 0x08 /* Hide pending-moderation files */
 
 
 
803 #endif
804
805 /*
806 ** Output HTML to show a list of attachments.
807 */
@@ -810,19 +1418,25 @@
810 const char *zHeader, /* Header to display with attachments */
811 const int flags /* ATTACHLIST_... flags */
812 ){
813 int cnt = 0;
814 char szBuf[36] = {0}; /* scratchpad for attachment size value */
815 const char * zLinkTgt = (ATTACHLIST_TARGET_BLANK & flags)
816 ? " target=\"_blank\"" : "";
 
 
817 Stmt q;
 
818 db_prepare(&q,
819 "SELECT datetime(mtime,toLocal()), filename, user,"
820 " (SELECT uuid FROM blob WHERE rid=attachid), src, target, "
821 " attachid "
822 " FROM attachment"
823 " WHERE isLatest AND src!='' AND target=%Q"
 
 
 
824 " ORDER BY mtime DESC",
825 zTarget
826 );
827 while( db_step(&q)==SQLITE_ROW ){
828 const char *zDate = db_column_text(&q, 0);
@@ -832,36 +1446,51 @@
832 const char *zSrc = db_column_text(&q, 4);
833 const char *zTarget = db_column_text(&q, 5);
834 const char *zDispUser = zUser && zUser[0] ? zUser : "anonymous";
835 const char *zTypeArg = 0; /* URL arg name for /attachdownload */
836 const int aid = db_column_int(&q, 6);
837 const int iAType = attachment_target_type(zTarget);
838 if( (flags & ATTACHLIST_HIDE_UNAPPROVED)
839 && moderation_pending(aid)
840 && !moderation_user_could(aid, 1, 0) ){
841 continue;
 
 
 
 
842 }
843 if( cnt==0 ){
844 @ <section class='attachlist'>
 
 
 
 
 
 
 
 
845 if( flags & ATTACHLIST_HRULE_ABOVE ){
846 @ <hr>
847 }
848 @ %s(zHeader)
 
 
 
 
849 @ <ul>
850 }
851 cnt++;
852 switch( iAType ){
853 case CFTYPE_TICKET: zTypeArg = "tkt"; break;
854 case CFTYPE_FORUM: zTypeArg = "forumpost"; break;
855 case CFTYPE_EVENT: zTypeArg = "technote"; break;
856 case CFTYPE_WIKI:
857 default: zTypeArg = "page"; break;
858 }
859 @ <li>
860 @ <a href="%R/artifact/%!S(zSrc)"%s(zLinkTgt)>%h(zFile)</a>
861 if( flags & ATTACHLIST_SIZE ){
862 const int sz = db_int(0,"SELECT size FROM blob WHERE uuid=%Q", zSrc);
863 sqlite3_snprintf(sizeof(szBuf), szBuf, " %d bytes", sz);
864 }
865 @ [<a href="%R/attachdownload/%t(zFile)?%s(zTypeArg)=%t(zTarget)\
866 @&file=%t(zFile)%s(zLinkTgt)">download</a>%s(szBuf)]
867 @ added by %h(zDispUser) on
@@ -870,11 +1499,15 @@
870 moderation_pending_www(aid);
871 @ </li>
872 }
873 if( cnt ){
874 @ </ul>
875 @ </section>
 
 
 
 
876 }
877 db_finalize(&q);
878 }
879
880 /*
@@ -1023,15 +1656,204 @@
1023 }
1024 for(i = 2; i < g.argc; ++i){
1025 const char *zPage = g.argv[i];
1026 db_bind_text(&q, ":tgtname", zPage);
1027 while(SQLITE_ROW == db_step(&q)){
1028 const char * zTime = db_column_text(&q, 0);
1029 const char * zSrc = db_column_text(&q, 1);
1030 const char * zTarget = db_column_text(&q, 2);
1031 const char * zName = db_column_text(&q, 3);
1032 printf("%-20s %s %.12s %s\n", zTarget, zTime, zSrc, zName);
1033 }
1034 db_reset(&q);
1035 }
1036 db_finalize(&q);
1037 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1038
--- src/attach.c
+++ src/attach.c
@@ -22,41 +22,188 @@
22 #include <assert.h>
23
24 /*
25 ** Given a presumedly legal attachment target name, this guesses the
26 ** target type and returns one of CFTYPE_FORUM, CFTYPE_WIKI,
27 ** CFTYPE_TICKET, or CFTYPE_EVENT. Returns 0 if it cannot distinguish
28 ** the target type.
29 **
30 ** zTarget is an attachment target name: wiki page name, tech-note ID,
31 ** ticket ID, or forumpost hash.
32 **
33 ** If bFull is true then it requires zTarget to be a full ID for
34 ** tech-notes and tickets, otherwise such IDs may be prefixes. If
35 ** bFull is false then tech-notes and tickets will perform a prefix
36 ** match, but it is up to the caller to provide enough of a prefix to
37 ** rule out ambiguity[^1]. When called repeatedly, this routine can
38 ** run a bit faster and more efficiently if bFull is true, but some
39 ** historical use cases call for prefix matches.
40 **
41 ** Wiki page names always require an exact match.
42 **
43 ** Forum posts are a special case:
44 **
45 ** - They ignore the bFull flag. That is, they will do prefix matches
46 ** but will not match an ambiguous prefix.
47 **
48 ** - It is up to the caller to, if needed, resolve zTarget using
49 ** forumpost_head_rid2() to resolve the RID of the earliest version
50 ** of the post, as that is the only one which attachments should
51 ** target.
52 **
53 ** [^1]: Historically (from the perspective of 2026-06) attachment
54 ** target lookups have used GLOB prefix matching but have taken no
55 ** measures to ensure that the prefix is unambiguous. Ergo we do the
56 ** same here. It is assumed that the caller passes enough of a prefix
57 ** to be unambiguous and that's worked out fine so far.
58 */
59 int attachment_target_type(const char *zTarget, int bFull){
60 if( !zTarget || !zTarget[0] || strlen(zTarget)>64/*vs. abuse*/ ){
61 return 0;
62 }
63 if( symbolic_name_to_rid(zTarget, "f")>0 ){
64 /* Check forum posts first because they are the most likely target
65 ** as of 2026. We should arguably use something more
66 ** specialized/efficient than symbolic_name_to_rid(). */
67 return CFTYPE_FORUM;
68 }
69 if( bFull ){
70 static Stmt q = empty_Stmt_m;
71 int rc = 0;
72 if( !q.pStmt ){
73 db_static_prepare(
74 &q,
75 "SELECT CASE "
76 /* Ordered by presumed likelihood of attachments. */
77 "WHEN (SELECT 1 FROM tag WHERE tagname='tkt-'||:tgt) THEN %d\n"
78 "WHEN (SELECT 1 FROM tag WHERE tagname='wiki-'||:tgt) THEN %d\n"
79 "WHEN (SELECT 1 FROM tag WHERE tagname='event-'||:tgt) THEN %d\n"
80 "ELSE 0 END",
81 CFTYPE_TICKET, CFTYPE_WIKI, CFTYPE_EVENT
82 );
83 }
84 db_bind_text(&q, ":tgt", zTarget);
85 if( SQLITE_ROW==db_step(&q) ){
86 rc = db_column_int(&q, 0);
87 }
88 db_reset(&q);
89 return rc;
90 }else{
91 return db_int(
92 0,
93 "SELECT CASE "
94 "WHEN (SELECT tagid FROM tag WHERE tagname GLOB 'tkt-%q*')"
95 " THEN %d\n"
96 "WHEN (SELECT tagid FROM tag WHERE tagname='wiki-%q')"
97 " THEN %d\n"
98 "WHEN (SELECT tagid FROM tag WHERE tagname GLOB 'event-%q*')"
99 " THEN %d\n"
100 "ELSE 0 END",
101 zTarget, CFTYPE_TICKET,
102 zTarget, CFTYPE_WIKI,
103 zTarget, CFTYPE_EVENT
104 );
105 }
106 }
107
108 /*
109 ** Given an attachment target name, returns the target's blob.rid.
110 ** zTarget and bFull work as described for attachment_target_type().
111 **
112 ** For forum posts, this always returns the RID of the first version
113 ** of the post, as attachments should always target that instance.
114 */
115 int attachment_target_rid(const char *zTarget, int bFull){
116 int rid = 0;
117 const int eType = attachment_target_type(zTarget, bFull);
118 switch(eType){
119 case CFTYPE_TICKET:
120 case CFTYPE_EVENT:{
121 const char *zTagPrefix = (eType==CFTYPE_EVENT) ? "event" : "tkt";
122 rid = db_int(
123 0, "SELECT b.rid FROM blob b, tag t, tagxref x\n"
124 "WHERE tagname %s '%s-%q%s'\n"
125 "AND x.tagtype>0\n"
126 "AND x.tagid=t.tagid\n"
127 "AND x.rid=b.rid\n"
128 "ORDER BY x.mtime DESC",
129 bFull ? "=" : "GLOB"/*safe-for-%s*/,
130 zTagPrefix/*safe-for-%s*/,
131 zTarget,
132 bFull ? "" : "*"/*safe-for-%s*/
133 );
134 break;
135 }
136 case CFTYPE_FORUM:
137 rid = db_int(
138 0, "SELECT f.fpid FROM forumpost f, blob b\n"
139 "WHERE f.fpid=b.rid\n"
140 "AND b.uuid %s '%q%s'",
141 bFull ? "=" : "GLOB"/*safe-for-%s*/,
142 zTarget,
143 bFull ? "" : "*"/*safe-for-%s*/
144 );
145 if( rid>0 ){
146 rid = forumpost_head_rid(rid);
147 }
148 break;
149 case CFTYPE_WIKI:
150 rid = db_int(
151 0, "SELECT b.rid FROM blob b, tag t, tagxref x\n"
152 "WHERE tagname='wiki-%q'\n"
153 "AND x.tagtype>0\n"
154 "AND x.tagid=t.tagid\n"
155 "AND x.rid=b.rid\n"
156 "ORDER BY x.mtime DESC",
157 zTarget
158 );
159 break;
160 default:
161 break;
162 }
163 return rid;
164 }
165
166 /*
167 ** For a given aritfact ID and type (from the CFTYPE_xyz enum),
168 ** returns true if the current user could hypothetically apply and
169 ** attachment to it, else returns 0.
170 **
171 ** The rid is currently only relevant when eArtifactType is
172 ** CFTYPE_FORUM. For forum posts, it checks precisely the rid given,
173 ** not the head RID, to keep non-admins from attaching files to
174 ** threads which have since been taken over by another user (this
175 ** happens when an admin edits another user's post).
176 */
177 int attach_user_may(int rid, int eArtifactType){
178 if( g.perm.Admin ) return 1;
179 if( !login_is_individual() ) return 0;
180 switch(eArtifactType){
181 case CFTYPE_FORUM:
182 return g.perm.AttachForum && forumpost_is_owner(rid, 0);
183 case CFTYPE_WIKI:
184 return g.perm.ApndWiki && g.perm.Attach;
185 case CFTYPE_TICKET:
186 return g.perm.ApndTkt && g.perm.Attach;
187 case CFTYPE_EVENT:
188 return g.perm.Write && g.perm.ApndWiki && g.perm.Attach;
189 default:
190 return 0;
191 }
192 }
193
194 /*
195 ** Emits a single-button FORM which invokes
196 ** /attachadd with target=$zTarget.
197 */
198 void attach_render_attachadd_button(const char *zTarget){
199 /* This could be changed from POST to GET, and arguably should so
200 ** that the target=X part becomes part of the resulting URL. */
201 @ <form method="post" action="%R/attachadd">\
202 @ <input type="hidden" name="target" value="%T(zTarget)">\
203 @ <input type="submit" value="Attach...">
204 @ </form>\
205 }
206
207 /*
208 ** WEBPAGE: attachlist
209 ** List attachments.
@@ -69,20 +216,21 @@
216 ** At most one of technote=, tkt=, forumpost=, or page= may be supplied.
217 **
218 ** If none are given, all attachments are listed. If one is given, only
219 ** attachments for the designated technote, ticket or wiki page are shown.
220 **
221 ** HASH may be just a prefix of the relevant forum post, technical
222 ** note, or ticket artifact hash, in which case all attachments of all
223 ** technical notes or tickets with the prefix will be listed. Forum
224 ** posts, on the other hand, require a unique hash or hash prefix.
225 */
226 void attachlist_page(void){
227 const char *zPage = P("page");
228 const char *zTkt = P("tkt");
229 const char *zTechNote = P("technote");
230 const char *zForumPost = P("forumpost");
231 char *zLink = 0;
232 Blob sql;
233 Stmt q;
234
235 if( zPage && zTkt ) zTkt = 0;
236 login_check_credentials();
@@ -102,32 +250,47 @@
250 if( fnid<=0 ){
251 webpage_error("Invalid forum post ID: %h", zForumPost);
252 }
253 blob_append_sql(&sql, " WHERE target="
254 "(SELECT uuid FROM blob WHERE rid=%d)", fnid);
255 zLink = mprintf("forum post <a href='%R/forumpost/%t'>%#h</a>",
256 zForumPost, hash_digits(0), zForumPost);
257 }else if( zPage ){
258 if( g.perm.RdWiki==0 ){ login_needed(g.anon.RdWiki); return; }
259 style_header("Attachments To Wiki page %h", zPage);
260 blob_append_sql(&sql, " WHERE target=%Q", zPage);
261 zLink = mprintf("wiki page <a href='%R/wiki?name=%t'>%h</a>",
262 zPage, zPage);
263 }else if( zTkt ){
264 if( g.perm.RdTkt==0 ){ login_needed(g.anon.RdTkt); return; }
265 style_header("Attachments To Ticket %S", zTkt);
266 blob_append_sql(&sql, " WHERE target GLOB '%q*'", zTkt);
267 zLink = mprintf("ticket <a href='%R/tktview?name=%t'>%#h</a>",
268 zTkt, hash_digits(0), zTkt);
269 }else if( zTechNote ){
270 if( g.perm.RdWiki==0 ){ login_needed(g.anon.RdWiki); return; }
271 style_header("Attachments To Tech Note %S", zTechNote);
272 blob_append_sql(&sql, " WHERE target GLOB '%q*'",
273 zTechNote);
274 zLink = mprintf("tech-note <a href='%R/technote?name=%t'>%#h</a>",
275 zTechNote, hash_digits(0), zTechNote);
276 }else{
277 if( g.perm.RdTkt==0 && g.perm.RdWiki==0 ){
278 login_needed(g.anon.RdTkt || g.anon.RdWiki);
279 return;
280 }
281 style_header("All Attachments");
282 }
283 blob_append_sql(&sql, " ORDER BY mtime DESC");
284 db_prepare(&q, "%s", blob_sql_text(&sql));
285
286 if( zLink ){
287 @ <h2>Attachments for %s(zLink)</h2>
288 fossil_free(zLink);
289 zLink = 0;
290 }
291
292 @ <ol>
293 while( db_step(&q)==SQLITE_ROW ){
294 const char *zDate;
295 const char *zSrc;
296 const char *zTarget;
@@ -137,10 +300,11 @@
300 const char *zUuid;
301 const char *zDispUser;
302 const int attachid = db_column_int(&q, 7);
303 int type;
304 int i;
305 int bDeleted;
306 char *zUrlTail = 0;
307
308 if( moderation_pending(attachid)
309 && !moderation_user_could(attachid, 1, 0) ){
310 /* Elide entries which are currently pending moderation unless
@@ -160,11 +324,12 @@
324 if( zFilename[i]=='/' && zFilename[i+1]!=0 ){
325 zFilename = &zFilename[i+1];
326 i = -1;
327 }
328 }
329 bDeleted = 0==zSrc || 0==zSrc[0];
330 type = attachment_target_type(zTarget, 1);
331 switch( type ){
332 case CFTYPE_TICKET:
333 zUrlTail = mprintf("tkt=%s&file=%t", zTarget, zFilename);
334 break;
335 case CFTYPE_EVENT:
@@ -176,20 +341,32 @@
341 case CFTYPE_WIKI:
342 zUrlTail = mprintf("page=%t&file=%t", zTarget, zFilename);
343 break;
344 }
345 @ <li><p>
346 if( bDeleted ){
347 @ <s>\
348 }
349 @ Attachment %z(href("%R/ainfo/%!S",zUuid))%S(zUuid)</a>\
350 moderation_pending_www(attachid);
351 @ <br>\
352 @ <a href="%R/attachview?%s(zUrlTail)">%h(zFilename)</a>
353 @ [<a href="%R/attachdownload/%t(zFilename)?%s(zUrlTail)">download</a>]\
354 if( bDeleted ){
355 @ </s>
356 }
357 @ <br>
358 if( zComment ) while( fossil_isspace(zComment[0]) ) zComment++;
359 if( zComment && zComment[0] ){
360 /* FIXME (2026-06-05): Honor the N-card (comment mimetype). %W
361 ** (historically used here) assumes fossil-wiki and the
362 ** fileformat.wiki doc has always claimed that it defaults to
363 ** text/plain. /ainfo assumes it is plain text. */
364 @ %h(zComment)<br>
365 }
366 if( zForumPost==0 && zPage==0 && zTkt==0 && zTechNote==0 ){
367 if( bDeleted ){
368 zSrc = "Deleted from";
369 }else {
370 zSrc = "Added to";
371 }
372 switch( type ){
@@ -362,41 +539,81 @@
539 Manifest *pManifest;
540
541 db_begin_transaction();
542 blob_init(&content, aContent, szContent);
543 pManifest = manifest_parse(&content, 0, 0);
544 addCompress = pManifest!=0;
545 manifest_destroy(pManifest);
546 blob_init(&content, aContent, szContent);
547 if( addCompress ){
548 blob_compress(&content, &content);
 
549 }
550 rid = content_put_ex(&content, 0, 0, 0, needModerator);
551 zUUID = rid_to_uuid(rid);
552 blob_zero(&manifest);
553 for(i=n=0; zName[i]; i++){
554 if( zName[i]=='/' || zName[i]=='\\' ) n = i+1;
555 }
556 zName += n;
557 if( zName[0]==0 ) zName = "unknown";
558 blob_appendf(&manifest, "A %F%s %F %s\n",
559 zName, addCompress ? ".gz" : "", zTarget, zUUID);
560 if( zComment!=0 && zComment[0]!=0 ){
561 while( fossil_isspace(zComment[0]) ) zComment++;
562 n = strlen(zComment);
563 while( n>0 && fossil_isspace(zComment[n-1]) ){ n--; }
564 if( n>0 ){
565 blob_appendf(&manifest, "C %#F\n", n, zComment);
566 }
567 }
568 zDate = date_in_standard_format("now");
569 blob_appendf(&manifest, "D %z\n", zDate);
570 blob_appendf(&manifest, "U %F\n", login_name());
571 md5sum_blob(&manifest, &cksum);
572 blob_appendf(&manifest, "Z %b\n", &cksum);
573 attach_put(&manifest, rid, needModerator);
574 assert( blob_is_reset(&manifest) );
575 db_end_transaction(0);
576 }
577
578 /*
579 ** Renders the "legacy" (static) /attachadd form. One of the first
580 ** four arguments must be non-NULL and the other three must be NULL.
581 ** zComment may be NULL, as may zFrom. See the call sites for more
582 ** context.
583 */
584 static void attach_render_legacy_form(const char *zForumPost,
585 const char *zTechNote,
586 const char *zTicket,
587 const char *zWikiPage,
588 const char *zComment,
589 const char *zFrom){
590 form_begin("enctype='multipart/form-data' id='attachadd-legacy-form'",
591 "%R/attachadd");
592 @ <div>\
593 @ File to Attach:
594 @ <input type="file" name="f" size="60"><br>
595 @ Description:<br>
596 @ <textarea name="comment" cols="80" rows="5" wrap="virtual"\
597 @ >%h(zComment)</textarea><br>
598 if( zForumPost ){
599 @ <input type="hidden" name="forumpost" value="%h(zForumPost)">\
600 }else if( zTicket ){
601 @ <input type="hidden" name="tkt" value="%h(zTicket)">\
602 }else if( zTechNote ){
603 @ <input type="hidden" name="technote" value="%h(zTechNote)">\
604 }else if( zWikiPage ){
605 @ <input type="hidden" name="page" value="%h(zWikiPage)">\
606 }
607 @ <input type="hidden" name="from" value="%h(zFrom)">\
608 @ <input type="submit" name="ok" value="Add Attachment">\
609 @ <input type="submit" name="cancel" value="Cancel">\
610 @ </div>
611 captcha_generate(0);
612 login_insert_csrf_secret();
613 @ </form>
614 }
615
616 /*
617 ** WEBPAGE: attachadd
618 ** Add a new attachment.
619 **
@@ -404,33 +621,54 @@
621 ** page=WIKIPAGE
622 ** technote=HASH
623 ** forumpost=HASH
624 ** from=URL
625 **
626 ** Adds a POSTed file attachment to the given target.
627 **
628 ** Or the "version 2" interface:
629 **
630 ** target=ATTACHMENT_TARGET
631 **
632 ** Behaves as documented for attachaddV2_page().
633 */
634 void attachadd_page(void){
635 const char *zPage;
636 const char *zForumPost;
637 const char *zTkt;
638 const char *zTechNote;
639 const char *aContent;
640 const char *zName;
641 const char *zComment;
 
642 const char *zTarget;
643 const char *zFrom; /* Origin page - redirect here after saving */
644 char *zTo = 0; /* Optionally redirect here after saving */
645 char *zTargetType = 0;
646 char *zExtraFree = 0;
647 int szContent;
648 int goodCaptcha = 1;
649 int szLimit = 0;
650
651 if( P("target")!=0 ){
652 attachaddV2_page();
653 return;
654 }
655 zPage = P("page");
656 zForumPost = P("forumpost");
657 zTkt = P("tkt");
658 zTechNote = P("technote");
659 zFrom = P("from");
660 aContent = P("f");
661 zName = PD("f:filename","unknown");
662 zComment = PD("comment", "");
663 szContent = atoi(PD("f:bytes","0"));
664
665 if( zFrom==0 ) zFrom = mprintf("%R/home");
666 if( P("cancel") ) cgi_redirect(zFrom);
667 if( (!!zPage + !!zTkt + !!zTechNote + !!zForumPost)!=1 ){
668 webpage_error("Requires exactly one one: page=X, tkt=X, forumpost=X,"
669 " technote=X, or target=X");
670 }
671 login_check_credentials();
672 if( zForumPost ){
673 int fpid;
674 if( g.perm.AttachForum==0 ){
@@ -445,26 +683,23 @@
683 "forum posts.");
684 }
685 zTarget = zExtraFree = rid_to_uuid(fpid);
686 zTargetType = mprintf("Forum post <a href=\"%R/forumpost/%S\">%h</a>",
687 zTarget, zForumPost);
688 zTo = zFrom ? 0 : mprintf("%R/forumpost/%S", zTarget);
 
 
 
 
689 }else if( zPage ){
690 if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
691 login_needed(g.anon.ApndWiki && g.anon.Attach);
692 return;
693 }
694 if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'", zPage) ){
695 fossil_redirect_home();
696 }
697 zTarget = zPage;
698 zTargetType = mprintf("Wiki Page <a href=\"%R/wiki?name=%t\">%h</a>",
699 zPage, zPage);
700 zTo = zFrom ? 0 : mprintf("%R/wiki?name=%T", zTarget);
701 }else if ( zTechNote ){
702 if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
703 login_needed(g.anon.Write && g.anon.ApndWiki && g.anon.Attach);
704 return;
705 }
@@ -474,11 +709,11 @@
709 if( zTechNote==0) fossil_redirect_home();
710 }
711 zTarget = zTechNote;
712 zTargetType = mprintf("Tech Note <a href=\"%R/technote/%s\">%S</a>",
713 zTechNote, zTechNote);
714 zTo = zFrom ? 0 : mprintf("%R/technote/%S", zTarget);
715 }else{
716 assert( zTkt );
717 if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
718 login_needed(g.anon.ApndTkt && g.anon.Attach);
719 return;
@@ -487,21 +722,25 @@
722 zTkt = db_text(0, "SELECT substr(tagname,5) FROM tag"
723 " WHERE tagname GLOB 'tkt-%q*'", zTkt);
724 if( zTkt==0 ) fossil_redirect_home();
725 }
726 zTarget = zTkt;
727 zTargetType = mprintf("Ticket <a href=\"%R/tktview/%S\">%S</a>",
728 zTkt, zTkt);
729 zTo = zFrom ? 0 : mprintf("%R/tktview/%S", zTarget);
730 }
731 szLimit = db_get_int("attachment-size-limit", 0);
732 if( szContent<0 || (szLimit && szContent>szLimit) ){
733 /* This check must be done late so that zTargetType is set up. */
734 @ <p class="generalError">Attachment %h(zName) is too large.
735 @ <a href="%R/help/attachment-size-limit">Limit</a> is
736 @ %d(szLimit ? szLimit : 0x7fffffff) bytes</p>
737 /* Fall through and render form. */
738 }else if( P("ok")
739 && cgi_csrf_safe(2)
740 && szContent>0
741 && (goodCaptcha = captcha_is_correct(0)) ){
742 int needModerator = (zForumPost!=0 && forum_need_moderation()) ||
743 (zTkt!=0 && ticket_need_moderation(0)) ||
744 (zPage!=0 && wiki_need_moderation(0));
745 attach_commit(zName, zTarget, aContent, szContent, needModerator, zComment);
746 cgi_redirect(zTo ? zTo : zFrom);
@@ -511,35 +750,374 @@
750 style_header("Add Attachment");
751 if( !goodCaptcha ){
752 @ <p class="generalError">Error: Incorrect security code.</p>
753 }
754 @ <h2>Add Attachment To %s(zTargetType)</h2>
755 attach_render_legacy_form(zForumPost, zTechNote, zTkt, zPage,
756 zComment, zFrom);
757 builtin_fossil_js_bundle_or("attach", NULL);
758 style_finish_page();
759 fossil_free(zTargetType);
760 fossil_free(zExtraFree);
761 }
762
763 /*
764 ** WEBPAGE: attachadd_ajax_post hidden
765 **
766 ** Used by attachadd V2 to handle attachments via POST requests with:
767 **
768 ** target=ATTACHMENT_TARGET
769 ** file1..fileN=FILE_OBJECTS
770 ** dryrun=0|1
771 **
772 ** Each posted file in the set file1..fileN gets attached to the given
773 ** target, permissions permitting. If dryrun>0 then the change is
774 ** rolled back instead of committed. target=X must refer to a full
775 ** target ID, not a prefix.
776 **
777 ** Responds with JSON: an empty object on success and
778 ** {error:"message"} on error. The on-success response structure is
779 ** subject to amendment.
780 */
781 void attachadd_ajax_post(void){
782 const char *zTarget;
783 char *zExtraFree = 0;
784 int eTgtType = 0;
785 int bNeedsModeration = 0;
786 int goodCaptcha = 1;
787 int bRollback = 0; /* Roll back if true. */
788
789 if( ! ajax_route_bootstrap(0, 1) ){
790 return;
791 }else if( !(goodCaptcha = captcha_is_correct(0)) ){
792 goto ajax_err_403;
793 }else if( !ajax_check_csrf(2) ){
794 return;
795 }
796 db_begin_transaction();
797 zTarget = P("target");
798 eTgtType = attachment_target_type(zTarget, 1);
799 CX("{");
800 switch( eTgtType ){
801 default:
802 case 0:
803 ajax_route_error(400, "Invalid attachment target.");
804 db_rollback_transaction();
805 return;
806 case CFTYPE_FORUM:{
807 int fpid;
808 if( g.perm.AttachForum==0 ){
809 goto ajax_err_403;
810 }
811 fpid = forumpost_head_rid2(zTarget);
812 if( fpid<=0 ){
813 goto ajax_err_404;
814 }else if( !g.perm.Admin && !forumpost_is_owner(fpid, 0) ){
815 ajax_route_error(403, "Only admins can attach files to "
816 "other users' forum posts.");
817 db_rollback_transaction();
818 return;
819 }
820 zTarget = zExtraFree = rid_to_uuid(fpid);
821 bNeedsModeration = forum_need_moderation();
822 break;
823 }
824 case CFTYPE_EVENT:{
825 if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
826 goto ajax_err_403;
827 }
828 if( !db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",
829 zTarget) ){
830 zTarget = zExtraFree =
831 db_text(0, "SELECT substr(tagname,7) FROM tag"
832 " WHERE tagname GLOB 'event-%q*'", zTarget);
833 if( zTarget==0){
834 goto ajax_err_404;
835 }
836 }
837 bNeedsModeration = 0;
838 break;
839 }
840 case CFTYPE_TICKET:{
841 if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
842 goto ajax_err_403;
843 }
844 if( !db_exists("SELECT 1 FROM tag WHERE tagname='tkt-%q'",
845 zTarget) ){
846 zTarget = db_text(0, "SELECT substr(tagname,5) FROM tag"
847 " WHERE tagname GLOB 'tkt-%q*'", zTarget);
848 if( zTarget==0 ){
849 goto ajax_err_404;
850 }
851 }
852 bNeedsModeration = ticket_need_moderation(0);
853 break;
854 }
855 case CFTYPE_WIKI:{
856 if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
857 goto ajax_err_403;
858 }
859 if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",
860 zTarget) ){
861 goto ajax_err_404;
862 }
863 bNeedsModeration = wiki_need_moderation(0);
864 break;
865 }
866 }
867
868 if( attachments_ajax_from_POST(zTarget, bNeedsModeration)>=0 ){
869 CX("}");
870 if( atoi(PD("dryrun","0"))>0 ){
871 bRollback = 1;
872 }
873 }/*else error response was set up*/
874 fossil_free(zExtraFree);
875 db_end_transaction(bRollback);
876 return;
877 ajax_err_403:
878 if( db_transaction_nesting_depth()>0 ){
879 db_rollback_transaction();
880 }
881 ajax_route_error_forbidden();
882 return;
883 ajax_err_404:
884 assert( db_transaction_nesting_depth()>0 );
885 db_rollback_transaction();
886 ajax_route_error(404, "Target not found.");
887 return;
888 }
889
890 /*
891 ** A helper for AJAX-style routines which accept file attachments via
892 ** POST. zTarget must be a full attachment target. bNeedsModeration
893 ** must be true if the attachment requires moderation.
894 **
895 ** It is up to the caller to have validated all security measures
896 ** before calling this.
897 **
898 ** This looks for POSTed files names "file1".."fileN", stopping when
899 ** it finds no entry. Returns the number of entries attached to the
900 ** target or a negative value on error (in which case the current db
901 ** transaction will be in a rollback state).
902 **
903 ** The only errors are currently attachment size limit violations:
904 ** attachments must have a non-0 size and if the attachment-size-limit
905 ** setting is >0 then each file's size must be <= that.
906 **
907 ** If this returns a negative value, it will have populated an error
908 ** response using ajax_route_error(). On success it produces no
909 ** output.
910 **
911 ** ACHTUNG: if zTarget is a forum post, it "really should" be the ID
912 ** of the first version of that post, as that's where attachments are
913 ** intended to be applied so that they can be found and removed
914 ** consistently. Potential TODO is have this function do that if
915 ** attachment_target_type(zTarget,1)!=0 but it would (for current
916 ** uses) require duplicating work already done in the callers.
917 */
918 int attachments_ajax_from_POST(const char *zTarget, int bNeedsModeration){
919 int i;
920 int rc = 0;
921 int n = 0;
922 int szLimit; /* attachment-max-size setting */
923 char aKeyPrefix[20]; /* Buffer for key "file%d" */
924 char aKeySize[30]; /* Buffer for key "file%d:bytes" */
925 char aKeyName[30]; /* Buffer for key "file%d:filename" */
926 char aKeyDesc[30]; /* Buffer for key "file%d_desc" */
927
928 db_begin_transaction();
929 szLimit = db_get_int("attachment-size-limit", 0);
930
931 for(i = 1; ; ++i, ++n){
932 /* Look for P("fileN"), where N=1..n */
933 const char *zContent;
934 const char *zFilename;
935 int szContent;
936 sqlite3_snprintf(sizeof(aKeyPrefix), aKeyPrefix, "file%d", i);
937 zContent = P(aKeyPrefix);
938 if( !zContent ){
939 /* End of the list. */
940 break;
941 }
942 sqlite3_snprintf(sizeof(aKeySize), aKeySize, "%s:bytes",
943 aKeyPrefix);
944 szContent = atoi(PD(aKeySize,"-1"));
945 if( szContent<=0 ){
946 rc = -ajax_route_error(400,"Invalid file size: %d", szContent);
947 break;
948 }else if( szLimit>0 && szContent>szLimit ){
949 rc = -ajax_route_error(413, "File size limit is %d bytes.", szLimit);
950 break;
951 }else{
952 sqlite3_snprintf(sizeof(aKeyName), aKeyName, "%s:filename",
953 aKeyPrefix);
954 sqlite3_snprintf(sizeof(aKeyDesc), aKeyDesc, "%s_desc",
955 aKeyPrefix);
956 if( 0==(zFilename=P(aKeyName)) ){
957 rc = -ajax_route_error(400, "Missing filename.");
958 break;
959 }
960 attach_commit(zFilename, zTarget, zContent, szContent,
961 bNeedsModeration, P(aKeyDesc));
962 }
963 }
964 if( rc<0 ){
965 db_rollback_transaction();
966 return rc;
967 }else{
968 db_commit_transaction();
969 return n;
970 }
971 }
972
973 /*
974 ** Proxy for /attachadd?target=X
975 **
976 ** Lists attachments for, and can add them to, a target artifact.
977 **
978 ** target=TKT_HASH|WIKIPAGE_NAME|TECHNOTE_HASH|FORUMPOST_HASH
979 ** from=ORIGINATING_URL
980 **
981 ** Works like /attachadd but uses a JS-based interactive attachment
982 ** selector.
983 **
984 ** from=X tells it where to redirect to when it's done.
985 **
986 ** This page requires a post-2018-ish JS-capable browser.
987 */
988 void attachaddV2_page(void){
989 const char *zFrom = P("from");
990 const char *zTarget = P("target");
991 char *zTo = 0;
992 char *zTargetType = 0;
993 char *zExtraFree = 0;
994 int eTgtType = 0;
995 int goodCaptcha = 1;
996 char const * noJsArgs[] = {0,0,0,0}; /* Args for noscript form */
997
998 if( P("cancel") ) cgi_redirect(zFrom);
999 if( 0==zTarget ){
1000 webpage_error("Requires target=X");
1001 }
1002 login_check_credentials();
1003 eTgtType = attachment_target_type(zTarget, 1);
1004 switch( eTgtType ){
1005 default:
1006 case 0:
1007 webpage_error("Cannot resolve target=%h.", zTarget);
1008 break;
1009 case CFTYPE_FORUM:{
1010 int fpid;
1011 if( g.perm.AttachForum==0 ){
1012 login_needed(g.anon.AttachForum);
1013 return;
1014 }
1015 fpid = forumpost_head_rid2(zTarget);
1016 if( fpid<=0 ){
1017 webpage_error("Invalid forum post ID: %h", zTarget);
1018 }else if( !g.perm.Admin && !forumpost_is_owner(fpid, 0) ){
1019 webpage_error("Only admins can attach files to other users' "
1020 "forum posts.");
1021 }
1022 zTarget = zExtraFree = rid_to_uuid(fpid);
1023 noJsArgs[0] = zTarget;
1024 zTargetType = mprintf(
1025 "Forum post <a href=\"%R/forumpost/%S\">%.16h</a>",
1026 zTarget, zTarget
1027 );
1028 zTo = mprintf("%R/forumpost/%S", zTarget);
1029 break;
1030 }
1031 case CFTYPE_EVENT:{
1032 if( g.perm.Write==0 || g.perm.ApndWiki==0 || g.perm.Attach==0 ){
1033 login_needed(g.anon.Write && g.anon.ApndWiki && g.anon.Attach);
1034 return;
1035 }
1036 if( !db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",
1037 zTarget) ){
1038 zTarget = db_text(0, "SELECT substr(tagname,7) FROM tag"
1039 " WHERE tagname GLOB 'event-%q*'",
1040 zTarget);
1041 if( zTarget==0) fossil_redirect_home();
1042 }
1043 zTo = zFrom ? 0 : mprintf("%R/technote?name=%T", zTarget);
1044 zTargetType = mprintf("Tech-note <a href=\"%R/technote/%s\">%S</a>",
1045 zTarget, zTarget);
1046 noJsArgs[1] = zTarget;
1047 break;
1048 }
1049 case CFTYPE_TICKET:{
1050 if( g.perm.ApndTkt==0 || g.perm.Attach==0 ){
1051 login_needed(g.anon.ApndTkt && g.anon.Attach);
1052 return;
1053 }
1054 if( !db_exists("SELECT 1 FROM tag WHERE tagname='tkt-%q'",
1055 zTarget) ){
1056 zTarget = db_text(0, "SELECT substr(tagname,5) FROM tag"
1057 " WHERE tagname GLOB 'tkt-%q*'", zTarget);
1058 if( zTarget==0 ) fossil_redirect_home();
1059 }
1060 zTo = zFrom ? 0 : mprintf("%R/tktview/%t", zTarget);
1061 zTargetType = mprintf("Ticket <a href=\"%R/tktview/%s\">%S</a>",
1062 zTarget, zTarget);
1063 noJsArgs[2] = zTarget;
1064 break;
1065 }
1066 case CFTYPE_WIKI:{
1067 if( g.perm.ApndWiki==0 || g.perm.Attach==0 ){
1068 login_needed(g.anon.ApndWiki && g.anon.Attach);
1069 return;
1070 }
1071 if( !db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",
1072 zTarget) ){
1073 fossil_redirect_home();
1074 }
1075 zTo = zFrom ? 0 : mprintf("%R/wiki?name=%T", zTarget);
1076 zTargetType = mprintf(
1077 "Wiki page <a href=\"%R/wiki?name=%h\">%h</a>",
1078 zTarget, zTarget
1079 );
1080 noJsArgs[3] = zTarget;
1081 break;
1082 }
1083 }
1084
1085 db_begin_transaction();
1086
1087 style_set_current_feature("attach");
1088 style_header("Add Attachment");
1089 if( !goodCaptcha ){
1090 @ <p class="generalError">Error: Incorrect security code.</p>
1091 }
1092 @ <h2>Attachments for %s(zTargetType)</h2>
1093 attachment_list(zTarget, NULL,
1094 ATTACHLIST_SIZE | ATTACHLIST_HIDE_UNAPPROVED);
1095 attach_render_legacy_form(
1096 noJsArgs[0], noJsArgs[1], noJsArgs[2],
1097 noJsArgs[3], 0,
1098 zFrom ? zFrom : (zTo ? zTo : (zTo=mprintf("%R/home")))
1099 );
1100 @ <div id='attachadd-form-wrapper' class='hidden'>
1101 /* fossil.attach.js populates this DIV with the attachment widget,
1102 ** imports these hidden fields, and removes the legacy form. */
1103 @ <input type="hidden" name="target" value="%h(zTarget)">
1104 if( zFrom ){
1105 @ <input type="hidden" name="from" value="%h(zFrom)">
1106 }
1107 if( zTo ){
1108 @ <input type="hidden" name="to" value="%h(zTo)">
1109 }
 
1110 captcha_generate(0);
1111 login_insert_csrf_secret();
1112 @ </div>
1113 builtin_fossil_js_bundle_or("attach", NULL);
1114 db_end_transaction(0);
1115 style_finish_page();
1116 fossil_free(zTargetType);
1117 fossil_free(zExtraFree);
1118 fossil_free(zTo);
1119 }
1120
1121 /*
1122 ** WEBPAGE: ainfo
1123 ** URL: /ainfo?name=ARTIFACTID
@@ -600,15 +1178,17 @@
1178 && db_exists("SELECT 1 FROM ticket WHERE tkt_uuid='%q'", zTarget)
1179 ){
1180 if( !g.perm.RdTkt ){ login_needed(g.anon.RdTkt); return; }
1181 zTktUuid = zTarget;
1182 showDelMenu = g.perm.WrTkt;
1183 }else if( db_exists("SELECT 1 FROM tag WHERE tagname='wiki-%q'",
1184 zTarget) ){
1185 if( !g.perm.RdWiki ){ login_needed(g.anon.RdWiki); return; }
1186 zWikiName = zTarget;
1187 showDelMenu = g.perm.WrWiki;
1188 }else if( db_exists("SELECT 1 FROM tag WHERE tagname='event-%q'",
1189 zTarget) ){
1190 if( !g.perm.RdWiki ){ login_needed(g.anon.RdWiki); return; }
1191 zTNUuid = zTarget;
1192 showDelMenu = g.perm.Write && g.perm.WrWiki;
1193 }
1194 if( showDelMenu ){
@@ -632,11 +1212,13 @@
1212 Blob cksum;
1213 const char *zFile = zName;
1214
1215 if( !bUserIsOwner ){
1216 if( zForumPost ? !forumpost_may_close() : !g.perm.Admin ){
1217 webpage_error(
1218 "Only admins can delete other users' attachments."
1219 );
1220 }
1221 }
1222 db_begin_transaction();
1223 blob_zero(&manifest);
1224 for(i=n=0; zFile[i]; i++){
@@ -656,14 +1238,14 @@
1238 @ <p>The attachment below has been deleted.</p>
1239 fossil_free(zNewDate);
1240 }
1241
1242 if( P("del")
1243 && ((zForumPost && (bUserIsOwner || forumpost_may_close()))
1244 || (zTktUuid && g.perm.WrTkt)
1245 || (zWikiName && g.perm.WrWiki)
1246 || (zTNUuid && g.perm.Write && g.perm.WrWiki))
1247 ){
1248 form_begin(0, "%R/ainfo/%!S", zUuid);
1249 @ <p>Confirm you want to delete the attachment shown below.
1250 @ <input type="submit" name="confirm" value="Confirm">
1251 login_insert_csrf_secret();
@@ -711,20 +1293,22 @@
1293 @ (%d(rid))
1294 }
1295 modPending = moderation_pending_www(rid);
1296 if( zForumPost ){
1297 @ <tr><th>Forum&nbsp;Post:</th>
1298 @ <td>%z(href("%R/forumpost/%s",zForumPost))%h(zForumPost)</a>\
1299 @ </td></tr>
1300 }else if( zTktUuid ){
1301 @ <tr><th>Ticket:</th>
1302 @ <td>%z(href("%R/tktview/%s",zTktUuid))%s(zTktUuid)</a></td></tr>
1303 }else if( zTNUuid ){
1304 @ <tr><th>Tech Note:</th>
1305 @ <td>%z(href("%R/technote/%s",zTNUuid))%s(zTNUuid)</a></td></tr>
1306 }else if( zWikiName ){
1307 @ <tr><th>Wiki&nbsp;Page:</th>
1308 @ <td>%z(href("%R/wiki?name=%t",zWikiName))%h(zWikiName)</a>\
1309 @ </td></tr>
1310 }
1311 @ <tr><th>Date:</th><td>
1312 hyperlink_to_date(zDate, "</td></tr>");
1313 @ <tr><th>User:</th><td>
1314 hyperlink_to_user(pAttach->zUser, zDate, "</td></tr>");
@@ -735,22 +1319,42 @@
1319 }
1320 @ <tr><th>Filename:</th><td>%h(zName)</td></tr>
1321 if( g.perm.Setup ){
1322 @ <tr><th>MIME-Type:</th><td>%h(zMime)</td></tr>
1323 }
1324 @ <tr><th valign="top">Description:</th>\
1325 /* FIXME (2026-06-05): Honor the N-card (comment mimetype). */
1326 @ <td valign="top">%h(zDesc)</td></tr>
1327 @ </table>
1328
1329 if( modPending && (isModerator || bUserIsOwner) ){
1330 @ <div class="section">Moderation</div>
1331 @ <blockquote>
1332 form_begin(0, "%R/ainfo/%s", zUuid);
1333 @ <label><input type="radio" name="modaction" value="delete">
1334 @ Delete this attachment</label><br>
1335 if( isModerator ){
1336 #if 0
1337 /* TODO/FIXME (2026-06-03): only allow approval of an attachment
1338 ** if its target has been approved. Without this, we can end up
1339 ** with stale attachments which refer to rejected targets. We
1340 ** need a type-specific RID/UUID here, which requires
1341 ** refactoring above to get it. */
1342 const int tgtid = 0;
1343 if( moderation_pending(tgtid) ){
1344 @ <label><input type="radio" name="modaction" \
1345 @ disabled value="approve">
1346 @ <span class='modpending'>Cannot approve:
1347 @ target is pending moderation</span>\
1348 @ </label><br>
1349 }else
1350 #else
1351 {
1352 @ <label><input type="radio" name="modaction" value="approve">
1353 @ Approve this attachment</label><br>
1354 }
1355 #endif
1356 }
1357 @ <input type="submit" value="Submit">
1358 login_insert_csrf_secret();
1359 @ </form>
1360 @ </blockquote>
@@ -767,11 +1371,12 @@
1371 const char *z;
1372 content_get(ridSrc, &attach);
1373 blob_to_utf8_no_bom(&attach, 0);
1374 z = blob_str(&attach);
1375 if( zLn ){
1376 output_text_with_line_numbers(z, blob_size(&attach),
1377 zName, zLn, 1);
1378 }else{
1379 @ <pre>
1380 @ %h(z)
1381 @ </pre>
1382 }
@@ -798,10 +1403,13 @@
1403 */
1404 #define ATTACHLIST_HRULE_ABOVE 0x01 /* Insert <hr> above header */
1405 #define ATTACHLIST_TARGET_BLANK 0x02 /* use target=_blank for links */
1406 #define ATTACHLIST_SIZE 0x04 /* add size */
1407 #define ATTACHLIST_HIDE_UNAPPROVED 0x08 /* Hide pending-moderation files */
1408 #define ATTACHLIST_DETAILS_CLOSED 0x10 /* Wrap in a closed DETAILS element */
1409 #define ATTACHLIST_DETAILS_OPEN 0x20 /* Wrap in an open DETAILS element */
1410 #define ATTACHLIST_HIDE_EMPTY 0x40 /* Skip if size<1 */
1411 #endif
1412
1413 /*
1414 ** Output HTML to show a list of attachments.
1415 */
@@ -810,19 +1418,25 @@
1418 const char *zHeader, /* Header to display with attachments */
1419 const int flags /* ATTACHLIST_... flags */
1420 ){
1421 int cnt = 0;
1422 char szBuf[36] = {0}; /* scratchpad for attachment size value */
1423 const char *zLinkTgt = (ATTACHLIST_TARGET_BLANK & flags)
1424 ? " target=\"_blank\"" : "";
1425 const int bUseDetail = flags &
1426 (ATTACHLIST_DETAILS_CLOSED | ATTACHLIST_DETAILS_OPEN);
1427 Stmt q;
1428
1429 db_prepare(&q,
1430 "SELECT datetime(mtime,toLocal()), a.filename, a.user,"
1431 " b1.uuid, a.src, a.target, a.attachid, b2.size\n"
1432 " FROM attachment a, blob b1, blob b2\n"
1433 " WHERE a.isLatest\n"
1434 " AND a.src IS NOT NULL\n"
1435 " AND a.target=%Q\n"
1436 " AND b1.rid=a.attachid\n"
1437 " AND b2.uuid=a.src\n"
1438 " ORDER BY mtime DESC",
1439 zTarget
1440 );
1441 while( db_step(&q)==SQLITE_ROW ){
1442 const char *zDate = db_column_text(&q, 0);
@@ -832,36 +1446,51 @@
1446 const char *zSrc = db_column_text(&q, 4);
1447 const char *zTarget = db_column_text(&q, 5);
1448 const char *zDispUser = zUser && zUser[0] ? zUser : "anonymous";
1449 const char *zTypeArg = 0; /* URL arg name for /attachdownload */
1450 const int aid = db_column_int(&q, 6);
1451 const int sz = db_column_int(&q, 7);
1452 if( (flags & ATTACHLIST_HIDE_UNAPPROVED)
1453 && moderation_pending(aid)
1454 && !moderation_user_could(aid, 1, 0) ){
1455 continue;
1456 }
1457 if( sz<1 && (flags & ATTACHLIST_HIDE_EMPTY) ){
1458 /* Deleted or phantom items. */
1459 continue;
1460 }
1461 if( cnt==0 ){
1462 if( bUseDetail ){
1463 @ <details class='attachlist'
1464 if( ATTACHLIST_DETAILS_OPEN & flags ){
1465 @ open
1466 }
1467 @ >
1468 }else{
1469 @ <section class='attachlist'>
1470 }
1471 if( flags & ATTACHLIST_HRULE_ABOVE ){
1472 @ <hr>
1473 }
1474 if( bUseDetail ){
1475 @ <summary>%s(zHeader)</summary>
1476 }else{
1477 @ %s(zHeader)
1478 }
1479 @ <ul>
1480 }
1481 cnt++;
1482 switch( attachment_target_type(zTarget, 1) ){
1483 case CFTYPE_TICKET: zTypeArg = "tkt"; break;
1484 case CFTYPE_FORUM: zTypeArg = "forumpost"; break;
1485 case CFTYPE_EVENT: zTypeArg = "technote"; break;
1486 case CFTYPE_WIKI:
1487 default: zTypeArg = "page"; break;
1488 }
1489 @ <li>
1490 @ <a href="%R/artifact/%!S(zSrc)"%s(zLinkTgt)>%h(zFile)</a>
1491 if( flags & ATTACHLIST_SIZE ){
 
1492 sqlite3_snprintf(sizeof(szBuf), szBuf, " %d bytes", sz);
1493 }
1494 @ [<a href="%R/attachdownload/%t(zFile)?%s(zTypeArg)=%t(zTarget)\
1495 @&file=%t(zFile)%s(zLinkTgt)">download</a>%s(szBuf)]
1496 @ added by %h(zDispUser) on
@@ -870,11 +1499,15 @@
1499 moderation_pending_www(aid);
1500 @ </li>
1501 }
1502 if( cnt ){
1503 @ </ul>
1504 if( bUseDetail ){
1505 @ </details>
1506 }else{
1507 @ </section>
1508 }
1509 }
1510 db_finalize(&q);
1511 }
1512
1513 /*
@@ -1023,15 +1656,204 @@
1656 }
1657 for(i = 2; i < g.argc; ++i){
1658 const char *zPage = g.argv[i];
1659 db_bind_text(&q, ":tgtname", zPage);
1660 while(SQLITE_ROW == db_step(&q)){
1661 const char *zTime = db_column_text(&q, 0);
1662 const char *zSrc = db_column_text(&q, 1);
1663 const char *zTarget = db_column_text(&q, 2);
1664 const char *zName = db_column_text(&q, 3);
1665 printf("%-20s %s %.12s %s\n", zTarget, zTime, zSrc, zName);
1666 }
1667 db_reset(&q);
1668 }
1669 db_finalize(&q);
1670 }
1671
1672 /*
1673 ** Renders the list of attachments for artifact pManifest as JSON to
1674 ** blob pOut. If pManifest->type is not one of (CFTYPE_TICKET,
1675 ** CFTYPE_FORUM, CFTYPE_EVENT, CFTYPE_WIKI) then it behaves as if the
1676 ** result set is empty.
1677 **
1678 ** If there are no matching attachments then its behavior depends on
1679 ** emptyPolicy:
1680 **
1681 ** <0 = emit a JSON NULL
1682 ** 0 = emit no output
1683 ** >0 = emit an empty JSON array
1684 **
1685 ** If bLatestOnly is true then only the most recent entry for a given
1686 ** attachment is emitted, else all versions are emitted in descending
1687 ** mtime order.
1688 **
1689 ** Returns the number of attachments.
1690 **
1691 ** Output format:
1692 **
1693 ** [{
1694 ** "uuid": attachment artifact hash,
1695 ** "src": hash of the attachment blob,
1696 ** "target": wiki page name or ticket/event ID,
1697 ** "filename": filename of attachment,
1698 ** "mtime": ISO-8601 timestamp UTC,
1699 ** "isLatest": true if this is the latest version of this file
1700 ** else false,
1701 ** }, ...once per attachment]
1702 **
1703 */
1704 int attachments_to_json(const Manifest *pManifest,
1705 Blob *pOut, int bLatestOnly,
1706 int emptyPolicy){
1707 int i = 0;
1708 Stmt q = empty_Stmt;
1709 char *zToFree = 0;
1710 const char *zTgt = 0;
1711 switch(pManifest->type){
1712 case CFTYPE_FORUM: zTgt = zToFree = rid_to_uuid(pManifest->rid);
1713 break;
1714 case CFTYPE_WIKI: zTgt = pManifest->zWikiTitle; break;
1715 case CFTYPE_EVENT: zTgt = pManifest->zEventId; break;
1716 case CFTYPE_TICKET: zTgt = pManifest->zTicketUuid; break;
1717 default:
1718 goto empty_result;
1719 }
1720 db_prepare(&q,
1721 "SELECT datetime(mtime), a.src, a.target, a.filename, a.isLatest,\n"
1722 " b2.size, b1.uuid, a.user, a.comment\n"
1723 " FROM attachment a, blob b1, blob b2\n"
1724 " WHERE a.target=%Q\n"
1725 " AND a.src IS NOT NULL\n"
1726 " AND b1.rid=a.attachid\n"
1727 " AND b2.uuid=a.src\n"
1728 " AND (a.isLatest OR %d)\n"
1729 " ORDER BY a.target, a.isLatest DESC, a.mtime DESC\n",
1730 zTgt, !bLatestOnly
1731 );
1732 while(SQLITE_ROW == db_step(&q)){
1733 const char *zTime = db_column_text(&q, 0);
1734 const char *zSrc = db_column_text(&q, 1);
1735 const char *zTarget = db_column_text(&q, 2);
1736 const char *zName = db_column_text(&q, 3);
1737 const int isLatest = db_column_int(&q, 4);
1738 const int sz = db_column_int(&q, 5);
1739 const char *zUuid = db_column_text(&q, 6);
1740 const char *zUser = db_column_text(&q, 7);
1741 const char *zComment = db_column_text(&q, 8);
1742 if(!i++){
1743 blob_append_char(pOut, '[');
1744 }else{
1745 blob_append_char(pOut, ',');
1746 }
1747 blob_appendf(
1748 pOut,
1749 "{\"uuid\": %!j, \"src\": %!j, \"target\": %!j, "
1750 "\"filename\": %!j, \"size\":%d, \"mtime\": %!j, "
1751 "\"isLatest\": %s, \"user\": %!j, \"comment\": ",
1752 zUuid, zSrc, zTarget,
1753 zName, sz, zTime, isLatest ? "true" : "false",
1754 zUser
1755 );
1756 if( zComment && zComment[0] ){
1757 blob_appendf(pOut, "%!j", zComment);
1758 }else{
1759 blob_append_literal(pOut, "null");
1760 }
1761 blob_append_char(pOut, '}');
1762 }
1763 fossil_free(zToFree);
1764 db_finalize(&q);
1765 if(!i){
1766 empty_result:
1767 if( emptyPolicy>0 ){
1768 blob_append_literal(pOut, "[]");
1769 }else if( emptyPolicy<0 ){
1770 blob_append_literal(pOut, "null");
1771 }
1772 }else{
1773 blob_append_char(pOut, ']');
1774 }
1775 return i;
1776 }
1777
1778 /*
1779 ** COMMAND: test-attachment-target
1780 **
1781 ** Usage: %fossil test-attachment-target TARGET_ID...
1782 */
1783 void test_attachment_target_type_cmd(void){
1784 int i;
1785 verify_all_options();
1786 db_find_and_open_repository(0, 0);
1787 if( g.argc<3 ){
1788 usage("test-attachment-target TARGET_ID");
1789 return;
1790 }
1791 for( i = 2; i < g.argc; ++i ){
1792 const char *zTarget = g.argv[i];
1793 const int rid = attachment_target_rid(zTarget, 0);
1794 const int type = attachment_target_type(zTarget, 0);
1795 const char *zType = "<invalid>";
1796 switch(type){
1797 case CFTYPE_EVENT: zType = "technote"; break;
1798 case CFTYPE_FORUM: zType = "forumpost"; break;
1799 case CFTYPE_TICKET: zType = "ticket"; break;
1800 case CFTYPE_WIKI: zType = "wiki"; break;
1801 }
1802 fossil_print("%-20s = %-9s #%d %z\n",
1803 zTarget, zType, rid,
1804 rid>0 ? rid_to_uuid(rid) : 0);
1805 }
1806 }
1807
1808
1809 /*
1810 ** COMMAND: test-attachments-to-json
1811 **
1812 ** Usage: %fossil test-attachments-to-json TARGET_ID...
1813 **
1814 ** Options:
1815 ** --old List all versions of attachments. Default is to
1816 ** list only the latest.
1817 ** --full Require a full target ID, not a prefix.
1818 **
1819 ** Emits a JSON array of attachments for the given attachment targets.
1820 ** The given IDs must be wiki page names, ticket hashes, tech-note
1821 ** hashes, or forum post hashes. By default it accepts hash prefixes
1822 ** but does no detection of ambiguity or cross-type prefix collisions
1823 ** so may emit curious results if given short, colliding IDs.
1824 */
1825 void test_attachments_to_json_cmd(void){
1826 const int emptyPolicy = 1;
1827 const int bLatestOnly = find_option("old",0,0)==0;
1828 const int bFullId = find_option("full",0,0)!=0;
1829 int i;
1830
1831 verify_all_options();
1832 db_find_and_open_repository(0, 0);
1833 if( g.argc<3 ){
1834 usage("test-attachments-to-json TARGET_ID");
1835 return;
1836 }
1837 for( i = 2; i < g.argc; ++i ){
1838 const char *zTarget = g.argv[i];
1839 const int rid = attachment_target_rid(zTarget, bFullId);
1840 if( 0==rid ){
1841 fossil_print("** cannot resolve %s\n", zTarget);
1842 }else{
1843 Blob b = BLOB_INITIALIZER;
1844 Manifest *pManifest = manifest_get(rid, CFTYPE_ANY, NULL);
1845 assert( pManifest );
1846 attachments_to_json(pManifest, &b, bLatestOnly, emptyPolicy);
1847 fossil_print("Attachments for %s: ", zTarget);
1848 if( b.nUsed ){
1849 char *zPretty = db_text(0,"SELECT json_pretty(%B)", &b);
1850 fossil_print("%s\n", zPretty);
1851 fossil_free(zPretty);
1852 }else{
1853 fossil_print("none\n");
1854 }
1855 blob_reset(&b);
1856 manifest_destroy(pManifest);
1857 }
1858 }
1859 }
1860
+20 -1
--- src/builtin.c
+++ src/builtin.c
@@ -668,22 +668,39 @@
668668
CX("editStateMarkers: {"
669669
"/*Symbolic markers to denote certain edit states.*/"
670670
"isNew:'[+]', isModified:'[*]', isDeleted:'[-]'},\n");
671671
CX("confirmerButtonTicks: 3 "
672672
"/*default fossil.confirmer tick count.*/,\n");
673
+ CX("attachmentSizeLimit: %d,\n",
674
+ db_get_int("attachment-size-limit",0));
673675
/* Inject certain info about the current skin... */
674676
CX("skin:{");
675677
/* can leak a local filesystem path:
676678
CX("name: %!j,", skin_in_use());*/
677679
CX("isDark: %s"
678680
"/*true if the current skin has the 'white-foreground' detail*/",
679681
skin_detail_boolean("white-foreground") ? "true" : "false");
680682
CX("}\n"/*fossil.config.skin*/);
681683
CX("};\n"/* fossil.config */);
684
+ if( forum_statuses()->n>1 ){
685
+ const ForumStatusList * fsl = forum_statuses();
686
+ int i;
687
+ CX("window.fossil.config.forumStatuses = [");
688
+ for(i = 0; i < fsl->n; ++i){
689
+ const ForumStatus *fs = &fsl->aStatus[i];
690
+ if(i) CX(",");
691
+ CX("{label:%!j, value:%!j}", fs->zLabel, fs->zValue);
692
+ }
693
+ CX("];\n");
694
+ }
695
+#define JBOOL(COND) ((COND) ? "true" : "false")
682696
CX("window.fossil.user = {");
683697
CX("name: %!j,", (g.zLogin&&*g.zLogin) ? g.zLogin : "guest");
684
- CX("isAdmin: %s", (g.perm.Admin || g.perm.Setup) ? "true" : "false");
698
+ CX("isAdmin: %s,", JBOOL(g.perm.Admin || g.perm.Setup));
699
+ CX("mayAttachForum: %s,", JBOOL(g.perm.AttachForum));
700
+ CX("enableDebug: %s,", JBOOL(g.perm.Debug || g.perm.Admin));
701
+ CX("isIndividual: %s", JBOOL(login_is_individual()));
685702
CX("};\n"/*fossil.user*/);
686703
CX("if(fossil.config.skin.isDark) "
687704
"document.body.classList.add('fossil-dark-style');\n");
688705
/*
689706
** fossil.page holds info about the current page. This is also
@@ -699,10 +716,11 @@
699716
}
700717
/* The remaining window.fossil bootstrap code is not dependent on
701718
** C-runtime state... */
702719
builtin_request_js("fossil.bootstrap.js");
703720
}
721
+#undef JBOOL
704722
}
705723
706724
/*
707725
** Given the NAME part of fossil.NAME.js, this function checks whether
708726
** that module has been emitted by this function before. If it has,
@@ -732,10 +750,11 @@
732750
** entries: all known deps of this one. Each
733751
** REQUIRES an EXPLICIT trailing \0, including
734752
** the final one! */
735753
} fjs[] = {
736754
/* This list ordering isn't strictly important. */
755
+ {"attach", 0, "dom\0"},
737756
{"confirmer", 0, 0},
738757
{"copybutton", 0, "dom\0"},
739758
{"diff", 0, "dom\0fetch\0storage\0"
740759
/* maintenance note: "diff" needs "storage" for storing the
741760
** sbs-sync-scroll toggle. */},
742761
--- src/builtin.c
+++ src/builtin.c
@@ -668,22 +668,39 @@
668 CX("editStateMarkers: {"
669 "/*Symbolic markers to denote certain edit states.*/"
670 "isNew:'[+]', isModified:'[*]', isDeleted:'[-]'},\n");
671 CX("confirmerButtonTicks: 3 "
672 "/*default fossil.confirmer tick count.*/,\n");
 
 
673 /* Inject certain info about the current skin... */
674 CX("skin:{");
675 /* can leak a local filesystem path:
676 CX("name: %!j,", skin_in_use());*/
677 CX("isDark: %s"
678 "/*true if the current skin has the 'white-foreground' detail*/",
679 skin_detail_boolean("white-foreground") ? "true" : "false");
680 CX("}\n"/*fossil.config.skin*/);
681 CX("};\n"/* fossil.config */);
 
 
 
 
 
 
 
 
 
 
 
 
682 CX("window.fossil.user = {");
683 CX("name: %!j,", (g.zLogin&&*g.zLogin) ? g.zLogin : "guest");
684 CX("isAdmin: %s", (g.perm.Admin || g.perm.Setup) ? "true" : "false");
 
 
 
685 CX("};\n"/*fossil.user*/);
686 CX("if(fossil.config.skin.isDark) "
687 "document.body.classList.add('fossil-dark-style');\n");
688 /*
689 ** fossil.page holds info about the current page. This is also
@@ -699,10 +716,11 @@
699 }
700 /* The remaining window.fossil bootstrap code is not dependent on
701 ** C-runtime state... */
702 builtin_request_js("fossil.bootstrap.js");
703 }
 
704 }
705
706 /*
707 ** Given the NAME part of fossil.NAME.js, this function checks whether
708 ** that module has been emitted by this function before. If it has,
@@ -732,10 +750,11 @@
732 ** entries: all known deps of this one. Each
733 ** REQUIRES an EXPLICIT trailing \0, including
734 ** the final one! */
735 } fjs[] = {
736 /* This list ordering isn't strictly important. */
 
737 {"confirmer", 0, 0},
738 {"copybutton", 0, "dom\0"},
739 {"diff", 0, "dom\0fetch\0storage\0"
740 /* maintenance note: "diff" needs "storage" for storing the
741 ** sbs-sync-scroll toggle. */},
742
--- src/builtin.c
+++ src/builtin.c
@@ -668,22 +668,39 @@
668 CX("editStateMarkers: {"
669 "/*Symbolic markers to denote certain edit states.*/"
670 "isNew:'[+]', isModified:'[*]', isDeleted:'[-]'},\n");
671 CX("confirmerButtonTicks: 3 "
672 "/*default fossil.confirmer tick count.*/,\n");
673 CX("attachmentSizeLimit: %d,\n",
674 db_get_int("attachment-size-limit",0));
675 /* Inject certain info about the current skin... */
676 CX("skin:{");
677 /* can leak a local filesystem path:
678 CX("name: %!j,", skin_in_use());*/
679 CX("isDark: %s"
680 "/*true if the current skin has the 'white-foreground' detail*/",
681 skin_detail_boolean("white-foreground") ? "true" : "false");
682 CX("}\n"/*fossil.config.skin*/);
683 CX("};\n"/* fossil.config */);
684 if( forum_statuses()->n>1 ){
685 const ForumStatusList * fsl = forum_statuses();
686 int i;
687 CX("window.fossil.config.forumStatuses = [");
688 for(i = 0; i < fsl->n; ++i){
689 const ForumStatus *fs = &fsl->aStatus[i];
690 if(i) CX(",");
691 CX("{label:%!j, value:%!j}", fs->zLabel, fs->zValue);
692 }
693 CX("];\n");
694 }
695 #define JBOOL(COND) ((COND) ? "true" : "false")
696 CX("window.fossil.user = {");
697 CX("name: %!j,", (g.zLogin&&*g.zLogin) ? g.zLogin : "guest");
698 CX("isAdmin: %s,", JBOOL(g.perm.Admin || g.perm.Setup));
699 CX("mayAttachForum: %s,", JBOOL(g.perm.AttachForum));
700 CX("enableDebug: %s,", JBOOL(g.perm.Debug || g.perm.Admin));
701 CX("isIndividual: %s", JBOOL(login_is_individual()));
702 CX("};\n"/*fossil.user*/);
703 CX("if(fossil.config.skin.isDark) "
704 "document.body.classList.add('fossil-dark-style');\n");
705 /*
706 ** fossil.page holds info about the current page. This is also
@@ -699,10 +716,11 @@
716 }
717 /* The remaining window.fossil bootstrap code is not dependent on
718 ** C-runtime state... */
719 builtin_request_js("fossil.bootstrap.js");
720 }
721 #undef JBOOL
722 }
723
724 /*
725 ** Given the NAME part of fossil.NAME.js, this function checks whether
726 ** that module has been emitted by this function before. If it has,
@@ -732,10 +750,11 @@
750 ** entries: all known deps of this one. Each
751 ** REQUIRES an EXPLICIT trailing \0, including
752 ** the final one! */
753 } fjs[] = {
754 /* This list ordering isn't strictly important. */
755 {"attach", 0, "dom\0"},
756 {"confirmer", 0, 0},
757 {"copybutton", 0, "dom\0"},
758 {"diff", 0, "dom\0fetch\0storage\0"
759 /* maintenance note: "diff" needs "storage" for storing the
760 ** sbs-sync-scroll toggle. */},
761
+3 -2
--- src/cgi.c
+++ src/cgi.c
@@ -1335,12 +1335,13 @@
13351335
}
13361336
fossil_free(zErr);
13371337
}
13381338
}
13391339
if( !g.syncInfo.zLoginCard && 0!=(z=(char*)P("x-f-l-c")) ){
1340
- /* x-f-l-c (X-Fossil-Login-Card card transmitted via cookie
1341
- ** instead of in the sync payload. */
1340
+ /* x-f-l-c (X-Fossil-Login-Card) transmitted via cookie instead of
1341
+ ** in the sync payload. The format of this value is the same as a
1342
+ ** "login" card, as parsed by xfer.c:page_xfer(). */
13421343
rc |= 0x04;
13431344
g.syncInfo.zLoginCard = fossil_strdup(z);
13441345
g.syncInfo.fLoginCardMode |= 0x02;
13451346
cgi_delete_parameter("x-f-l-c");
13461347
}
13471348
--- src/cgi.c
+++ src/cgi.c
@@ -1335,12 +1335,13 @@
1335 }
1336 fossil_free(zErr);
1337 }
1338 }
1339 if( !g.syncInfo.zLoginCard && 0!=(z=(char*)P("x-f-l-c")) ){
1340 /* x-f-l-c (X-Fossil-Login-Card card transmitted via cookie
1341 ** instead of in the sync payload. */
 
1342 rc |= 0x04;
1343 g.syncInfo.zLoginCard = fossil_strdup(z);
1344 g.syncInfo.fLoginCardMode |= 0x02;
1345 cgi_delete_parameter("x-f-l-c");
1346 }
1347
--- src/cgi.c
+++ src/cgi.c
@@ -1335,12 +1335,13 @@
1335 }
1336 fossil_free(zErr);
1337 }
1338 }
1339 if( !g.syncInfo.zLoginCard && 0!=(z=(char*)P("x-f-l-c")) ){
1340 /* x-f-l-c (X-Fossil-Login-Card) transmitted via cookie instead of
1341 ** in the sync payload. The format of this value is the same as a
1342 ** "login" card, as parsed by xfer.c:page_xfer(). */
1343 rc |= 0x04;
1344 g.syncInfo.zLoginCard = fossil_strdup(z);
1345 g.syncInfo.fLoginCardMode |= 0x02;
1346 cgi_delete_parameter("x-f-l-c");
1347 }
1348
--- src/comformat.c
+++ src/comformat.c
@@ -33,10 +33,12 @@
3333
*/
3434
#define COMMENT_PRINT_TRIM_CRLF ((u32)0x00000002) /* Trim leading CR/LF. */
3535
#define COMMENT_PRINT_TRIM_SPACE ((u32)0x00000004) /* Trim leading/trailing. */
3636
#define COMMENT_PRINT_WORD_BREAK ((u32)0x00000008) /* Break lines on words. */
3737
#define COMMENT_PRINT_ORIG_BREAK ((u32)0x00000010) /* Break before original. */
38
+#define COMMENT_PRINT_SUMMARY ((u32)0x00000020)
39
+ /* Truncate after first blank line. */
3840
#endif
3941
4042
/********* Code copied from SQLite src/shell.c.in on 2024-09-30 **********/
4143
/* Lookup table to estimate the number of columns consumed by a Unicode
4244
** character.
4345
--- src/comformat.c
+++ src/comformat.c
@@ -33,10 +33,12 @@
33 */
34 #define COMMENT_PRINT_TRIM_CRLF ((u32)0x00000002) /* Trim leading CR/LF. */
35 #define COMMENT_PRINT_TRIM_SPACE ((u32)0x00000004) /* Trim leading/trailing. */
36 #define COMMENT_PRINT_WORD_BREAK ((u32)0x00000008) /* Break lines on words. */
37 #define COMMENT_PRINT_ORIG_BREAK ((u32)0x00000010) /* Break before original. */
 
 
38 #endif
39
40 /********* Code copied from SQLite src/shell.c.in on 2024-09-30 **********/
41 /* Lookup table to estimate the number of columns consumed by a Unicode
42 ** character.
43
--- src/comformat.c
+++ src/comformat.c
@@ -33,10 +33,12 @@
33 */
34 #define COMMENT_PRINT_TRIM_CRLF ((u32)0x00000002) /* Trim leading CR/LF. */
35 #define COMMENT_PRINT_TRIM_SPACE ((u32)0x00000004) /* Trim leading/trailing. */
36 #define COMMENT_PRINT_WORD_BREAK ((u32)0x00000008) /* Break lines on words. */
37 #define COMMENT_PRINT_ORIG_BREAK ((u32)0x00000010) /* Break before original. */
38 #define COMMENT_PRINT_SUMMARY ((u32)0x00000020)
39 /* Truncate after first blank line. */
40 #endif
41
42 /********* Code copied from SQLite src/shell.c.in on 2024-09-30 **********/
43 /* Lookup table to estimate the number of columns consumed by a Unicode
44 ** character.
45
+163 -1
--- src/default.css
+++ src/default.css
@@ -1505,10 +1505,13 @@
15051505
}
15061506
table.numbered-lines td.line-numbers > pre {
15071507
margin: 0.25em/*must match top PADDING of td.file-content
15081508
> pre > code*/ 0 0 0;
15091509
padding: 0;
1510
+ line-height: inherit;
1511
+ font-size: inherit;
1512
+ font-family: inherit;
15101513
}
15111514
table.numbered-lines td.line-numbers span {
15121515
display: inline-block;
15131516
margin: 0;
15141517
padding: 0;
@@ -1693,11 +1696,11 @@
16931696
-0.6836761,0.240014 -1.4255375,0.720042 V 3.0698267 q 0.8800513,-0.3054724 1.6073661,-0.4509353 \
16941697
0.7273151,-0.145463 1.403718,-0.145463 1.7746486,0 2.7056104,0.727315 0.930965,0.720042 \
16951698
0.930965,2.1092135 0,0.7127686 -0.283654,1.2800746 -0.283652,0.5600324 -0.967329,1.2073428 \
16961699
L 10.025425,8.2119439 Q 9.530851,8.6628792 9.3781148,8.9392588 9.2253789,9.2083654 \
16971700
9.2253789,9.535657 Z M 6.5997716,10.939376 h 2.6256073 v 2.589241 H 6.5997716 Z' \
1698
-style='fill:%23f8f8f8;stroke-width:1.35412836' /%3e%3c/svg%3e ");
1701
+style='fill:%23f8f8f8;stroke-width:1.35412836' /%3e%3c/svg%3e ");
16991702
background-repeat: no-repeat;
17001703
background-position: center;
17011704
/* When not using a background image, this additional style works
17021705
reasonably well along with a ::before content of "?": */
17031706
/*border-width: 1px;
@@ -2007,10 +2010,169 @@
20072010
margin: 0;
20082011
}
20092012
div.helpPage blockquote {
20102013
margin-left: 0.2em;
20112014
}
2015
+
2016
+/* .attach* = styles for file attachments */
2017
+section.attachlist {}
2018
+details.attachlist > summary {
2019
+ cursor: pointer;
2020
+}
2021
+/* .Attacher is the top container element used by the JS Attacher
2022
+ class in fossil.attach.js. */
2023
+.Attacher {
2024
+ margin-bottom: 1em;
2025
+ display: flex;
2026
+ flex-direction: column;
2027
+ gap: 0.75em;
2028
+}
2029
+.Attacher.reverse {
2030
+ flex-direction: column-reverse;
2031
+}
2032
+.Attacher .attach-row {
2033
+ display: flex;
2034
+ flex-direction: column;
2035
+ gap: 0.5em;
2036
+ padding: 0.75em;
2037
+ border: 1px dashed #ccc;
2038
+ border-radius: 0.25em;
2039
+ background-color: #fafafa;
2040
+}
2041
+.Attacher .error {
2042
+ padding: 0.5em;
2043
+ background-color: #d32f2f;
2044
+ color: #fff;
2045
+}
2046
+.Attacher .error a {
2047
+ color: inherit;
2048
+ text-decoration: underline;
2049
+}
2050
+body.fossil-dark-style .Attacher .attach-row {
2051
+ background-color: initial;
2052
+}
2053
+.Attacher .attach-dropzone {
2054
+ padding: 1em;
2055
+ text-align: center;
2056
+ background: #ffffff;
2057
+ border: 1px solid #ddd;
2058
+ cursor: pointer;
2059
+ border-radius: 0.25em;
2060
+ transition: background-color 0.15s linear;
2061
+ display: flex;
2062
+ flex-direction: row;
2063
+ flex-wrap: nowrap;
2064
+}
2065
+body.fossil-dark-style .Attacher .attach-dropzone{
2066
+ background: initial;
2067
+}
2068
+.Attacher .attach-dropzone.populated {
2069
+ background-color: #f1f8e9;
2070
+ border-color: #8bc34a;
2071
+ border-style: solid;
2072
+ text-align: left;
2073
+}
2074
+body.fossil-dark-style .Attacher .attach-dropzone.populated{
2075
+ background-color: initial;
2076
+}
2077
+.Attacher .attach-dropzone.dragover {
2078
+ background-color: #e1f5fe;
2079
+ color: black;
2080
+ border-color: #03a9f4;
2081
+}
2082
+body.fossil-dark-style .Attacher .attach-dropzone.dragover{
2083
+ background-color: #e1f5fe;
2084
+ border-color: #03a9f4;
2085
+}
2086
+.Attacher .thumbnail {
2087
+ max-width: 10em;
2088
+ max-height: 10em;
2089
+ margin: 0 1em;
2090
+}
2091
+.Attacher .attach-row-info{
2092
+ font-family: monospace;
2093
+ flex-grow: 1;
2094
+ display: flex;
2095
+ flex-direction: column;
2096
+}
2097
+.Attacher .attach-filename {}
2098
+.Attacher .attach-size {/*size and mimetype*/}
2099
+.Attacher .attach-desc {
2100
+ max-width: initial;
2101
+ width: 100%;
2102
+ box-sizing: border-box;
2103
+ min-height: 4em;
2104
+ padding: 0.5em;
2105
+ font-family: inherit;
2106
+ resize: vertical;
2107
+}
2108
+.Attacher .attach-row-remove {
2109
+ align-self: center;
2110
+ padding: 0.25em 0.75em;
2111
+ margin-left: 1em;
2112
+ background-color: #d32f2f;
2113
+ color: #fff;
2114
+ border: none;
2115
+ border-radius: 0.25em;
2116
+ cursor: pointer;
2117
+ font-weight: bold;
2118
+}
2119
+.Attacher .attach-row-remove:hover {
2120
+ background-color: #b71c1c;
2121
+}
2122
+.Attacher .attach-controls {
2123
+ display: flex;
2124
+ flex-direction: row;
2125
+ gap: 1em;
2126
+}
2127
+.Attacher .attach-controls .attach-add-button {
2128
+ padding: 0.5em 1em;
2129
+ cursor: pointer;
2130
+ flex-grow: 2;
2131
+ line-height: initial/*work around an inherited alignment quirk*/;
2132
+}
2133
+
2134
+/* .animate-X and their associated @keyframes are used by various
2135
+ widgets to animate their comings and goings. */
2136
+.animate-entrance {
2137
+ animation: slideFadeIn 0.25s linear forwards;
2138
+ transform-origin: top;
2139
+ overflow: hidden /*prevent content bleeding during expansion*/;
2140
+}
2141
+.animate-exit {
2142
+ animation: slideFadeOut 0.25s linear forwards;
2143
+ transform-origin: top;
2144
+ overflow: hidden;
2145
+}
2146
+@keyframes slideFadeIn {
2147
+ 0% {
2148
+ opacity: 0;
2149
+ transform: translateY(-1em/*must match slideFadeOut*/);
2150
+ max-height: 0;
2151
+ }
2152
+ 100% {
2153
+ opacity: 1;
2154
+ transform: translateY(0);
2155
+ max-height: 100em /*a value safely larger than the widget*/;
2156
+ }
2157
+}
2158
+@keyframes slideFadeOut {
2159
+ 0% {
2160
+ opacity: 1;
2161
+ transform: translateY(0);
2162
+ max-height: 100em /*must match slideFadeIn*/;
2163
+ }
2164
+ 100% {
2165
+ opacity: 0;
2166
+ transform: translateY(-1em/*must match slideFadeIn*/);
2167
+ max-height: 0;
2168
+ padding-top: 0;
2169
+ padding-bottom: 0;
2170
+ margin-top: 0;
2171
+ margin-bottom: 0;
2172
+ }
2173
+}
20122174
20132175
/* Objects in the "desktoponly" class are invisible on mobile */
20142176
@media screen and (max-width: 600px) {
20152177
.desktoponly {
20162178
display: none;
20172179
--- src/default.css
+++ src/default.css
@@ -1505,10 +1505,13 @@
1505 }
1506 table.numbered-lines td.line-numbers > pre {
1507 margin: 0.25em/*must match top PADDING of td.file-content
1508 > pre > code*/ 0 0 0;
1509 padding: 0;
 
 
 
1510 }
1511 table.numbered-lines td.line-numbers span {
1512 display: inline-block;
1513 margin: 0;
1514 padding: 0;
@@ -1693,11 +1696,11 @@
1693 -0.6836761,0.240014 -1.4255375,0.720042 V 3.0698267 q 0.8800513,-0.3054724 1.6073661,-0.4509353 \
1694 0.7273151,-0.145463 1.403718,-0.145463 1.7746486,0 2.7056104,0.727315 0.930965,0.720042 \
1695 0.930965,2.1092135 0,0.7127686 -0.283654,1.2800746 -0.283652,0.5600324 -0.967329,1.2073428 \
1696 L 10.025425,8.2119439 Q 9.530851,8.6628792 9.3781148,8.9392588 9.2253789,9.2083654 \
1697 9.2253789,9.535657 Z M 6.5997716,10.939376 h 2.6256073 v 2.589241 H 6.5997716 Z' \
1698 style='fill:%23f8f8f8;stroke-width:1.35412836' /%3e%3c/svg%3e ");
1699 background-repeat: no-repeat;
1700 background-position: center;
1701 /* When not using a background image, this additional style works
1702 reasonably well along with a ::before content of "?": */
1703 /*border-width: 1px;
@@ -2007,10 +2010,169 @@
2007 margin: 0;
2008 }
2009 div.helpPage blockquote {
2010 margin-left: 0.2em;
2011 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2012
2013 /* Objects in the "desktoponly" class are invisible on mobile */
2014 @media screen and (max-width: 600px) {
2015 .desktoponly {
2016 display: none;
2017
--- src/default.css
+++ src/default.css
@@ -1505,10 +1505,13 @@
1505 }
1506 table.numbered-lines td.line-numbers > pre {
1507 margin: 0.25em/*must match top PADDING of td.file-content
1508 > pre > code*/ 0 0 0;
1509 padding: 0;
1510 line-height: inherit;
1511 font-size: inherit;
1512 font-family: inherit;
1513 }
1514 table.numbered-lines td.line-numbers span {
1515 display: inline-block;
1516 margin: 0;
1517 padding: 0;
@@ -1693,11 +1696,11 @@
1696 -0.6836761,0.240014 -1.4255375,0.720042 V 3.0698267 q 0.8800513,-0.3054724 1.6073661,-0.4509353 \
1697 0.7273151,-0.145463 1.403718,-0.145463 1.7746486,0 2.7056104,0.727315 0.930965,0.720042 \
1698 0.930965,2.1092135 0,0.7127686 -0.283654,1.2800746 -0.283652,0.5600324 -0.967329,1.2073428 \
1699 L 10.025425,8.2119439 Q 9.530851,8.6628792 9.3781148,8.9392588 9.2253789,9.2083654 \
1700 9.2253789,9.535657 Z M 6.5997716,10.939376 h 2.6256073 v 2.589241 H 6.5997716 Z' \
1701 style='fill:%23f8f8f8;stroke-width:1.35412836' /%3e%3c/svg%3e ");
1702 background-repeat: no-repeat;
1703 background-position: center;
1704 /* When not using a background image, this additional style works
1705 reasonably well along with a ::before content of "?": */
1706 /*border-width: 1px;
@@ -2007,10 +2010,169 @@
2010 margin: 0;
2011 }
2012 div.helpPage blockquote {
2013 margin-left: 0.2em;
2014 }
2015
2016 /* .attach* = styles for file attachments */
2017 section.attachlist {}
2018 details.attachlist > summary {
2019 cursor: pointer;
2020 }
2021 /* .Attacher is the top container element used by the JS Attacher
2022 class in fossil.attach.js. */
2023 .Attacher {
2024 margin-bottom: 1em;
2025 display: flex;
2026 flex-direction: column;
2027 gap: 0.75em;
2028 }
2029 .Attacher.reverse {
2030 flex-direction: column-reverse;
2031 }
2032 .Attacher .attach-row {
2033 display: flex;
2034 flex-direction: column;
2035 gap: 0.5em;
2036 padding: 0.75em;
2037 border: 1px dashed #ccc;
2038 border-radius: 0.25em;
2039 background-color: #fafafa;
2040 }
2041 .Attacher .error {
2042 padding: 0.5em;
2043 background-color: #d32f2f;
2044 color: #fff;
2045 }
2046 .Attacher .error a {
2047 color: inherit;
2048 text-decoration: underline;
2049 }
2050 body.fossil-dark-style .Attacher .attach-row {
2051 background-color: initial;
2052 }
2053 .Attacher .attach-dropzone {
2054 padding: 1em;
2055 text-align: center;
2056 background: #ffffff;
2057 border: 1px solid #ddd;
2058 cursor: pointer;
2059 border-radius: 0.25em;
2060 transition: background-color 0.15s linear;
2061 display: flex;
2062 flex-direction: row;
2063 flex-wrap: nowrap;
2064 }
2065 body.fossil-dark-style .Attacher .attach-dropzone{
2066 background: initial;
2067 }
2068 .Attacher .attach-dropzone.populated {
2069 background-color: #f1f8e9;
2070 border-color: #8bc34a;
2071 border-style: solid;
2072 text-align: left;
2073 }
2074 body.fossil-dark-style .Attacher .attach-dropzone.populated{
2075 background-color: initial;
2076 }
2077 .Attacher .attach-dropzone.dragover {
2078 background-color: #e1f5fe;
2079 color: black;
2080 border-color: #03a9f4;
2081 }
2082 body.fossil-dark-style .Attacher .attach-dropzone.dragover{
2083 background-color: #e1f5fe;
2084 border-color: #03a9f4;
2085 }
2086 .Attacher .thumbnail {
2087 max-width: 10em;
2088 max-height: 10em;
2089 margin: 0 1em;
2090 }
2091 .Attacher .attach-row-info{
2092 font-family: monospace;
2093 flex-grow: 1;
2094 display: flex;
2095 flex-direction: column;
2096 }
2097 .Attacher .attach-filename {}
2098 .Attacher .attach-size {/*size and mimetype*/}
2099 .Attacher .attach-desc {
2100 max-width: initial;
2101 width: 100%;
2102 box-sizing: border-box;
2103 min-height: 4em;
2104 padding: 0.5em;
2105 font-family: inherit;
2106 resize: vertical;
2107 }
2108 .Attacher .attach-row-remove {
2109 align-self: center;
2110 padding: 0.25em 0.75em;
2111 margin-left: 1em;
2112 background-color: #d32f2f;
2113 color: #fff;
2114 border: none;
2115 border-radius: 0.25em;
2116 cursor: pointer;
2117 font-weight: bold;
2118 }
2119 .Attacher .attach-row-remove:hover {
2120 background-color: #b71c1c;
2121 }
2122 .Attacher .attach-controls {
2123 display: flex;
2124 flex-direction: row;
2125 gap: 1em;
2126 }
2127 .Attacher .attach-controls .attach-add-button {
2128 padding: 0.5em 1em;
2129 cursor: pointer;
2130 flex-grow: 2;
2131 line-height: initial/*work around an inherited alignment quirk*/;
2132 }
2133
2134 /* .animate-X and their associated @keyframes are used by various
2135 widgets to animate their comings and goings. */
2136 .animate-entrance {
2137 animation: slideFadeIn 0.25s linear forwards;
2138 transform-origin: top;
2139 overflow: hidden /*prevent content bleeding during expansion*/;
2140 }
2141 .animate-exit {
2142 animation: slideFadeOut 0.25s linear forwards;
2143 transform-origin: top;
2144 overflow: hidden;
2145 }
2146 @keyframes slideFadeIn {
2147 0% {
2148 opacity: 0;
2149 transform: translateY(-1em/*must match slideFadeOut*/);
2150 max-height: 0;
2151 }
2152 100% {
2153 opacity: 1;
2154 transform: translateY(0);
2155 max-height: 100em /*a value safely larger than the widget*/;
2156 }
2157 }
2158 @keyframes slideFadeOut {
2159 0% {
2160 opacity: 1;
2161 transform: translateY(0);
2162 max-height: 100em /*must match slideFadeIn*/;
2163 }
2164 100% {
2165 opacity: 0;
2166 transform: translateY(-1em/*must match slideFadeIn*/);
2167 max-height: 0;
2168 padding-top: 0;
2169 padding-bottom: 0;
2170 margin-top: 0;
2171 margin-bottom: 0;
2172 }
2173 }
2174
2175 /* Objects in the "desktoponly" class are invisible on mobile */
2176 @media screen and (max-width: 600px) {
2177 .desktoponly {
2178 display: none;
2179
+26 -14
--- src/delta.c
+++ src/delta.c
@@ -186,20 +186,29 @@
186186
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
187187
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
188188
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
189189
-1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
190190
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
191
+
192
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
193
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
194
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
195
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
196
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
197
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
198
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
199
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
191200
};
192201
unsigned int v = 0;
193202
int c;
194203
unsigned char *z = (unsigned char*)*pz;
195
- unsigned char *zStart = z;
196
- while( (c = zValue[0x7f&*(z++)])>=0 ){
197
- v = (v<<6) + c;
204
+ unsigned char *zEnd = z + (*pLen);
205
+ while( z<zEnd && (c = zValue[*z])>=0 ){
206
+ v = (v<<6) + c;
207
+ z++;
198208
}
199
- z--;
200
- *pLen -= z - zStart;
209
+ *pLen -= (int)(z - (unsigned char*)*pz);
201210
*pz = (char*)z;
202211
return v;
203212
}
204213
205214
/*
@@ -537,11 +546,11 @@
537546
** needed.
538547
*/
539548
int delta_output_size(const char *zDelta, int lenDelta){
540549
int size;
541550
size = getInt(&zDelta, &lenDelta);
542
- if( *zDelta!='\n' ){
551
+ if( lenDelta<=0 || *zDelta!='\n' ){
543552
/* ERROR: size integer not terminated by "\n" */
544553
return -1;
545554
}
546555
return size;
547556
}
@@ -574,28 +583,30 @@
574583
int lenDelta, /* Length of the delta */
575584
char *zOut /* Write the output into this preallocated buffer */
576585
){
577586
sqlite3_uint64 limit;
578587
sqlite3_uint64 total = 0;
588
+
579589
#ifdef FOSSIL_ENABLE_DELTA_CKSUM_TEST
580590
char *zOrigOut = zOut;
581591
#endif
582592
583593
limit = getInt(&zDelta, &lenDelta);
584
- if( *zDelta!='\n' ){
594
+ if( lenDelta<=0 || *zDelta!='\n' ){
585595
/* ERROR: size integer not terminated by "\n" */
586596
return -1;
587597
}
588
- zDelta++; lenDelta--;
589
- while( *zDelta && lenDelta>0 ){
598
+ zDelta++; lenDelta--; /* Skip the \n */
599
+ while( lenDelta>0 && zDelta[0] ){
590600
unsigned int cnt, ofst;
591601
cnt = getInt(&zDelta, &lenDelta);
602
+ if( lenDelta<=0 ) return -1;
592603
switch( zDelta[0] ){
593604
case '@': {
594605
zDelta++; lenDelta--;
595606
ofst = getInt(&zDelta, &lenDelta);
596
- if( lenDelta>0 && zDelta[0]!=',' ){
607
+ if( lenDelta<=0 || zDelta[0]!=',' ){
597608
/* ERROR: copy command not terminated by ',' */
598609
return -1;
599610
}
600611
zDelta++; lenDelta--;
601612
DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
@@ -618,11 +629,11 @@
618629
if( total>limit ){
619630
/* ERROR: insert command gives an output larger than predicted */
620631
return -1;
621632
}
622633
DEBUG1( printf("INSERT %d\n", cnt); )
623
- if( (int)cnt>lenDelta ){
634
+ if( (i64)cnt>(i64)lenDelta ){
624635
/* ERROR: insert count exceeds size of delta */
625636
return -1;
626637
}
627638
memcpy(zOut, zDelta, cnt);
628639
zOut += cnt;
@@ -668,23 +679,24 @@
668679
){
669680
unsigned int nInsert = 0;
670681
unsigned int nCopy = 0;
671682
672683
(void)getInt(&zDelta, &lenDelta);
673
- if( *zDelta!='\n' ){
684
+ if( lenDelta<=0 || *zDelta!='\n' ){
674685
/* ERROR: size integer not terminated by "\n" */
675686
return -1;
676687
}
677688
zDelta++; lenDelta--;
678689
while( *zDelta && lenDelta>0 ){
679690
unsigned int cnt;
680691
cnt = getInt(&zDelta, &lenDelta);
692
+ if( lenDelta<=0 ) break;
681693
switch( zDelta[0] ){
682694
case '@': {
683695
zDelta++; lenDelta--;
684696
(void)getInt(&zDelta, &lenDelta);
685
- if( lenDelta>0 && zDelta[0]!=',' ){
697
+ if( lenDelta<=0 || zDelta[0]!=',' ){
686698
/* ERROR: copy command not terminated by ',' */
687699
return -1;
688700
}
689701
zDelta++; lenDelta--;
690702
nCopy += cnt;
@@ -691,11 +703,11 @@
691703
break;
692704
}
693705
case ':': {
694706
zDelta++; lenDelta--;
695707
nInsert += cnt;
696
- if( (int)cnt>lenDelta ){
708
+ if( (i64)cnt>(i64)lenDelta ){
697709
/* ERROR: insert count exceeds size of delta */
698710
return -1;
699711
}
700712
zDelta += cnt;
701713
lenDelta -= cnt;
702714
--- src/delta.c
+++ src/delta.c
@@ -186,20 +186,29 @@
186 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
187 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
188 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
189 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
190 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
 
 
 
 
 
 
 
 
 
191 };
192 unsigned int v = 0;
193 int c;
194 unsigned char *z = (unsigned char*)*pz;
195 unsigned char *zStart = z;
196 while( (c = zValue[0x7f&*(z++)])>=0 ){
197 v = (v<<6) + c;
 
198 }
199 z--;
200 *pLen -= z - zStart;
201 *pz = (char*)z;
202 return v;
203 }
204
205 /*
@@ -537,11 +546,11 @@
537 ** needed.
538 */
539 int delta_output_size(const char *zDelta, int lenDelta){
540 int size;
541 size = getInt(&zDelta, &lenDelta);
542 if( *zDelta!='\n' ){
543 /* ERROR: size integer not terminated by "\n" */
544 return -1;
545 }
546 return size;
547 }
@@ -574,28 +583,30 @@
574 int lenDelta, /* Length of the delta */
575 char *zOut /* Write the output into this preallocated buffer */
576 ){
577 sqlite3_uint64 limit;
578 sqlite3_uint64 total = 0;
 
579 #ifdef FOSSIL_ENABLE_DELTA_CKSUM_TEST
580 char *zOrigOut = zOut;
581 #endif
582
583 limit = getInt(&zDelta, &lenDelta);
584 if( *zDelta!='\n' ){
585 /* ERROR: size integer not terminated by "\n" */
586 return -1;
587 }
588 zDelta++; lenDelta--;
589 while( *zDelta && lenDelta>0 ){
590 unsigned int cnt, ofst;
591 cnt = getInt(&zDelta, &lenDelta);
 
592 switch( zDelta[0] ){
593 case '@': {
594 zDelta++; lenDelta--;
595 ofst = getInt(&zDelta, &lenDelta);
596 if( lenDelta>0 && zDelta[0]!=',' ){
597 /* ERROR: copy command not terminated by ',' */
598 return -1;
599 }
600 zDelta++; lenDelta--;
601 DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
@@ -618,11 +629,11 @@
618 if( total>limit ){
619 /* ERROR: insert command gives an output larger than predicted */
620 return -1;
621 }
622 DEBUG1( printf("INSERT %d\n", cnt); )
623 if( (int)cnt>lenDelta ){
624 /* ERROR: insert count exceeds size of delta */
625 return -1;
626 }
627 memcpy(zOut, zDelta, cnt);
628 zOut += cnt;
@@ -668,23 +679,24 @@
668 ){
669 unsigned int nInsert = 0;
670 unsigned int nCopy = 0;
671
672 (void)getInt(&zDelta, &lenDelta);
673 if( *zDelta!='\n' ){
674 /* ERROR: size integer not terminated by "\n" */
675 return -1;
676 }
677 zDelta++; lenDelta--;
678 while( *zDelta && lenDelta>0 ){
679 unsigned int cnt;
680 cnt = getInt(&zDelta, &lenDelta);
 
681 switch( zDelta[0] ){
682 case '@': {
683 zDelta++; lenDelta--;
684 (void)getInt(&zDelta, &lenDelta);
685 if( lenDelta>0 && zDelta[0]!=',' ){
686 /* ERROR: copy command not terminated by ',' */
687 return -1;
688 }
689 zDelta++; lenDelta--;
690 nCopy += cnt;
@@ -691,11 +703,11 @@
691 break;
692 }
693 case ':': {
694 zDelta++; lenDelta--;
695 nInsert += cnt;
696 if( (int)cnt>lenDelta ){
697 /* ERROR: insert count exceeds size of delta */
698 return -1;
699 }
700 zDelta += cnt;
701 lenDelta -= cnt;
702
--- src/delta.c
+++ src/delta.c
@@ -186,20 +186,29 @@
186 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
187 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
188 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
189 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
190 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
191
192 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
193 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
194 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
195 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
196 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
197 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
198 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
199 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
200 };
201 unsigned int v = 0;
202 int c;
203 unsigned char *z = (unsigned char*)*pz;
204 unsigned char *zEnd = z + (*pLen);
205 while( z<zEnd && (c = zValue[*z])>=0 ){
206 v = (v<<6) + c;
207 z++;
208 }
209 *pLen -= (int)(z - (unsigned char*)*pz);
 
210 *pz = (char*)z;
211 return v;
212 }
213
214 /*
@@ -537,11 +546,11 @@
546 ** needed.
547 */
548 int delta_output_size(const char *zDelta, int lenDelta){
549 int size;
550 size = getInt(&zDelta, &lenDelta);
551 if( lenDelta<=0 || *zDelta!='\n' ){
552 /* ERROR: size integer not terminated by "\n" */
553 return -1;
554 }
555 return size;
556 }
@@ -574,28 +583,30 @@
583 int lenDelta, /* Length of the delta */
584 char *zOut /* Write the output into this preallocated buffer */
585 ){
586 sqlite3_uint64 limit;
587 sqlite3_uint64 total = 0;
588
589 #ifdef FOSSIL_ENABLE_DELTA_CKSUM_TEST
590 char *zOrigOut = zOut;
591 #endif
592
593 limit = getInt(&zDelta, &lenDelta);
594 if( lenDelta<=0 || *zDelta!='\n' ){
595 /* ERROR: size integer not terminated by "\n" */
596 return -1;
597 }
598 zDelta++; lenDelta--; /* Skip the \n */
599 while( lenDelta>0 && zDelta[0] ){
600 unsigned int cnt, ofst;
601 cnt = getInt(&zDelta, &lenDelta);
602 if( lenDelta<=0 ) return -1;
603 switch( zDelta[0] ){
604 case '@': {
605 zDelta++; lenDelta--;
606 ofst = getInt(&zDelta, &lenDelta);
607 if( lenDelta<=0 || zDelta[0]!=',' ){
608 /* ERROR: copy command not terminated by ',' */
609 return -1;
610 }
611 zDelta++; lenDelta--;
612 DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
@@ -618,11 +629,11 @@
629 if( total>limit ){
630 /* ERROR: insert command gives an output larger than predicted */
631 return -1;
632 }
633 DEBUG1( printf("INSERT %d\n", cnt); )
634 if( (i64)cnt>(i64)lenDelta ){
635 /* ERROR: insert count exceeds size of delta */
636 return -1;
637 }
638 memcpy(zOut, zDelta, cnt);
639 zOut += cnt;
@@ -668,23 +679,24 @@
679 ){
680 unsigned int nInsert = 0;
681 unsigned int nCopy = 0;