[libgda] Upgraded to SqlCipher 2.2.1



commit ee94392a2c7cd96232360195764afc2deea3fa34
Author: Vivien Malerba <malerba gnome-db org>
Date:   Sat Jul 13 11:04:51 2013 +0200

    Upgraded to SqlCipher 2.2.1

 providers/sqlcipher/sqlcipher.patch |  570 +++++++++++++++++++---------------
 1 files changed, 318 insertions(+), 252 deletions(-)
---
diff --git a/providers/sqlcipher/sqlcipher.patch b/providers/sqlcipher/sqlcipher.patch
index 047ef67..fad792e 100644
--- a/providers/sqlcipher/sqlcipher.patch
+++ b/providers/sqlcipher/sqlcipher.patch
@@ -1,5 +1,5 @@
---- sqlite3.c.sqlite   2013-06-30 15:20:58.230969175 +0200
-+++ sqlite3.c  2013-06-30 15:14:57.082959321 +0200
+--- sqlite3.c.sqlite   2013-07-13 11:02:55.228615268 +0200
++++ sqlite3.c  2013-07-13 11:02:46.604615238 +0200
 @@ -12585,9 +12585,45 @@
  #endif /* _SQLITEINT_H_ */
  
@@ -48,7 +48,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -12597,3032 +12633,3163 @@
+@@ -12597,3032 +12633,3229 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -1077,7 +1077,7 @@
 +#define FILE_HEADER_SZ 16
 +
 +#ifndef CIPHER_VERSION
-+#define CIPHER_VERSION "2.2.0"
++#define CIPHER_VERSION "2.2.1"
  #endif
 -#ifdef SQLITE_MAX_SCHEMA_RETRY
 -  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
@@ -2308,7 +2308,8 @@
 +
 +static unsigned int default_flags = DEFAULT_CIPHER_FLAGS;
 +static unsigned char hmac_salt_mask = HMAC_SALT_MASK;
-+
++static unsigned int sqlcipher_activate_count = 0;
++static sqlite3_mutex* sqlcipher_provider_mutex = NULL;
 +static sqlcipher_provider *default_provider = NULL;
 +
 +struct codec_ctx {
@@ -2363,9 +2364,8 @@
 -  int nChildCsr;          /* Number of cursors for child frame */
 -  int nChange;            /* Statement changes (Vdbe.nChanges)     */
 -};
--
--#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
 +int sqlcipher_register_provider(sqlcipher_provider *p) {
++  sqlite3_mutex_enter(sqlcipher_provider_mutex);
 +  if(default_provider != NULL && default_provider != p) {
 +    /* only free the current registerd provider if it has been initialized
 +       and it isn't a pointer to the same provider passed to the function
@@ -2373,13 +2373,11 @@
 +    sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
 +  }
 +  default_provider = p;   
++  sqlite3_mutex_leave(sqlcipher_provider_mutex);
 +  return SQLITE_OK;
 +}
  
--/*
--** A value for VdbeCursor.cacheValid that means the cache is always invalid.
--*/
--#define CACHE_STALE 0
+-#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
 +/* return a pointer to the currently registered provider. This will
 +   allow an application to fetch the current registered provider and
 +   make minor changes to it */
@@ -2388,6 +2386,13 @@
 +}
  
 -/*
+-** A value for VdbeCursor.cacheValid that means the cache is always invalid.
+-*/
+-#define CACHE_STALE 0
++void sqlcipher_activate() {
++  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
+ 
+-/*
 -** Internally, the vdbe manipulates nearly all SQL values as Mem
 -** structures. Each Mem struct may cache multiple representations (string,
 -** integer etc.) of the same value.
@@ -2410,28 +2415,33 @@
 -#ifdef SQLITE_DEBUG
 -  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
 -  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
-+void sqlcipher_activate() {
-+  sqlcipher_provider *p;
-+  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
-+  p = sqlcipher_malloc(sizeof(sqlcipher_provider));
-+  {
++  if(sqlcipher_provider_mutex == NULL) {
++    /* allocate a new mutex to guard access to the provider */
++    sqlcipher_provider_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
++  }
++
++  /* check to see if there is a provider registered at this point
++     if there no provider registered at this point, register the 
++     default provider */
++  if(sqlcipher_get_provider() == NULL) {
++    sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider)); 
 +#if defined (SQLCIPHER_CRYPTO_CC)
