1/*
2** 2010 September 31
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
13** This file contains a VFS "shim" - a layer that sits in between the
14** pager and the real VFS.
15**
16** This particular shim enforces a quota system on files.  One or more
17** database files are in a "quota group" that is defined by a GLOB
18** pattern.  A quota is set for the combined size of all files in the
19** the group.  A quota of zero means "no limit".  If the total size
20** of all files in the quota group is greater than the limit, then
21** write requests that attempt to enlarge a file fail with SQLITE_FULL.
22**
23** However, before returning SQLITE_FULL, the write requests invoke
24** a callback function that is configurable for each quota group.
25** This callback has the opportunity to enlarge the quota.  If the
26** callback does enlarge the quota such that the total size of all
27** files within the group is less than the new quota, then the write
28** continues as if nothing had happened.
29*/
30#include "sqlite3.h"
31#include <string.h>
32#include <assert.h>
33
34/*
35** For an build without mutexes, no-op the mutex calls.
36*/
37#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
38#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
39#define sqlite3_mutex_free(X)
40#define sqlite3_mutex_enter(X)
41#define sqlite3_mutex_try(X)      SQLITE_OK
42#define sqlite3_mutex_leave(X)
43#define sqlite3_mutex_held(X)     ((void)(X),1)
44#define sqlite3_mutex_notheld(X)  ((void)(X),1)
45#endif /* SQLITE_THREADSAFE==0 */
46
47
48/************************ Object Definitions ******************************/
49
50/* Forward declaration of all object types */
51typedef struct quotaGroup quotaGroup;
52typedef struct quotaConn quotaConn;
53typedef struct quotaFile quotaFile;
54
55/*
56** A "quota group" is a collection of files whose collective size we want
57** to limit.  Each quota group is defined by a GLOB pattern.
58**
59** There is an instance of the following object for each defined quota
60** group.  This object records the GLOB pattern that defines which files
61** belong to the quota group.  The object also remembers the size limit
62** for the group (the quota) and the callback to be invoked when the
63** sum of the sizes of the files within the group goes over the limit.
64**
65** A quota group must be established (using sqlite3_quota_set(...))
66** prior to opening any of the database connections that access files
67** within the quota group.
68*/
69struct quotaGroup {
70  const char *zPattern;          /* Filename pattern to be quotaed */
71  sqlite3_int64 iLimit;          /* Upper bound on total file size */
72  sqlite3_int64 iSize;           /* Current size of all files */
73  void (*xCallback)(             /* Callback invoked when going over quota */
74     const char *zFilename,         /* Name of file whose size increases */
75     sqlite3_int64 *piLimit,        /* IN/OUT: The current limit */
76     sqlite3_int64 iSize,           /* Total size of all files in the group */
77     void *pArg                     /* Client data */
78  );
79  void *pArg;                    /* Third argument to the xCallback() */
80  void (*xDestroy)(void*);       /* Optional destructor for pArg */
81  quotaGroup *pNext, **ppPrev;   /* Doubly linked list of all quota objects */
82  quotaFile *pFiles;             /* Files within this group */
83};
84
85/*
86** An instance of this structure represents a single file that is part
87** of a quota group.  A single file can be opened multiple times.  In
88** order keep multiple openings of the same file from causing the size
89** of the file to count against the quota multiple times, each file
90** has a unique instance of this object and multiple open connections
91** to the same file each point to a single instance of this object.
92*/
93struct quotaFile {
94  char *zFilename;                /* Name of this file */
95  quotaGroup *pGroup;             /* Quota group to which this file belongs */
96  sqlite3_int64 iSize;            /* Current size of this file */
97  int nRef;                       /* Number of times this file is open */
98  quotaFile *pNext, **ppPrev;     /* Linked list of files in the same group */
99};
100
101/*
102** An instance of the following object represents each open connection
103** to a file that participates in quota tracking.  This object is a
104** subclass of sqlite3_file.  The sqlite3_file object for the underlying
105** VFS is appended to this structure.
106*/
107struct quotaConn {
108  sqlite3_file base;              /* Base class - must be first */
109  quotaFile *pFile;               /* The underlying file */
110  /* The underlying VFS sqlite3_file is appended to this object */
111};
112
113/************************* Global Variables **********************************/
114/*
115** All global variables used by this file are containing within the following
116** gQuota structure.
117*/
118static struct {
119  /* The pOrigVfs is the real, original underlying VFS implementation.
120  ** Most operations pass-through to the real VFS.  This value is read-only
121  ** during operation.  It is only modified at start-time and thus does not
122  ** require a mutex.
123  */
124  sqlite3_vfs *pOrigVfs;
125
126  /* The sThisVfs is the VFS structure used by this shim.  It is initialized
127  ** at start-time and thus does not require a mutex
128  */
129  sqlite3_vfs sThisVfs;
130
131  /* The sIoMethods defines the methods used by sqlite3_file objects
132  ** associated with this shim.  It is initialized at start-time and does
133  ** not require a mutex.
134  **
135  ** When the underlying VFS is called to open a file, it might return
136  ** either a version 1 or a version 2 sqlite3_file object.  This shim
137  ** has to create a wrapper sqlite3_file of the same version.  Hence
138  ** there are two I/O method structures, one for version 1 and the other
139  ** for version 2.
140  */
141  sqlite3_io_methods sIoMethodsV1;
142  sqlite3_io_methods sIoMethodsV2;
143
144  /* True when this shim as been initialized.
145  */
146  int isInitialized;
147
148  /* For run-time access any of the other global data structures in this
149  ** shim, the following mutex must be held.
150  */
151  sqlite3_mutex *pMutex;
152
153  /* List of quotaGroup objects.
154  */
155  quotaGroup *pGroup;
156
157} gQuota;
158
159/************************* Utility Routines *********************************/
160/*
161** Acquire and release the mutex used to serialize access to the
162** list of quotaGroups.
163*/
164static void quotaEnter(void){ sqlite3_mutex_enter(gQuota.pMutex); }
165static void quotaLeave(void){ sqlite3_mutex_leave(gQuota.pMutex); }
166
167
168/* If the reference count and threshold for a quotaGroup are both
169** zero, then destroy the quotaGroup.
170*/
171static void quotaGroupDeref(quotaGroup *pGroup){
172  if( pGroup->pFiles==0 && pGroup->iLimit==0 ){
173    *pGroup->ppPrev = pGroup->pNext;
174    if( pGroup->pNext ) pGroup->pNext->ppPrev = pGroup->ppPrev;
175    if( pGroup->xDestroy ) pGroup->xDestroy(pGroup->pArg);
176    sqlite3_free(pGroup);
177  }
178}
179
180/*
181** Return TRUE if string z matches glob pattern zGlob.
182**
183** Globbing rules:
184**
185**      '*'       Matches any sequence of zero or more characters.
186**
187**      '?'       Matches exactly one character.
188**
189**     [...]      Matches one character from the enclosed list of
190**                characters.
191**
192**     [^...]     Matches one character not in the enclosed list.
193**
194*/
195static int quotaStrglob(const char *zGlob, const char *z){
196  int c, c2;
197  int invert;
198  int seen;
199
200  while( (c = (*(zGlob++)))!=0 ){
201    if( c=='*' ){
202      while( (c=(*(zGlob++))) == '*' || c=='?' ){
203        if( c=='?' && (*(z++))==0 ) return 0;
204      }
205      if( c==0 ){
206        return 1;
207      }else if( c=='[' ){
208        while( *z && quotaStrglob(zGlob-1,z)==0 ){
209          z++;
210        }
211        return (*z)!=0;
212      }
213      while( (c2 = (*(z++)))!=0 ){
214        while( c2!=c ){
215          c2 = *(z++);
216          if( c2==0 ) return 0;
217        }
218        if( quotaStrglob(zGlob,z) ) return 1;
219      }
220      return 0;
221    }else if( c=='?' ){
222      if( (*(z++))==0 ) return 0;
223    }else if( c=='[' ){
224      int prior_c = 0;
225      seen = 0;
226      invert = 0;
227      c = *(z++);
228      if( c==0 ) return 0;
229      c2 = *(zGlob++);
230      if( c2=='^' ){
231        invert = 1;
232        c2 = *(zGlob++);
233      }
234      if( c2==']' ){
235        if( c==']' ) seen = 1;
236        c2 = *(zGlob++);
237      }
238      while( c2 && c2!=']' ){
239        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
240          c2 = *(zGlob++);
241          if( c>=prior_c && c<=c2 ) seen = 1;
242          prior_c = 0;
243        }else{
244          if( c==c2 ){
245            seen = 1;
246          }
247          prior_c = c2;
248        }
249        c2 = *(zGlob++);
250      }
251      if( c2==0 || (seen ^ invert)==0 ) return 0;
252    }else{
253      if( c!=(*(z++)) ) return 0;
254    }
255  }
256  return *z==0;
257}
258
259
260/* Find a quotaGroup given the filename.
261**
262** Return a pointer to the quotaGroup object. Return NULL if not found.
263*/
264static quotaGroup *quotaGroupFind(const char *zFilename){
265  quotaGroup *p;
266  for(p=gQuota.pGroup; p && quotaStrglob(p->zPattern, zFilename)==0;
267      p=p->pNext){}
268  return p;
269}
270
271/* Translate an sqlite3_file* that is really a quotaConn* into
272** the sqlite3_file* for the underlying original VFS.
273*/
274static sqlite3_file *quotaSubOpen(sqlite3_file *pConn){
275  quotaConn *p = (quotaConn*)pConn;
276  return (sqlite3_file*)&p[1];
277}
278
279/************************* VFS Method Wrappers *****************************/
280/*
281** This is the xOpen method used for the "quota" VFS.
282**
283** Most of the work is done by the underlying original VFS.  This method
284** simply links the new file into the appropriate quota group if it is a
285** file that needs to be tracked.
286*/
287static int quotaOpen(
288  sqlite3_vfs *pVfs,          /* The quota VFS */
289  const char *zName,          /* Name of file to be opened */
290  sqlite3_file *pConn,        /* Fill in this file descriptor */
291  int flags,                  /* Flags to control the opening */
292  int *pOutFlags              /* Flags showing results of opening */
293){
294  int rc;                                    /* Result code */
295  quotaConn *pQuotaOpen;                     /* The new quota file descriptor */
296  quotaFile *pFile;                          /* Corresponding quotaFile obj */
297  quotaGroup *pGroup;                        /* The group file belongs to */
298  sqlite3_file *pSubOpen;                    /* Real file descriptor */
299  sqlite3_vfs *pOrigVfs = gQuota.pOrigVfs;   /* Real VFS */
300
301  /* If the file is not a main database file or a WAL, then use the
302  ** normal xOpen method.
303  */
304  if( (flags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_WAL))==0 ){
305    return pOrigVfs->xOpen(pOrigVfs, zName, pConn, flags, pOutFlags);
306  }
307
308  /* If the name of the file does not match any quota group, then
309  ** use the normal xOpen method.
310  */
311  quotaEnter();
312  pGroup = quotaGroupFind(zName);
313  if( pGroup==0 ){
314    rc = pOrigVfs->xOpen(pOrigVfs, zName, pConn, flags, pOutFlags);
315  }else{
316    /* If we get to this point, it means the file needs to be quota tracked.
317    */
318    pQuotaOpen = (quotaConn*)pConn;
319    pSubOpen = quotaSubOpen(pConn);
320    rc = pOrigVfs->xOpen(pOrigVfs, zName, pSubOpen, flags, pOutFlags);
321    if( rc==SQLITE_OK ){
322      for(pFile=pGroup->pFiles; pFile && strcmp(pFile->zFilename, zName);
323          pFile=pFile->pNext){}
324      if( pFile==0 ){
325        int nName = strlen(zName);
326        pFile = sqlite3_malloc( sizeof(*pFile) + nName + 1 );
327        if( pFile==0 ){
328          quotaLeave();
329          pSubOpen->pMethods->xClose(pSubOpen);
330          return SQLITE_NOMEM;
331        }
332        memset(pFile, 0, sizeof(*pFile));
333        pFile->zFilename = (char*)&pFile[1];
334        memcpy(pFile->zFilename, zName, nName+1);
335        pFile->pNext = pGroup->pFiles;
336        if( pGroup->pFiles ) pGroup->pFiles->ppPrev = &pFile->pNext;
337        pFile->ppPrev = &pGroup->pFiles;
338        pGroup->pFiles = pFile;
339        pFile->pGroup = pGroup;
340      }
341      pFile->nRef++;
342      pQuotaOpen->pFile = pFile;
343      if( pSubOpen->pMethods->iVersion==1 ){
344        pQuotaOpen->base.pMethods = &gQuota.sIoMethodsV1;
345      }else{
346        pQuotaOpen->base.pMethods = &gQuota.sIoMethodsV2;
347      }
348    }
349  }
350  quotaLeave();
351  return rc;
352}
353
354/************************ I/O Method Wrappers *******************************/
355
356/* xClose requests get passed through to the original VFS.  But we
357** also have to unlink the quotaConn from the quotaFile and quotaGroup.
358** The quotaFile and/or quotaGroup are freed if they are no longer in use.
359*/
360static int quotaClose(sqlite3_file *pConn){
361  quotaConn *p = (quotaConn*)pConn;
362  quotaFile *pFile = p->pFile;
363  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
364  int rc;
365  rc = pSubOpen->pMethods->xClose(pSubOpen);
366  quotaEnter();
367  pFile->nRef--;
368  if( pFile->nRef==0 ){
369    quotaGroup *pGroup = pFile->pGroup;
370    pGroup->iSize -= pFile->iSize;
371    if( pFile->pNext ) pFile->pNext->ppPrev = pFile->ppPrev;
372    *pFile->ppPrev = pFile->pNext;
373    quotaGroupDeref(pGroup);
374    sqlite3_free(pFile);
375  }
376  quotaLeave();
377  return rc;
378}
379
380/* Pass xRead requests directory thru to the original VFS without
381** further processing.
382*/
383static int quotaRead(
384  sqlite3_file *pConn,
385  void *pBuf,
386  int iAmt,
387  sqlite3_int64 iOfst
388){
389  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
390  return pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst);
391}
392
393/* Check xWrite requests to see if they expand the file.  If they do,
394** the perform a quota check before passing them through to the
395** original VFS.
396*/
397static int quotaWrite(
398  sqlite3_file *pConn,
399  const void *pBuf,
400  int iAmt,
401  sqlite3_int64 iOfst
402){
403  quotaConn *p = (quotaConn*)pConn;
404  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
405  sqlite3_int64 iEnd = iOfst+iAmt;
406  quotaGroup *pGroup;
407  quotaFile *pFile = p->pFile;
408  sqlite3_int64 szNew;
409
410  if( pFile->iSize<iEnd ){
411    pGroup = pFile->pGroup;
412    quotaEnter();
413    szNew = pGroup->iSize - pFile->iSize + iEnd;
414    if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){
415      if( pGroup->xCallback ){
416        pGroup->xCallback(pFile->zFilename, &pGroup->iLimit, szNew,
417                          pGroup->pArg);
418      }
419      if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){
420        quotaLeave();
421        return SQLITE_FULL;
422      }
423    }
424    pGroup->iSize = szNew;
425    pFile->iSize = iEnd;
426    quotaLeave();
427  }
428  return pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst);
429}
430
431/* Pass xTruncate requests thru to the original VFS.  If the
432** success, update the file size.
433*/
434static int quotaTruncate(sqlite3_file *pConn, sqlite3_int64 size){
435  quotaConn *p = (quotaConn*)pConn;
436  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
437  int rc = pSubOpen->pMethods->xTruncate(pSubOpen, size);
438  quotaFile *pFile = p->pFile;
439  quotaGroup *pGroup;
440  if( rc==SQLITE_OK ){
441    quotaEnter();
442    pGroup = pFile->pGroup;
443    pGroup->iSize -= pFile->iSize;
444    pFile->iSize = size;
445    pGroup->iSize += size;
446    quotaLeave();
447  }
448  return rc;
449}
450
451/* Pass xSync requests through to the original VFS without change
452*/
453static int quotaSync(sqlite3_file *pConn, int flags){
454  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
455  return pSubOpen->pMethods->xSync(pSubOpen, flags);
456}
457
458/* Pass xFileSize requests through to the original VFS but then
459** update the quotaGroup with the new size before returning.
460*/
461static int quotaFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){
462  quotaConn *p = (quotaConn*)pConn;
463  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
464  quotaFile *pFile = p->pFile;
465  quotaGroup *pGroup;
466  sqlite3_int64 sz;
467  int rc;
468
469  rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz);
470  if( rc==SQLITE_OK ){
471    quotaEnter();
472    pGroup = pFile->pGroup;
473    pGroup->iSize -= pFile->iSize;
474    pFile->iSize = sz;
475    pGroup->iSize += sz;
476    quotaLeave();
477    *pSize = sz;
478  }
479  return rc;
480}
481
482/* Pass xLock requests through to the original VFS unchanged.
483*/
484static int quotaLock(sqlite3_file *pConn, int lock){
485  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
486  return pSubOpen->pMethods->xLock(pSubOpen, lock);
487}
488
489/* Pass xUnlock requests through to the original VFS unchanged.
490*/
491static int quotaUnlock(sqlite3_file *pConn, int lock){
492  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
493  return pSubOpen->pMethods->xUnlock(pSubOpen, lock);
494}
495
496/* Pass xCheckReservedLock requests through to the original VFS unchanged.
497*/
498static int quotaCheckReservedLock(sqlite3_file *pConn, int *pResOut){
499  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
500  return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut);
501}
502
503/* Pass xFileControl requests through to the original VFS unchanged.
504*/
505static int quotaFileControl(sqlite3_file *pConn, int op, void *pArg){
506  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
507  return pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg);
508}
509
510/* Pass xSectorSize requests through to the original VFS unchanged.
511*/
512static int quotaSectorSize(sqlite3_file *pConn){
513  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
514  return pSubOpen->pMethods->xSectorSize(pSubOpen);
515}
516
517/* Pass xDeviceCharacteristics requests through to the original VFS unchanged.
518*/
519static int quotaDeviceCharacteristics(sqlite3_file *pConn){
520  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
521  return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen);
522}
523
524/* Pass xShmMap requests through to the original VFS unchanged.
525*/
526static int quotaShmMap(
527  sqlite3_file *pConn,            /* Handle open on database file */
528  int iRegion,                    /* Region to retrieve */
529  int szRegion,                   /* Size of regions */
530  int bExtend,                    /* True to extend file if necessary */
531  void volatile **pp              /* OUT: Mapped memory */
532){
533  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
534  return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend, pp);
535}
536
537/* Pass xShmLock requests through to the original VFS unchanged.
538*/
539static int quotaShmLock(
540  sqlite3_file *pConn,       /* Database file holding the shared memory */
541  int ofst,                  /* First lock to acquire or release */
542  int n,                     /* Number of locks to acquire or release */
543  int flags                  /* What to do with the lock */
544){
545  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
546  return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags);
547}
548
549/* Pass xShmBarrier requests through to the original VFS unchanged.
550*/
551static void quotaShmBarrier(sqlite3_file *pConn){
552  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
553  pSubOpen->pMethods->xShmBarrier(pSubOpen);
554}
555
556/* Pass xShmUnmap requests through to the original VFS unchanged.
557*/
558static int quotaShmUnmap(sqlite3_file *pConn, int deleteFlag){
559  sqlite3_file *pSubOpen = quotaSubOpen(pConn);
560  return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag);
561}
562
563/************************** Public Interfaces *****************************/
564/*
565** Initialize the quota VFS shim.  Use the VFS named zOrigVfsName
566** as the VFS that does the actual work.  Use the default if
567** zOrigVfsName==NULL.
568**
569** The quota VFS shim is named "quota".  It will become the default
570** VFS if makeDefault is non-zero.
571**
572** THIS ROUTINE IS NOT THREADSAFE.  Call this routine exactly once
573** during start-up.
574*/
575int sqlite3_quota_initialize(const char *zOrigVfsName, int makeDefault){
576  sqlite3_vfs *pOrigVfs;
577  if( gQuota.isInitialized ) return SQLITE_MISUSE;
578  pOrigVfs = sqlite3_vfs_find(zOrigVfsName);
579  if( pOrigVfs==0 ) return SQLITE_ERROR;
580  assert( pOrigVfs!=&gQuota.sThisVfs );
581  gQuota.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
582  if( !gQuota.pMutex ){
583    return SQLITE_NOMEM;
584  }
585  gQuota.isInitialized = 1;
586  gQuota.pOrigVfs = pOrigVfs;
587  gQuota.sThisVfs = *pOrigVfs;
588  gQuota.sThisVfs.xOpen = quotaOpen;
589  gQuota.sThisVfs.szOsFile += sizeof(quotaConn);
590  gQuota.sThisVfs.zName = "quota";
591  gQuota.sIoMethodsV1.iVersion = 1;
592  gQuota.sIoMethodsV1.xClose = quotaClose;
593  gQuota.sIoMethodsV1.xRead = quotaRead;
594  gQuota.sIoMethodsV1.xWrite = quotaWrite;
595  gQuota.sIoMethodsV1.xTruncate = quotaTruncate;
596  gQuota.sIoMethodsV1.xSync = quotaSync;
597  gQuota.sIoMethodsV1.xFileSize = quotaFileSize;
598  gQuota.sIoMethodsV1.xLock = quotaLock;
599  gQuota.sIoMethodsV1.xUnlock = quotaUnlock;
600  gQuota.sIoMethodsV1.xCheckReservedLock = quotaCheckReservedLock;
601  gQuota.sIoMethodsV1.xFileControl = quotaFileControl;
602  gQuota.sIoMethodsV1.xSectorSize = quotaSectorSize;
603  gQuota.sIoMethodsV1.xDeviceCharacteristics = quotaDeviceCharacteristics;
604  gQuota.sIoMethodsV2 = gQuota.sIoMethodsV1;
605  gQuota.sIoMethodsV2.iVersion = 2;
606  gQuota.sIoMethodsV2.xShmMap = quotaShmMap;
607  gQuota.sIoMethodsV2.xShmLock = quotaShmLock;
608  gQuota.sIoMethodsV2.xShmBarrier = quotaShmBarrier;
609  gQuota.sIoMethodsV2.xShmUnmap = quotaShmUnmap;
610  sqlite3_vfs_register(&gQuota.sThisVfs, makeDefault);
611  return SQLITE_OK;
612}
613
614/*
615** Shutdown the quota system.
616**
617** All SQLite database connections must be closed before calling this
618** routine.
619**
620** THIS ROUTINE IS NOT THREADSAFE.  Call this routine exactly one while
621** shutting down in order to free all remaining quota groups.
622*/
623int sqlite3_quota_shutdown(void){
624  quotaGroup *pGroup;
625  if( gQuota.isInitialized==0 ) return SQLITE_MISUSE;
626  for(pGroup=gQuota.pGroup; pGroup; pGroup=pGroup->pNext){
627    if( pGroup->pFiles ) return SQLITE_MISUSE;
628  }
629  while( gQuota.pGroup ){
630    pGroup = gQuota.pGroup;
631    gQuota.pGroup = pGroup->pNext;
632    pGroup->iLimit = 0;
633    quotaGroupDeref(pGroup);
634  }
635  gQuota.isInitialized = 0;
636  sqlite3_mutex_free(gQuota.pMutex);
637  sqlite3_vfs_unregister(&gQuota.sThisVfs);
638  memset(&gQuota, 0, sizeof(gQuota));
639  return SQLITE_OK;
640}
641
642/*
643** Create or destroy a quota group.
644**
645** The quota group is defined by the zPattern.  When calling this routine
646** with a zPattern for a quota group that already exists, this routine
647** merely updates the iLimit, xCallback, and pArg values for that quota
648** group.  If zPattern is new, then a new quota group is created.
649**
650** If the iLimit for a quota group is set to zero, then the quota group
651** is disabled and will be deleted when the last database connection using
652** the quota group is closed.
653**
654** Calling this routine on a zPattern that does not exist and with a
655** zero iLimit is a no-op.
656**
657** A quota group must exist with a non-zero iLimit prior to opening
658** database connections if those connections are to participate in the
659** quota group.  Creating a quota group does not affect database connections
660** that are already open.
661*/
662int sqlite3_quota_set(
663  const char *zPattern,           /* The filename pattern */
664  sqlite3_int64 iLimit,           /* New quota to set for this quota group */
665  void (*xCallback)(              /* Callback invoked when going over quota */
666     const char *zFilename,         /* Name of file whose size increases */
667     sqlite3_int64 *piLimit,        /* IN/OUT: The current limit */
668     sqlite3_int64 iSize,           /* Total size of all files in the group */
669     void *pArg                     /* Client data */
670  ),
671  void *pArg,                     /* client data passed thru to callback */
672  void (*xDestroy)(void*)         /* Optional destructor for pArg */
673){
674  quotaGroup *pGroup;
675  quotaEnter();
676  pGroup = gQuota.pGroup;
677  while( pGroup && strcmp(pGroup->zPattern, zPattern)!=0 ){
678    pGroup = pGroup->pNext;
679  }
680  if( pGroup==0 ){
681    int nPattern = strlen(zPattern);
682    if( iLimit<=0 ){
683      quotaLeave();
684      return SQLITE_OK;
685    }
686    pGroup = sqlite3_malloc( sizeof(*pGroup) + nPattern + 1 );
687    if( pGroup==0 ){
688      quotaLeave();
689      return SQLITE_NOMEM;
690    }
691    memset(pGroup, 0, sizeof(*pGroup));
692    pGroup->zPattern = (char*)&pGroup[1];
693    memcpy((char *)pGroup->zPattern, zPattern, nPattern+1);
694    if( gQuota.pGroup ) gQuota.pGroup->ppPrev = &pGroup->pNext;
695    pGroup->pNext = gQuota.pGroup;
696    pGroup->ppPrev = &gQuota.pGroup;
697    gQuota.pGroup = pGroup;
698  }
699  pGroup->iLimit = iLimit;
700  pGroup->xCallback = xCallback;
701  if( pGroup->xDestroy && pGroup->pArg!=pArg ){
702    pGroup->xDestroy(pGroup->pArg);
703  }
704  pGroup->pArg = pArg;
705  pGroup->xDestroy = xDestroy;
706  quotaGroupDeref(pGroup);
707  quotaLeave();
708  return SQLITE_OK;
709}
710
711
712/***************************** Test Code ***********************************/
713#ifdef SQLITE_TEST
714#include <tcl.h>
715
716/*
717** Argument passed to a TCL quota-over-limit callback.
718*/
719typedef struct TclQuotaCallback TclQuotaCallback;
720struct TclQuotaCallback {
721  Tcl_Interp *interp;    /* Interpreter in which to run the script */
722  Tcl_Obj *pScript;      /* Script to be run */
723};
724
725extern const char *sqlite3TestErrorName(int);
726
727
728/*
729** This is the callback from a quota-over-limit.
730*/
731static void tclQuotaCallback(
732  const char *zFilename,          /* Name of file whose size increases */
733  sqlite3_int64 *piLimit,         /* IN/OUT: The current limit */
734  sqlite3_int64 iSize,            /* Total size of all files in the group */
735  void *pArg                      /* Client data */
736){
737  TclQuotaCallback *p;            /* Callback script object */
738  Tcl_Obj *pEval;                 /* Script to evaluate */
739  Tcl_Obj *pVarname;              /* Name of variable to pass as 2nd arg */
740  unsigned int rnd;               /* Random part of pVarname */
741  int rc;                         /* Tcl error code */
742
743  p = (TclQuotaCallback *)pArg;
744  if( p==0 ) return;
745
746  pVarname = Tcl_NewStringObj("::piLimit_", -1);
747  Tcl_IncrRefCount(pVarname);
748  sqlite3_randomness(sizeof(rnd), (void *)&rnd);
749  Tcl_AppendObjToObj(pVarname, Tcl_NewIntObj((int)(rnd&0x7FFFFFFF)));
750  Tcl_ObjSetVar2(p->interp, pVarname, 0, Tcl_NewWideIntObj(*piLimit), 0);
751
752  pEval = Tcl_DuplicateObj(p->pScript);
753  Tcl_IncrRefCount(pEval);
754  Tcl_ListObjAppendElement(0, pEval, Tcl_NewStringObj(zFilename, -1));
755  Tcl_ListObjAppendElement(0, pEval, pVarname);
756  Tcl_ListObjAppendElement(0, pEval, Tcl_NewWideIntObj(iSize));
757  rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL);
758
759  if( rc==TCL_OK ){
760    Tcl_Obj *pLimit = Tcl_ObjGetVar2(p->interp, pVarname, 0, 0);
761    rc = Tcl_GetWideIntFromObj(p->interp, pLimit, piLimit);
762    Tcl_UnsetVar(p->interp, Tcl_GetString(pVarname), 0);
763  }
764
765  Tcl_DecrRefCount(pEval);
766  Tcl_DecrRefCount(pVarname);
767  if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp);
768}
769
770/*
771** Destructor for a TCL quota-over-limit callback.
772*/
773static void tclCallbackDestructor(void *pObj){
774  TclQuotaCallback *p = (TclQuotaCallback*)pObj;
775  if( p ){
776    Tcl_DecrRefCount(p->pScript);
777    sqlite3_free((char *)p);
778  }
779}
780
781/*
782** tclcmd: sqlite3_quota_initialize NAME MAKEDEFAULT
783*/
784static int test_quota_initialize(
785  void * clientData,
786  Tcl_Interp *interp,
787  int objc,
788  Tcl_Obj *CONST objv[]
789){
790  const char *zName;              /* Name of new quota VFS */
791  int makeDefault;                /* True to make the new VFS the default */
792  int rc;                         /* Value returned by quota_initialize() */
793
794  /* Process arguments */
795  if( objc!=3 ){
796    Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT");
797    return TCL_ERROR;
798  }
799  zName = Tcl_GetString(objv[1]);
800  if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR;
801  if( zName[0]=='\0' ) zName = 0;
802
803  /* Call sqlite3_quota_initialize() */
804  rc = sqlite3_quota_initialize(zName, makeDefault);
805  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
806
807  return TCL_OK;
808}
809
810/*
811** tclcmd: sqlite3_quota_shutdown
812*/
813static int test_quota_shutdown(
814  void * clientData,
815  Tcl_Interp *interp,
816  int objc,
817  Tcl_Obj *CONST objv[]
818){
819  int rc;                         /* Value returned by quota_shutdown() */
820
821  if( objc!=1 ){
822    Tcl_WrongNumArgs(interp, 1, objv, "");
823    return TCL_ERROR;
824  }
825
826  /* Call sqlite3_quota_shutdown() */
827  rc = sqlite3_quota_shutdown();
828  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
829
830  return TCL_OK;
831}
832
833/*
834** tclcmd: sqlite3_quota_set PATTERN LIMIT SCRIPT
835*/
836static int test_quota_set(
837  void * clientData,
838  Tcl_Interp *interp,
839  int objc,
840  Tcl_Obj *CONST objv[]
841){
842  const char *zPattern;           /* File pattern to configure */
843  sqlite3_int64 iLimit;           /* Initial quota in bytes */
844  Tcl_Obj *pScript;               /* Tcl script to invoke to increase quota */
845  int rc;                         /* Value returned by quota_set() */
846  TclQuotaCallback *p;            /* Callback object */
847  int nScript;                    /* Length of callback script */
848  void (*xDestroy)(void*);        /* Optional destructor for pArg */
849  void (*xCallback)(const char *, sqlite3_int64 *, sqlite3_int64, void *);
850
851  /* Process arguments */
852  if( objc!=4 ){
853    Tcl_WrongNumArgs(interp, 1, objv, "PATTERN LIMIT SCRIPT");
854    return TCL_ERROR;
855  }
856  zPattern = Tcl_GetString(objv[1]);
857  if( Tcl_GetWideIntFromObj(interp, objv[2], &iLimit) ) return TCL_ERROR;
858  pScript = objv[3];
859  Tcl_GetStringFromObj(pScript, &nScript);
860
861  if( nScript>0 ){
862    /* Allocate a TclQuotaCallback object */
863    p = (TclQuotaCallback *)sqlite3_malloc(sizeof(TclQuotaCallback));
864    if( !p ){
865      Tcl_SetResult(interp, (char *)"SQLITE_NOMEM", TCL_STATIC);
866      return TCL_OK;
867    }
868    memset(p, 0, sizeof(TclQuotaCallback));
869    p->interp = interp;
870    Tcl_IncrRefCount(pScript);
871    p->pScript = pScript;
872    xDestroy = tclCallbackDestructor;
873    xCallback = tclQuotaCallback;
874  }else{
875    p = 0;
876    xDestroy = 0;
877    xCallback = 0;
878  }
879
880  /* Invoke sqlite3_quota_set() */
881  rc = sqlite3_quota_set(zPattern, iLimit, xCallback, (void*)p, xDestroy);
882
883  Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
884  return TCL_OK;
885}
886
887/*
888** tclcmd:  sqlite3_quota_dump
889*/
890static int test_quota_dump(
891  void * clientData,
892  Tcl_Interp *interp,
893  int objc,
894  Tcl_Obj *CONST objv[]
895){
896  Tcl_Obj *pResult;
897  Tcl_Obj *pGroupTerm;
898  Tcl_Obj *pFileTerm;
899  quotaGroup *pGroup;
900  quotaFile *pFile;
901
902  pResult = Tcl_NewObj();
903  quotaEnter();
904  for(pGroup=gQuota.pGroup; pGroup; pGroup=pGroup->pNext){
905    pGroupTerm = Tcl_NewObj();
906    Tcl_ListObjAppendElement(interp, pGroupTerm,
907          Tcl_NewStringObj(pGroup->zPattern, -1));
908    Tcl_ListObjAppendElement(interp, pGroupTerm,
909          Tcl_NewWideIntObj(pGroup->iLimit));
910    Tcl_ListObjAppendElement(interp, pGroupTerm,
911          Tcl_NewWideIntObj(pGroup->iSize));
912    for(pFile=pGroup->pFiles; pFile; pFile=pFile->pNext){
913      pFileTerm = Tcl_NewObj();
914      Tcl_ListObjAppendElement(interp, pFileTerm,
915            Tcl_NewStringObj(pFile->zFilename, -1));
916      Tcl_ListObjAppendElement(interp, pFileTerm,
917            Tcl_NewWideIntObj(pFile->iSize));
918      Tcl_ListObjAppendElement(interp, pFileTerm,
919            Tcl_NewWideIntObj(pFile->nRef));
920      Tcl_ListObjAppendElement(interp, pGroupTerm, pFileTerm);
921    }
922    Tcl_ListObjAppendElement(interp, pResult, pGroupTerm);
923  }
924  quotaLeave();
925  Tcl_SetObjResult(interp, pResult);
926  return TCL_OK;
927}
928
929/*
930** This routine registers the custom TCL commands defined in this
931** module.  This should be the only procedure visible from outside
932** of this module.
933*/
934int Sqlitequota_Init(Tcl_Interp *interp){
935  static struct {
936     char *zName;
937     Tcl_ObjCmdProc *xProc;
938  } aCmd[] = {
939    { "sqlite3_quota_initialize", test_quota_initialize },
940    { "sqlite3_quota_shutdown", test_quota_shutdown },
941    { "sqlite3_quota_set", test_quota_set },
942    { "sqlite3_quota_dump", test_quota_dump },
943  };
944  int i;
945
946  for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
947    Tcl_CreateObjCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
948  }
949
950  return TCL_OK;
951}
952#endif
953