-+  extern int sqlcipher_cc_setup(sqlcipher_provider *p);
-+  sqlcipher_cc_setup(p);
++    extern int sqlcipher_cc_setup(sqlcipher_provider *p);
++    sqlcipher_cc_setup(p);
 +#elif defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT)
-+  extern int sqlcipher_ltc_setup(sqlcipher_provider *p);
-+  sqlcipher_ltc_setup(p);
++    extern int sqlcipher_ltc_setup(sqlcipher_provider *p);
++    sqlcipher_ltc_setup(p);
 +#elif defined (SQLCIPHER_CRYPTO_OPENSSL)
-+  extern int sqlcipher_openssl_setup(sqlcipher_provider *p);
-+  sqlcipher_openssl_setup(p);
++    extern int sqlcipher_openssl_setup(sqlcipher_provider *p);
++    sqlcipher_openssl_setup(p);
 +#else
 +#error "NO DEFAULT SQLCIPHER CRYPTO PROVIDER DEFINED"
  #endif
 -  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
 -  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
 -};
++    sqlcipher_register_provider(p);
 +  }
-+  sqlcipher_register_provider(p);
  
 -/* One or more of the following flags are set to indicate the validOK
 -** representations of the value stored in the Mem struct.
@@ -2455,26 +2465,16 @@
 -#define MEM_Invalid   0x0080   /* Value is undefined */
 -#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
 -#define MEM_TypeMask  0x01ff   /* Mask of type bits */
-+  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
-+}
++  sqlcipher_activate_count++; /* increment activation count */
  
-+void sqlcipher_deactivate() {
-+  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
-+  if(default_provider != NULL) {
-+    sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
-+    default_provider = NULL;
-+  }
-+  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
++  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
 +}
  
 -/* Whenever Mem contains a valid string or blob representation, one of
 -** the following flags must be set to determine the memory management
 -** policy for Mem.z.  The MEM_Term flag tells us whether or not the
 -** string is \000 or \u0000 terminated
-+/* constant time memset using volitile to avoid having the memset
-+   optimized out by the compiler. 
-+   Note: As suggested by Joachim Schipper (joachim schipper fox-it com)
- */
+-*/
 -#define MEM_Term      0x0200   /* String rep is nul terminated */
 -#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
 -#define MEM_Static    0x0800   /* Mem.z points to a static string */
@@ -2485,30 +2485,47 @@
 -  #undef MEM_Zero
 -  #define MEM_Zero 0x0000
 -#endif
-+void* sqlcipher_memset(void *v, unsigned char value, int len) {
-+  int i = 0;
-+  volatile unsigned char *a = v;
++void sqlcipher_deactivate() {
++  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
++  sqlcipher_activate_count--;
++  /* if no connections are using sqlcipher, cleanup globals */
++  if(sqlcipher_activate_count < 1) {
++    sqlite3_mutex_enter(sqlcipher_provider_mutex);
++    if(default_provider != NULL) {
++      sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
++      default_provider = NULL;
++    }
++    sqlite3_mutex_leave(sqlcipher_provider_mutex);
++    
++    /* last connection closed, free provider mutex*/
++    sqlite3_mutex_free(sqlcipher_provider_mutex); 
++    sqlcipher_provider_mutex = NULL;
  
 -/*
 -** Clear any existing type flags from a Mem and replace them with f
 -*/
 -#define MemSetTypeFlag(p, f) \
 -   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
-+  if (v == NULL) return v;
++    sqlcipher_activate_count = 0; /* reset activation count */
++  }
++  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
++}
  
 -/*
 -** Return true if a memory cell is not marked as invalid.  This macro
 -** is for use inside assert() statements only.
--*/
++/* constant time memset using volitile to avoid having the memset
++   optimized out by the compiler. 
++   Note: As suggested by Joachim Schipper (joachim schipper fox-it com)
+ */
 -#ifdef SQLITE_DEBUG
 -#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
 -#endif
-+  for(i = 0; i < len; i++) {
-+    a[i] = value;
-+  }
++void* sqlcipher_memset(void *v, unsigned char value, int len) {
++  int i = 0;
++  volatile unsigned char *a = v;
  
-+  return v;
-+}
++  if (v == NULL) return v;
  
 -/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
 -** additional information about auxiliary information bound to arguments
@@ -2527,12 +2544,9 @@
 -    void (*xDelete)(void *);      /* Destructor for the aux data */
 -  } apAux[1];                   /* One slot for each function argument */
 -};
-+/* constant time memory check tests every position of a memory segement
-+   matches a single value (i.e. the memory is all zeros)
-+   returns 0 if match, 1 of no match */
-+int sqlcipher_ismemset(const void *v, unsigned char value, int len) {
-+  const unsigned char *a = v;
-+  int i = 0, result = 0;
++  for(i = 0; i < len; i++) {
++    a[i] = value;
++  }
  
 -/*
 -** The "context" argument for a installable function.  A pointer to an
@@ -2556,9 +2570,8 @@
 -  int isError;          /* Error code returned by the function. */
 -  int skipFlag;         /* Skip skip accumulator loading if true */
 -};
-+  for(i = 0; i < len; i++) {
-+    result |= a[i] ^ value;
-+  }
++  return v;
++}
  
 -/*
 -** An Explain object accumulates indented output which is helpful
@@ -2571,18 +2584,20 @@
 -  u16 aIndent[100];  /* Levels of indentation */
 -  char zBase[100];   /* Initial space */
 -};
-+  return (result != 0);
-+}
++/* constant time memory check tests every position of a memory segement
++   matches a single value (i.e. the memory is all zeros)
++   returns 0 if match, 1 of no match */
++int sqlcipher_ismemset(const void *v, unsigned char value, int len) {
++  const unsigned char *a = v;
++  int i = 0, result = 0;
  
 -/* A bitfield type for use inside of structures.  Always follow with :N where
 -** N is the number of bits.
 -*/
 -typedef unsigned bft;  /* Bit Field Type */
-+/* constant time memory comparison routine. 
-+   returns 0 if match, 1 if no match */
-+int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
-+  const unsigned char *a0 = v0, *a1 = v1;
-+  int i = 0, result = 0;
++  for(i = 0; i < len; i++) {
++    result |= a[i] ^ value;
++  }
  
 -/*
 -** An instance of the virtual machine.  This structure contains the complete
@@ -2642,6 +2657,15 @@
 -  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
 -#ifndef SQLITE_OMIT_TRACE
 -  i64 startTime;          /* Time when query started - used for profiling */
++  return (result != 0);
++}
++
++/* constant time memory comparison routine. 
++   returns 0 if match, 1 if no match */
++int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
++  const unsigned char *a0 = v0, *a1 = v1;
++  int i = 0, result = 0;
++
 +  for(i = 0; i < len; i++) {
 +    result |= a0[i] ^ a1[i];
 +  }
@@ -2748,7 +2772,11 @@
 +
 +  ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider));
 +  if(ctx->provider == NULL) return SQLITE_NOMEM;
++
++  /* make a copy of the provider to be used for the duration of the context */
++  sqlite3_mutex_enter(sqlcipher_provider_mutex);
 +  memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider));
++  sqlite3_mutex_leave(sqlcipher_provider_mutex);
 +
 +  if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) return rc;
 +  ctx->key = (unsigned char *) sqlcipher_malloc(CIPHER_MAX_KEY_SZ);
@@ -4262,8 +4290,27 @@
 +  if(*ctx == NULL) return SQLITE_NOMEM;
 +  sqlcipher_ltc_activate(*ctx);
 +  return SQLITE_OK;
-+}
-+
+ }
+-#endif /* SQLITE_OMIT_LOCALTIME */
+ 
+-/*
+-** Process a modifier to a date-time stamp.  The modifiers are
+-** as follows:
+-**
+-**     NNN days
+-**     NNN hours
+-**     NNN minutes
+-**     NNN.NNNN seconds
+-**     NNN months
+-**     NNN years
+-**     start of month
+-**     start of year
+-**     start of week
+-**     start of day
+-**     weekday N
+-**     unixepoch
+-**     localtime
+-**     utc
 +static int sqlcipher_ltc_ctx_free(void **ctx) {
 +  sqlcipher_ltc_deactivate(&ctx);
 +  sqlcipher_free(*ctx, sizeof(ltc_ctx));
@@ -4289,33 +4336,48 @@
 +  p->ctx_init = sqlcipher_ltc_ctx_init;
 +  p->ctx_free = sqlcipher_ltc_ctx_free;
 +  p->add_random = sqlcipher_ltc_add_random;
- }
--#endif /* SQLITE_OMIT_LOCALTIME */
- 
--/*
--** Process a modifier to a date-time stamp.  The modifiers are
--** as follows:
--**
--**     NNN days
--**     NNN hours
--**     NNN minutes
--**     NNN.NNNN seconds
--**     NNN months
--**     NNN years
--**     start of month
--**     start of year
--**     start of week
--**     start of day
--**     weekday N
--**     unixepoch
--**     localtime
--**     utc
--**
++}
++
++#endif
++#endif
++/* END SQLCIPHER */
++
++/************** End of crypto_libtomcrypt.c **********************************/
++/************** Begin file crypto_openssl.c **********************************/
++/*
++** SQLCipher
++** http://sqlcipher.net
++**
++** Copyright (c) 2008 - 2013, ZETETIC LLC
++** All rights reserved.
++**
++** Redistribution and use in source and binary forms, with or without
++** modification, are permitted provided that the following conditions are met:
++**     * Redistributions of source code must retain the above copyright
++**       notice, this list of conditions and the following disclaimer.
++**     * Redistributions in binary form must reproduce the above copyright
++**       notice, this list of conditions and the following disclaimer in the
++**       documentation and/or other materials provided with the distribution.
++**     * Neither the name of the ZETETIC LLC nor the
++**       names of its contributors may be used to endorse or promote products
++**       derived from this software without specific prior written permission.
++**
++** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
++** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
++** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
++** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
++** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
++** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
++** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
++** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
++** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
++** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ **
 -** Return 0 on success and 1 if there is any kind of error. If the error
 -** is in a system call (i.e. localtime()), then an error message is written
 -** to context pCtx. If the error is an unrecognized modifier, no error is
 -** written to pCtx.
--*/
+ */
 -static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
 -  int rc = 1;
 -  int n;
@@ -4324,7 +4386,62 @@
 -  z = zBuf;
 -  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
 -    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
--  }
++/* BEGIN SQLCIPHER */
++#ifdef SQLITE_HAS_CODEC
++#ifdef SQLCIPHER_CRYPTO_OPENSSL
++#include <openssl/rand.h>
++#include <openssl/evp.h>
++#include <openssl/hmac.h>
++
++typedef struct {
++  EVP_CIPHER *evp_cipher;
++} openssl_ctx;
++
++
++static unsigned int openssl_external_init = 0;
++static unsigned int openssl_init_count = 0;
++static sqlite3_mutex* openssl_rand_mutex = NULL;
++
++static int sqlcipher_openssl_add_random(void *ctx, void *buffer, int length) {
++#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
++  sqlite3_mutex_enter(openssl_rand_mutex);
++#endif
++  RAND_add(buffer, length, 0);
++#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
++  sqlite3_mutex_leave(openssl_rand_mutex);
++#endif
++  return SQLITE_OK;
++}
++
++/* activate and initialize sqlcipher. Most importantly, this will automatically
++   intialize OpenSSL's EVP system if it hasn't already be externally. Note that 
++   this function may be called multiple times as new codecs are intiialized. 
++   Thus it performs some basic counting to ensure that only the last and final
++   sqlcipher_openssl_deactivate() will free the EVP structures. 
++*/
++static int sqlcipher_openssl_activate(void *ctx) {
++  /* initialize openssl and increment the internal init counter
++     but only if it hasn't been initalized outside of SQLCipher by this program 
++     e.g. on startup */
++  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
++
++  if(openssl_init_count == 0 && EVP_get_cipherbyname(CIPHER) != NULL) {
++    /* if openssl has not yet been initialized by this library, but 
++       a call to get_cipherbyname works, then the openssl library
++       has been initialized externally already. */
++    openssl_external_init = 1;
++  }
++
++  if(openssl_init_count == 0 && openssl_external_init == 0)  {
++    /* if the library was not externally initialized, then should be now */
++    OpenSSL_add_all_algorithms();
++  } 
++
++#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
++  if(openssl_rand_mutex == NULL) {
++    /* allocate a mutex to guard against concurrent calls to RAND_bytes() */
++    openssl_rand_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
+   }
 -  z[n] = 0;
 -  switch( z[0] ){
 -#ifndef SQLITE_OMIT_LOCALTIME
@@ -4365,6 +4482,31 @@
 -          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
 -        }
 -      }
++
++  openssl_init_count++; 
++  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
++  return SQLITE_OK;
++}
++
++/* deactivate SQLCipher, most imporantly decremeting the activation count and
++   freeing the EVP structures on the final deactivation to ensure that 
++   OpenSSL memory is cleaned up */
++static int sqlcipher_openssl_deactivate(void *ctx) {
++  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
++  openssl_init_count--;
++
++  if(openssl_init_count == 0) {
++    if(openssl_external_init == 0) {
++    /* if OpenSSL hasn't be initialized externally, and the counter reaches zero 
++       after it's decremented, release EVP memory
++       Note: this code will only be reached if OpensSSL_add_all_algorithms()
++       is called by SQLCipher internally. This should prevent SQLCipher from 
++       "cleaning up" openssl when it was initialized externally by the program */
++      EVP_cleanup();
++    }
++#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
++    sqlite3_mutex_free(openssl_rand_mutex);
++    openssl_rand_mutex = NULL;
  #endif
 -      break;
 -    }
@@ -4507,83 +4649,10 @@
 -    }
 -    default: {
 -      break;
-+/* END SQLCIPHER */
-+
-+/************** End of crypto_libtomcrypt.c **********************************/
-+/************** Begin file crypto_openssl.c **********************************/
-+/*
-+** SQLCipher
-+** http://sqlcipher.net
-+**
-+** Copyright (c) 2008 - 2013, ZETETIC LLC
-+** All rights reserved.
-+**
-+** Redistribution and use in source and binary forms, with or without
-+** modification, are permitted provided that the following conditions are met:
-+**     * Redistributions of source code must retain the above copyright
-+**       notice, this list of conditions and the following disclaimer.
-+**     * Redistributions in binary form must reproduce the above copyright
-+**       notice, this list of conditions and the following disclaimer in the
-+**       documentation and/or other materials provided with the distribution.
-+**     * Neither the name of the ZETETIC LLC nor the
-+**       names of its contributors may be used to endorse or promote products
-+**       derived from this software without specific prior written permission.
-+**
-+** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
-+** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-+** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-+** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
-+** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-+** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-+** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-+** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-+** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-+**
-+*/
-+/* BEGIN SQLCIPHER */
-+#ifdef SQLITE_HAS_CODEC
-+#ifdef SQLCIPHER_CRYPTO_OPENSSL
-+#include <openssl/rand.h>
-+#include <openssl/evp.h>
-+#include <openssl/hmac.h>
-+
-+typedef struct {
-+  EVP_CIPHER *evp_cipher;
-+} openssl_ctx;
-+
-+
-+static unsigned int openssl_external_init = 0;
-+static unsigned int openssl_init_count = 0;
-+
-+
-+static int sqlcipher_openssl_add_random(void *ctx, void *buffer, int length) {
-+  RAND_add(buffer, length, 0);
-+  return SQLITE_OK;
-+}
-+
-+/* activate and initialize sqlcipher. Most importantly, this will automatically
-+   intialize OpenSSL's EVP system if it hasn't already be externally. Note that 
-+   this function may be called multiple times as new codecs are intiialized. 
-+   Thus it performs some basic counting to ensure that only the last and final
-+   sqlcipher_openssl_deactivate() will free the EVP structures. 
-+*/
-+static int sqlcipher_openssl_activate(void *ctx) {
-+  /* we'll initialize openssl and increment the internal init counter
-+     but only if it hasn't been initalized outside of SQLCipher by this program 
-+     e.g. on startup */
-+  if(openssl_init_count == 0 && EVP_get_cipherbyname(CIPHER) != NULL) {
-+    openssl_external_init = 1;
-+  }
-+
-+  if(openssl_external_init == 0) {
-+    if(openssl_init_count == 0)  {
-+      OpenSSL_add_all_algorithms();
-     }
--  }
+-    }
+   }
 -  return rc;
-+    openssl_init_count++; 
-+  } 
++  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
 +  return SQLITE_OK;
  }
  
@@ -4617,43 +4686,34 @@
 -    z = sqlite3_value_text(argv[0]);
 -    if( !z || parseDateOrTime(context, (char*)z, p) ){
 -      return 1;
-+/* deactivate SQLCipher, most imporantly decremeting the activation count and
-+   freeing the EVP structures on the final deactivation to ensure that 
-+   OpenSSL memory is cleaned up */
-+static int sqlcipher_openssl_deactivate(void *ctx) {
-+  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
-+  /* If it is initialized externally, then the init counter should never be greater than zero.
-+     This should prevent SQLCipher from "cleaning up" openssl 
-+     when something else in the program might be using it. */
-+  if(openssl_external_init == 0) {
-+    openssl_init_count--;
-+    /* if the counter reaches zero after it's decremented release EVP memory
-+       Note: this code will only be reached if OpensSSL_add_all_algorithms()
-+       is called by SQLCipher internally. */
-+    if(openssl_init_count == 0) {
-+      EVP_cleanup();
-     }
-   }
+-    }
+-  }
 -  for(i=1; i<argc; i++){
 -    z = sqlite3_value_text(argv[i]);
 -    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
 -  }
 -  return 0;
-+  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
-+  return SQLITE_OK;
- }
- 
 +static const char* sqlcipher_openssl_get_provider_name(void *ctx) {
 +  return "openssl";
-+}
+ }
  
--/*
--** The following routines implement the various date and time functions
--** of SQLite.
--*/
 +/* generate a defined number of random bytes */
 +static int sqlcipher_openssl_random (void *ctx, void *buffer, int length) {
-+  return (RAND_bytes((unsigned char *)buffer, length) == 1) ? SQLITE_OK : SQLITE_ERROR;
++  int rc = 0;
++  /* concurrent calls to RAND_bytes can cause a crash under some openssl versions when a 
++     naive application doesn't use CRYPTO_set_locking_callback and
++     CRYPTO_THREADID_set_callback to ensure openssl thread safety. 
++     This is simple workaround to prevent this common crash
++     but a more proper solution is that applications setup platform-appropriate
++     thread saftey in openssl externally */
++#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
++  sqlite3_mutex_enter(openssl_rand_mutex);
++#endif
++  rc = RAND_bytes((unsigned char *)buffer, length);
++#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
++  sqlite3_mutex_leave(openssl_rand_mutex);
++#endif
++  return (rc == 1) ? SQLITE_OK : SQLITE_ERROR;
 +}
 +
 +static int sqlcipher_openssl_hmac(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int 
in_sz, unsigned char *in2, int in2_sz, unsigned char *out) {
@@ -4669,6 +4729,15 @@
 +}
  
 -/*
+-** The following routines implement the various date and time functions
+-** of SQLite.
+-*/
++static int sqlcipher_openssl_kdf(void *ctx, const char *pass, int pass_sz, unsigned char* salt, int 
salt_sz, int workfactor, int key_sz, unsigned char *key) {
++  PKCS5_PBKDF2_HMAC_SHA1(pass, pass_sz, salt, salt_sz, workfactor, key_sz, key);
++  return SQLITE_OK; 
++}
+ 
+-/*
 -**    julianday( TIMESTRING, MOD, MOD, ...)
 -**
 -** Return the julian day number of the date specified in the arguments
@@ -4683,8 +4752,20 @@
 -    computeJD(&x);
 -    sqlite3_result_double(context, x.iJD/86400000.0);
 -  }
-+static int sqlcipher_openssl_kdf(void *ctx, const char *pass, int pass_sz, unsigned char* salt, int 
salt_sz, int workfactor, int key_sz, unsigned char *key) {
-+  PKCS5_PBKDF2_HMAC_SHA1(pass, pass_sz, salt, salt_sz, workfactor, key_sz, key);
++static int sqlcipher_openssl_cipher(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, 
unsigned char *in, int in_sz, unsigned char *out) {
++  EVP_CIPHER_CTX ectx;
++  int tmp_csz, csz;
++ 
++  EVP_CipherInit(&ectx, ((openssl_ctx *)ctx)->evp_cipher, NULL, NULL, mode);
++  EVP_CIPHER_CTX_set_padding(&ectx, 0); // no padding
++  EVP_CipherInit(&ectx, NULL, key, iv, mode);
++  EVP_CipherUpdate(&ectx, out, &tmp_csz, in, in_sz);
++  csz = tmp_csz;  
++  out += tmp_csz;
++  EVP_CipherFinal(&ectx, out, &tmp_csz);
++  csz += tmp_csz;
++  EVP_CIPHER_CTX_cleanup(&ectx);
++  assert(in_sz == csz);
 +  return SQLITE_OK; 
  }
  
@@ -4706,21 +4787,10 @@
 -                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
 -    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 -  }
-+static int sqlcipher_openssl_cipher(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, 
unsigned char *in, int in_sz, unsigned char *out) {
-+  EVP_CIPHER_CTX ectx;
-+  int tmp_csz, csz;
-+ 
-+  EVP_CipherInit(&ectx, ((openssl_ctx *)ctx)->evp_cipher, NULL, NULL, mode);
-+  EVP_CIPHER_CTX_set_padding(&ectx, 0); // no padding
-+  EVP_CipherInit(&ectx, NULL, key, iv, mode);
-+  EVP_CipherUpdate(&ectx, out, &tmp_csz, in, in_sz);
-+  csz = tmp_csz;  
-+  out += tmp_csz;
-+  EVP_CipherFinal(&ectx, out, &tmp_csz);
-+  csz += tmp_csz;
-+  EVP_CIPHER_CTX_cleanup(&ectx);
-+  assert(in_sz == csz);
-+  return SQLITE_OK; 
++static int sqlcipher_openssl_set_cipher(void *ctx, const char *cipher_name) {
++  openssl_ctx *o_ctx = (openssl_ctx *)ctx;
++  o_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name);
++  return SQLITE_OK;
  }
  
 -/*
@@ -4740,10 +4810,8 @@
 -    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
 -    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 -  }
-+static int sqlcipher_openssl_set_cipher(void *ctx, const char *cipher_name) {
-+  openssl_ctx *o_ctx = (openssl_ctx *)ctx;
-+  o_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name);
-+  return SQLITE_OK;
++static const char* sqlcipher_openssl_get_cipher(void *ctx) {
++  return EVP_CIPHER_name(((openssl_ctx *)ctx)->evp_cipher);
  }
  
 -/*
@@ -4763,8 +4831,8 @@
 -    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
 -    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 -  }
-+static const char* sqlcipher_openssl_get_cipher(void *ctx) {
-+  return EVP_CIPHER_name(((openssl_ctx *)ctx)->evp_cipher);
++static int sqlcipher_openssl_get_key_sz(void *ctx) {
++  return EVP_CIPHER_key_length(((openssl_ctx *)ctx)->evp_cipher);
  }
  
 -/*
@@ -4915,8 +4983,8 @@
 -  z[j] = 0;
 -  sqlite3_result_text(context, z, -1,
 -                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
-+static int sqlcipher_openssl_get_key_sz(void *ctx) {
-+  return EVP_CIPHER_key_length(((openssl_ctx *)ctx)->evp_cipher);
++static int sqlcipher_openssl_get_iv_sz(void *ctx) {
++  return EVP_CIPHER_iv_length(((openssl_ctx *)ctx)->evp_cipher);
  }
  
 -/*
@@ -4931,8 +4999,8 @@
 -){
 -  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 -  timeFunc(context, 0, 0);
-+static int sqlcipher_openssl_get_iv_sz(void *ctx) {
-+  return EVP_CIPHER_iv_length(((openssl_ctx *)ctx)->evp_cipher);
++static int sqlcipher_openssl_get_block_sz(void *ctx) {
++  return EVP_CIPHER_block_size(((openssl_ctx *)ctx)->evp_cipher);
  }
  
 -/*
@@ -4947,8 +5015,8 @@
 -){
 -  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 -  dateFunc(context, 0, 0);
-+static int sqlcipher_openssl_get_block_sz(void *ctx) {
-+  return EVP_CIPHER_block_size(((openssl_ctx *)ctx)->evp_cipher);
++static int sqlcipher_openssl_get_hmac_sz(void *ctx) {
++  return EVP_MD_size(EVP_sha1());
  }
  
 -/*
@@ -4963,11 +5031,12 @@
 -){
 -  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 -  datetimeFunc(context, 0, 0);
-+static int sqlcipher_openssl_get_hmac_sz(void *ctx) {
-+  return EVP_MD_size(EVP_sha1());
++static int sqlcipher_openssl_ctx_copy(void *target_ctx, void *source_ctx) {
++  memcpy(target_ctx, source_ctx, sizeof(openssl_ctx));
++  return SQLITE_OK;
  }
 -#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
- 
+-
 -#ifdef SQLITE_OMIT_DATETIME_FUNCS
 -/*
 -** If the library is compiled to omit the full-scale date and time
@@ -4992,10 +5061,6 @@
 -  struct tm *pTm;
 -  struct tm sNow;
 -  char zBuf[20];
-+static int sqlcipher_openssl_ctx_copy(void *target_ctx, void *source_ctx) {
-+  memcpy(target_ctx, source_ctx, sizeof(openssl_ctx));
-+  return SQLITE_OK;
-+}
  
 -  UNUSED_PARAMETER(argc);
 -  UNUSED_PARAMETER(argv);
@@ -5113,12 +5178,12 @@
 -** from within OsOpen()), but some third-party implementations may.
 -** So we test the effects of a malloc() failing and the sqlite3OsXXX()
 -** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
+-**
+-** The following functions are instrumented for malloc() failure 
+-** testing:
 +** SQLCipher
 +** http://sqlcipher.net
  **
--** The following functions are instrumented for malloc() failure 
--** testing:
--**
 -**     sqlite3OsRead()
 -**     sqlite3OsWrite()
 -**     sqlite3OsSync()
@@ -5195,10 +5260,7 @@
 -SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
 -  DO_OS_MALLOC_TEST(id);
 -  return id->pMethods->xWrite(id, pBuf, amt, offset);
-+/* generate a defined number of random bytes */
-+static int sqlcipher_cc_random (void *ctx, void *buffer, int length) {
-+  return (SecRandomCopyBytes(kSecRandomDefault, length, (uint8_t *)buffer) == 0) ? SQLITE_OK : SQLITE_ERROR;
- }
+-}
 -SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
 -  return id->pMethods->xTruncate(id, size);
 -}
@@ -5209,7 +5271,10 @@
 -SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
 -  DO_OS_MALLOC_TEST(id);
 -  return id->pMethods->xFileSize(id, pSize);
--}
++/* generate a defined number of random bytes */
++static int sqlcipher_cc_random (void *ctx, void *buffer, int length) {
++  return (SecRandomCopyBytes(kSecRandomDefault, length, (uint8_t *)buffer) == 0) ? SQLITE_OK : SQLITE_ERROR;
+ }
 -SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
 -  DO_OS_MALLOC_TEST(id);
 -  return id->pMethods->xLock(id, lockType);
@@ -5932,7 +5997,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -15633,807 +15800,1140 @@
+@@ -15633,807 +15866,1140 @@
  **
  *************************************************************************
  **
@@ -7665,6 +7730,8 @@
  
 -/************** End of mem2.c ************************************************/
 -/************** Begin file mem3.c ********************************************/
+-/*
+-** 2007 October 14
 +          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
 +              pSchema->tblHash.count 
 +            + pSchema->trigHash.count
@@ -7748,13 +7815,12 @@
 +
 +/************** End of status.c **********************************************/
 +/************** Begin file date.c ********************************************/
- /*
--** 2007 October 14
++/*
 +** 2003 October 31
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -16443,1269 +16943,1505 @@
+@@ -16443,1269 +17009,1505 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -10328,7 +10394,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -17715,152 +18451,147 @@
+@@ -17715,152 +18517,147 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -10585,7 +10651,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -17870,205 +18601,278 @@
+@@ -17870,205 +18667,278 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -11014,7 +11080,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -18078,694 +18882,527 @@
+@@ -18078,694 +18948,527 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -12134,7 +12200,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -18775,1904 +19412,1632 @@
+@@ -18775,1904 +19478,1632 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -15388,7 +15454,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -20682,2498 +21047,2601 @@
+@@ -20682,2498 +21113,2601 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -20145,7 +20211,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -23182,13485 +23650,14956 @@
+@@ -23182,13485 +23716,14956 @@
  **    May you find forgiveness for yourself and forgive others.
  **    May you share freely, never taking more than you give.
  **
@@ -46576,7 +46642,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -36670,1019 +38609,1027 @@
+@@ -36670,1019 +38675,1027 @@
  **    May you share freely, never taking more than you give.
  **
  *************************************************************************
@@ -48434,7 +48500,7 @@
  **
  ** The author disclaims copyright to this source code.  In place of
  ** a legal notice, here is a blessing:
-@@ -37693,3176 +39640,3005 @@
+@@ -37693,3176 +39706,3005 @@
  **
  *************************************************************************
  **
@@ -54205,7 +54271,7 @@
        }
      }
    }
-@@ -40870,8409 +42646,8969 @@
+@@ -40870,8409 +42712,8969 @@
  }
  
  /*
@@ -70268,7 +70334,7 @@
  #ifndef SQLITE_OMIT_SHARED_CACHE
  #if SQLITE_THREADSAFE
  
-@@ -88696,10 +91032,24 @@
+@@ -88696,10 +91098,24 @@
  */
  SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
    int rc = sqlite3_overload_function(db, "MATCH", 2);
@@ -70293,7 +70359,7 @@
  }
  
  /*
-@@ -93695,6 +96045,12 @@
+@@ -93695,6 +96111,12 @@
    sqlite3 *db = pParse->db;    /* The database connection */
    Db *pDb;                     /* The specific database being pragmaed */
    Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
@@ -70306,7 +70372,7 @@
  
    if( v==0 ) return;
    sqlite3VdbeRunOnlyOnce(v);
-@@ -93755,6 +96111,13 @@
+@@ -93755,6 +96177,13 @@
      pParse->rc = rc;
    }else
                              
@@ -70320,7 +70386,7 @@
   
  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
    /*
-@@ -94348,60 +96711,6 @@
+@@ -94348,60 +96777,6 @@
  
  #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
    /*


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]