sdb.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /*
  5. * This file implements PKCS 11 on top of our existing security modules
  6. *
  7. * For more information about PKCS 11 See PKCS 11 Token Inteface Standard.
  8. * This implementation has two slots:
  9. * slot 1 is our generic crypto support. It does not require login.
  10. * It supports Public Key ops, and all they bulk ciphers and hashes.
  11. * It can also support Private Key ops for imported Private keys. It does
  12. * not have any token storage.
  13. * slot 2 is our private key support. It requires a login before use. It
  14. * can store Private Keys and Certs as token objects. Currently only private
  15. * keys and their associated Certificates are saved on the token.
  16. *
  17. * In this implementation, session objects are only visible to the session
  18. * that created or generated them.
  19. */
  20. #include "sdb.h"
  21. #include "pkcs11t.h"
  22. #include "seccomon.h"
  23. #include <sqlite3.h>
  24. #include "prthread.h"
  25. #include "prio.h"
  26. #include <stdio.h>
  27. #include "secport.h"
  28. #include "prmon.h"
  29. #include "prenv.h"
  30. #include "prprf.h"
  31. #include "prsystem.h" /* for PR_GetDirectorySeparator() */
  32. #include <sys/stat.h>
  33. #if defined(_WIN32)
  34. #include <io.h>
  35. #include <windows.h>
  36. #elif defined(XP_UNIX)
  37. #include <unistd.h>
  38. #endif
  39. #if defined(LINUX) && !defined(ANDROID)
  40. #include <linux/magic.h>
  41. #include <sys/vfs.h>
  42. #endif
  43. #include "utilpars.h"
  44. #ifdef SQLITE_UNSAFE_THREADS
  45. #include "prlock.h"
  46. /*
  47. * SQLite can be compiled to be thread safe or not.
  48. * turn on SQLITE_UNSAFE_THREADS if the OS does not support
  49. * a thread safe version of sqlite.
  50. */
  51. static PRLock *sqlite_lock = NULL;
  52. #define LOCK_SQLITE() PR_Lock(sqlite_lock);
  53. #define UNLOCK_SQLITE() PR_Unlock(sqlite_lock);
  54. #else
  55. #define LOCK_SQLITE()
  56. #define UNLOCK_SQLITE()
  57. #endif
  58. typedef enum {
  59. SDB_CERT = 1,
  60. SDB_KEY = 2
  61. } sdbDataType;
  62. /*
  63. * defines controlling how long we wait to acquire locks.
  64. *
  65. * SDB_SQLITE_BUSY_TIMEOUT specifies how long (in milliseconds)
  66. * sqlite will wait on lock. If that timeout expires, sqlite will
  67. * return SQLITE_BUSY.
  68. * SDB_BUSY_RETRY_TIME specifies how many seconds the sdb_ code waits
  69. * after receiving a busy before retrying.
  70. * SDB_MAX_BUSY_RETRIES specifies how many times the sdb_ will retry on
  71. * a busy condition.
  72. *
  73. * SDB_SQLITE_BUSY_TIMEOUT affects all opertions, both manual
  74. * (prepare/step/reset/finalize) and automatic (sqlite3_exec()).
  75. * SDB_BUSY_RETRY_TIME and SDB_MAX_BUSY_RETRIES only affect manual operations
  76. *
  77. * total wait time for automatic operations:
  78. * 1 second (SDB_SQLITE_BUSY_TIMEOUT/1000).
  79. * total wait time for manual operations:
  80. * (1 second + 5 seconds) * 10 = 60 seconds.
  81. * (SDB_SQLITE_BUSY_TIMEOUT/1000 + SDB_BUSY_RETRY_TIME)*SDB_MAX_BUSY_RETRIES
  82. */
  83. #define SDB_SQLITE_BUSY_TIMEOUT 1000 /* milliseconds */
  84. #define SDB_BUSY_RETRY_TIME 5 /* seconds */
  85. #define SDB_MAX_BUSY_RETRIES 10
  86. /*
  87. * known attributes
  88. */
  89. static const CK_ATTRIBUTE_TYPE known_attributes[] = {
  90. CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION,
  91. CKA_VALUE, CKA_OBJECT_ID, CKA_CERTIFICATE_TYPE, CKA_ISSUER,
  92. CKA_SERIAL_NUMBER, CKA_AC_ISSUER, CKA_OWNER, CKA_ATTR_TYPES, CKA_TRUSTED,
  93. CKA_CERTIFICATE_CATEGORY, CKA_JAVA_MIDP_SECURITY_DOMAIN, CKA_URL,
  94. CKA_HASH_OF_SUBJECT_PUBLIC_KEY, CKA_HASH_OF_ISSUER_PUBLIC_KEY,
  95. CKA_CHECK_VALUE, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE,
  96. CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER,
  97. CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE,
  98. CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT,
  99. CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT,
  100. CKA_PUBLIC_KEY_INFO, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS,
  101. CKA_SUB_PRIME_BITS, CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_EXTRACTABLE,
  102. CKA_LOCAL, CKA_NEVER_EXTRACTABLE, CKA_ALWAYS_SENSITIVE,
  103. CKA_KEY_GEN_MECHANISM, CKA_MODIFIABLE, CKA_EC_PARAMS,
  104. CKA_EC_POINT, CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
  105. CKA_ALWAYS_AUTHENTICATE, CKA_WRAP_WITH_TRUSTED, CKA_HW_FEATURE_TYPE,
  106. CKA_RESET_ON_INIT, CKA_HAS_RESET, CKA_PIXEL_X, CKA_PIXEL_Y,
  107. CKA_RESOLUTION, CKA_CHAR_ROWS, CKA_CHAR_COLUMNS, CKA_COLOR,
  108. CKA_BITS_PER_PIXEL, CKA_CHAR_SETS, CKA_ENCODING_METHODS, CKA_MIME_TYPES,
  109. CKA_MECHANISM_TYPE, CKA_REQUIRED_CMS_ATTRIBUTES,
  110. CKA_DEFAULT_CMS_ATTRIBUTES, CKA_SUPPORTED_CMS_ATTRIBUTES,
  111. CKA_WRAP_TEMPLATE, CKA_UNWRAP_TEMPLATE, CKA_NSS_TRUST, CKA_NSS_URL,
  112. CKA_NSS_EMAIL, CKA_NSS_SMIME_INFO, CKA_NSS_SMIME_TIMESTAMP,
  113. CKA_NSS_PKCS8_SALT, CKA_NSS_PASSWORD_CHECK, CKA_NSS_EXPIRES,
  114. CKA_NSS_KRL, CKA_NSS_PQG_COUNTER, CKA_NSS_PQG_SEED,
  115. CKA_NSS_PQG_H, CKA_NSS_PQG_SEED_BITS, CKA_NSS_MODULE_SPEC,
  116. CKA_NSS_OVERRIDE_EXTENSIONS, CKA_NSS_SERVER_DISTRUST_AFTER,
  117. CKA_NSS_EMAIL_DISTRUST_AFTER, CKA_TRUST_DIGITAL_SIGNATURE,
  118. CKA_TRUST_NON_REPUDIATION, CKA_TRUST_KEY_ENCIPHERMENT,
  119. CKA_TRUST_DATA_ENCIPHERMENT, CKA_TRUST_KEY_AGREEMENT,
  120. CKA_TRUST_KEY_CERT_SIGN, CKA_TRUST_CRL_SIGN, CKA_TRUST_SERVER_AUTH,
  121. CKA_TRUST_CLIENT_AUTH, CKA_TRUST_CODE_SIGNING, CKA_TRUST_EMAIL_PROTECTION,
  122. CKA_TRUST_IPSEC_END_SYSTEM, CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER,
  123. CKA_TRUST_TIME_STAMPING, CKA_TRUST_STEP_UP_APPROVED, CKA_CERT_SHA1_HASH,
  124. CKA_CERT_MD5_HASH, CKA_NSS_DB
  125. };
  126. static const int known_attributes_size = PR_ARRAY_SIZE(known_attributes);
  127. /*
  128. * Note on use of sqlReadDB: Only one thread at a time may have an actual
  129. * operation going on given sqlite3 * database. An operation is defined as
  130. * the time from a sqlite3_prepare() until the sqlite3_finalize().
  131. * Multiple sqlite3 * databases can be open and have simultaneous operations
  132. * going. We use the sqlXactDB for all write operations. This database
  133. * is only opened when we first create a transaction and closed when the
  134. * transaction is complete. sqlReadDB is open when we first opened the database
  135. * and is used for all read operation. It's use is protected by a monitor. This
  136. * is because an operation can span the use of FindObjectsInit() through the
  137. * call to FindObjectsFinal(). In the intermediate time it is possible to call
  138. * other operations like NSC_GetAttributeValue */
  139. struct SDBPrivateStr {
  140. char *sqlDBName; /* invariant, path to this database */
  141. sqlite3 *sqlXactDB; /* access protected by dbMon, use protected
  142. * by the transaction. Current transaction db*/
  143. PRThread *sqlXactThread; /* protected by dbMon,
  144. * current transaction thread */
  145. sqlite3 *sqlReadDB; /* use protected by dbMon, value invariant */
  146. PRIntervalTime lastUpdateTime; /* last time the cache was updated */
  147. PRIntervalTime updateInterval; /* how long the cache can go before it
  148. * must be updated again */
  149. sdbDataType type; /* invariant, database type */
  150. char *table; /* invariant, SQL table which contains the db */
  151. char *cacheTable; /* invariant, SQL table cache of db */
  152. PRMonitor *dbMon; /* invariant, monitor to protect
  153. * sqlXact* fields, and use of the sqlReadDB */
  154. CK_ATTRIBUTE_TYPE *schemaAttrs; /* Attribute columns that exist in the table. */
  155. unsigned int numSchemaAttrs;
  156. };
  157. typedef struct SDBPrivateStr SDBPrivate;
  158. /* Magic for an explicit NULL. NOTE: ideally this should be
  159. * out of band data. Since it's not completely out of band, pick
  160. * a value that has no meaning to any existing PKCS #11 attributes.
  161. * This value is 1) not a valid string (imbedded '\0'). 2) not a U_LONG
  162. * or a normal key (too short). 3) not a bool (too long). 4) not an RSA
  163. * public exponent (too many bits).
  164. */
  165. const unsigned char SQLITE_EXPLICIT_NULL[] = { 0xa5, 0x0, 0x5a };
  166. #define SQLITE_EXPLICIT_NULL_LEN 3
  167. /*
  168. * determine when we've completed our tasks
  169. */
  170. static int
  171. sdb_done(int err, int *count)
  172. {
  173. /* allow as many rows as the database wants to give */
  174. if (err == SQLITE_ROW) {
  175. *count = 0;
  176. return 0;
  177. }
  178. if (err != SQLITE_BUSY) {
  179. return 1;
  180. }
  181. /* err == SQLITE_BUSY, Dont' retry forever in this case */
  182. if (++(*count) >= SDB_MAX_BUSY_RETRIES) {
  183. return 1;
  184. }
  185. return 0;
  186. }
  187. #if defined(_WIN32)
  188. /*
  189. * NSPR functions and narrow CRT functions do not handle UTF-8 file paths that
  190. * sqlite3 expects.
  191. */
  192. static int
  193. sdb_chmod(const char *filename, int pmode)
  194. {
  195. int result;
  196. if (!filename) {
  197. return -1;
  198. }
  199. wchar_t *filenameWide = _NSSUTIL_UTF8ToWide(filename);
  200. if (!filenameWide) {
  201. return -1;
  202. }
  203. result = _wchmod(filenameWide, pmode);
  204. PORT_Free(filenameWide);
  205. return result;
  206. }
  207. #else
  208. #define sdb_chmod(filename, pmode) chmod((filename), (pmode))
  209. #endif
  210. /*
  211. * find out where sqlite stores the temp tables. We do this by replicating
  212. * the logic from sqlite.
  213. */
  214. #if defined(_WIN32)
  215. static char *
  216. sdb_getFallbackTempDir(void)
  217. {
  218. /* sqlite uses sqlite3_temp_directory if it is not NULL. We don't have
  219. * access to sqlite3_temp_directory because it is not exported from
  220. * sqlite3.dll. Assume sqlite3_win32_set_directory isn't called and
  221. * sqlite3_temp_directory is NULL.
  222. */
  223. char path[MAX_PATH];
  224. DWORD rv;
  225. size_t len;
  226. rv = GetTempPathA(MAX_PATH, path);
  227. if (rv > MAX_PATH || rv == 0)
  228. return NULL;
  229. len = strlen(path);
  230. if (len == 0)
  231. return NULL;
  232. /* The returned string ends with a backslash, for example, "C:\TEMP\". */
  233. if (path[len - 1] == '\\')
  234. path[len - 1] = '\0';
  235. return PORT_Strdup(path);
  236. }
  237. #elif defined(XP_UNIX)
  238. static char *
  239. sdb_getFallbackTempDir(void)
  240. {
  241. const char *azDirs[] = {
  242. NULL,
  243. NULL,
  244. "/var/tmp",
  245. "/usr/tmp",
  246. "/tmp",
  247. NULL /* List terminator */
  248. };
  249. unsigned int i;
  250. struct stat buf;
  251. const char *zDir = NULL;
  252. azDirs[0] = sqlite3_temp_directory;
  253. azDirs[1] = PR_GetEnvSecure("TMPDIR");
  254. for (i = 0; i < PR_ARRAY_SIZE(azDirs); i++) {
  255. zDir = azDirs[i];
  256. if (zDir == NULL)
  257. continue;
  258. if (stat(zDir, &buf))
  259. continue;
  260. if (!S_ISDIR(buf.st_mode))
  261. continue;
  262. if (access(zDir, 07))
  263. continue;
  264. break;
  265. }
  266. if (zDir == NULL)
  267. return NULL;
  268. return PORT_Strdup(zDir);
  269. }
  270. #else
  271. #error "sdb_getFallbackTempDir not implemented"
  272. #endif
  273. #ifndef SQLITE_FCNTL_TEMPFILENAME
  274. /* SQLITE_FCNTL_TEMPFILENAME was added in SQLite 3.7.15 */
  275. #define SQLITE_FCNTL_TEMPFILENAME 16
  276. #endif
  277. static char *
  278. sdb_getTempDir(sqlite3 *sqlDB)
  279. {
  280. int sqlrv;
  281. char *result = NULL;
  282. char *tempName = NULL;
  283. char *foundSeparator = NULL;
  284. /* Obtain temporary filename in sqlite's directory for temporary tables */
  285. sqlrv = sqlite3_file_control(sqlDB, 0, SQLITE_FCNTL_TEMPFILENAME,
  286. (void *)&tempName);
  287. if (sqlrv == SQLITE_NOTFOUND) {
  288. /* SQLITE_FCNTL_TEMPFILENAME not implemented because we are using
  289. * an older SQLite. */
  290. return sdb_getFallbackTempDir();
  291. }
  292. if (sqlrv != SQLITE_OK) {
  293. return NULL;
  294. }
  295. /* We'll extract the temporary directory from tempName */
  296. foundSeparator = PORT_Strrchr(tempName, PR_GetDirectorySeparator());
  297. if (foundSeparator) {
  298. /* We shorten the temp filename string to contain only
  299. * the directory name (including the trailing separator).
  300. * We know the byte after the foundSeparator position is
  301. * safe to use, in the shortest scenario it contains the
  302. * end-of-string byte.
  303. * By keeping the separator at the found position, it will
  304. * even work if tempDir consists of the separator, only.
  305. * (In this case the toplevel directory will be used for
  306. * access speed testing). */
  307. ++foundSeparator;
  308. *foundSeparator = 0;
  309. /* Now we copy the directory name for our caller */
  310. result = PORT_Strdup(tempName);
  311. }
  312. sqlite3_free(tempName);
  313. return result;
  314. }
  315. /*
  316. * Map SQL_LITE errors to PKCS #11 errors as best we can.
  317. */
  318. static CK_RV
  319. sdb_mapSQLError(sdbDataType type, int sqlerr)
  320. {
  321. switch (sqlerr) {
  322. /* good matches */
  323. case SQLITE_OK:
  324. case SQLITE_DONE:
  325. return CKR_OK;
  326. case SQLITE_NOMEM:
  327. return CKR_HOST_MEMORY;
  328. case SQLITE_READONLY:
  329. return CKR_TOKEN_WRITE_PROTECTED;
  330. /* close matches */
  331. case SQLITE_AUTH:
  332. case SQLITE_PERM:
  333. /*return CKR_USER_NOT_LOGGED_IN; */
  334. case SQLITE_CANTOPEN:
  335. case SQLITE_NOTFOUND:
  336. /* NSS distiguishes between failure to open the cert and the key db */
  337. return type == SDB_CERT ? CKR_NSS_CERTDB_FAILED : CKR_NSS_KEYDB_FAILED;
  338. case SQLITE_IOERR:
  339. return CKR_DEVICE_ERROR;
  340. default:
  341. break;
  342. }
  343. return CKR_GENERAL_ERROR;
  344. }
  345. /*
  346. * build up database name from a directory, prefix, name, version and flags.
  347. */
  348. static char *
  349. sdb_BuildFileName(const char *directory,
  350. const char *prefix, const char *type,
  351. int version)
  352. {
  353. char *dbname = NULL;
  354. /* build the full dbname */
  355. dbname = sqlite3_mprintf("%s%c%s%s%d.db", directory,
  356. (int)(unsigned char)PR_GetDirectorySeparator(),
  357. prefix, type, version);
  358. return dbname;
  359. }
  360. /*
  361. * find out how expensive the access system call is for non-existant files
  362. * in the given directory. Return the number of operations done in 33 ms.
  363. */
  364. static PRUint32
  365. sdb_measureAccess(const char *directory)
  366. {
  367. PRUint32 i;
  368. PRIntervalTime time;
  369. PRIntervalTime delta;
  370. PRIntervalTime duration = PR_MillisecondsToInterval(33);
  371. const char *doesntExistName = "_dOeSnotExist_.db";
  372. char *temp, *tempStartOfFilename;
  373. size_t maxTempLen, maxFileNameLen, directoryLength, tmpdirLength = 0;
  374. #ifdef SDB_MEASURE_USE_TEMP_DIR
  375. /*
  376. * on some OS's and Filesystems, creating a bunch of files and deleting
  377. * them messes up the systems's caching, but if we create the files in
  378. * a temp directory which we later delete, then the cache gets cleared
  379. * up. This code uses several OS dependent calls, and it's not clear
  380. * that temp directory use won't mess up other filesystems and OS caching,
  381. * so if you need this for your OS, you can turn on the
  382. * 'SDB_MEASURE_USE_TEMP_DIR' define in coreconf
  383. */
  384. const char template[] = "dbTemp.XXXXXX";
  385. tmpdirLength = sizeof(template);
  386. #endif
  387. /* no directory, just return one */
  388. if (directory == NULL) {
  389. return 1;
  390. }
  391. /* our calculation assumes time is a 4 bytes == 32 bit integer */
  392. PORT_Assert(sizeof(time) == 4);
  393. directoryLength = strlen(directory);
  394. maxTempLen = directoryLength + 1 /* dirname + / */
  395. + tmpdirLength /* tmpdirname includes / */
  396. + strlen(doesntExistName) /* filename base */
  397. + 11 /* max chars for 32 bit int plus potential sign */
  398. + 1; /* zero terminator */
  399. temp = PORT_ZAlloc(maxTempLen);
  400. if (!temp) {
  401. return 1;
  402. }
  403. /* We'll copy directory into temp just once, then ensure it ends
  404. * with the directory separator. */
  405. strcpy(temp, directory);
  406. if (directory[directoryLength - 1] != PR_GetDirectorySeparator()) {
  407. temp[directoryLength++] = PR_GetDirectorySeparator();
  408. }
  409. #ifdef SDB_MEASURE_USE_TEMP_DIR
  410. /* add the template for a temporary subdir, and create it */
  411. strcat(temp, template);
  412. if (!mkdtemp(temp)) {
  413. PORT_Free(temp);
  414. return 1;
  415. }
  416. /* and terminate that tmp subdir with a / */
  417. strcat(temp, "/");
  418. #endif
  419. /* Remember the position after the last separator, and calculate the
  420. * number of remaining bytes. */
  421. tempStartOfFilename = temp + directoryLength + tmpdirLength;
  422. maxFileNameLen = maxTempLen - directoryLength;
  423. /* measure number of Access operations that can be done in 33 milliseconds
  424. * (1/30'th of a second), or 10000 operations, which ever comes first.
  425. */
  426. time = PR_IntervalNow();
  427. for (i = 0; i < 10000u; i++) {
  428. PRIntervalTime next;
  429. /* We'll use the variable part first in the filename string, just in
  430. * case it's longer than assumed, so if anything gets cut off, it
  431. * will be cut off from the constant part.
  432. * This code assumes the directory name at the beginning of
  433. * temp remains unchanged during our loop. */
  434. PR_snprintf(tempStartOfFilename, maxFileNameLen,
  435. ".%lu%s", (PRUint32)(time + i), doesntExistName);
  436. PR_Access(temp, PR_ACCESS_EXISTS);
  437. next = PR_IntervalNow();
  438. delta = next - time;
  439. if (delta >= duration)
  440. break;
  441. }
  442. #ifdef SDB_MEASURE_USE_TEMP_DIR
  443. /* turn temp back into our tmpdir path by removing doesntExistName, and
  444. * remove the tmp dir */
  445. *tempStartOfFilename = '\0';
  446. (void)rmdir(temp);
  447. #endif
  448. PORT_Free(temp);
  449. /* always return 1 or greater */
  450. return i ? i : 1u;
  451. }
  452. /*
  453. * some file sytems are very slow to run sqlite3 on, particularly if the
  454. * access count is pretty high. On these filesystems is faster to create
  455. * a temporary database on the local filesystem and access that. This
  456. * code uses a temporary table to create that cache. Temp tables are
  457. * automatically cleared when the database handle it was created on
  458. * Is freed.
  459. */
  460. static const char DROP_CACHE_CMD[] = "DROP TABLE %s";
  461. static const char CREATE_CACHE_CMD[] =
  462. "CREATE TEMPORARY TABLE %s AS SELECT * FROM %s";
  463. static const char CREATE_ISSUER_INDEX_CMD[] =
  464. "CREATE INDEX issuer ON %s (a81)";
  465. static const char CREATE_SUBJECT_INDEX_CMD[] =
  466. "CREATE INDEX subject ON %s (a101)";
  467. static const char CREATE_LABEL_INDEX_CMD[] = "CREATE INDEX label ON %s (a3)";
  468. static const char CREATE_ID_INDEX_CMD[] = "CREATE INDEX ckaid ON %s (a102)";
  469. static CK_RV
  470. sdb_buildCache(sqlite3 *sqlDB, sdbDataType type,
  471. const char *cacheTable, const char *table)
  472. {
  473. char *newStr;
  474. int sqlerr = SQLITE_OK;
  475. newStr = sqlite3_mprintf(CREATE_CACHE_CMD, cacheTable, table);
  476. if (newStr == NULL) {
  477. return CKR_HOST_MEMORY;
  478. }
  479. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  480. sqlite3_free(newStr);
  481. if (sqlerr != SQLITE_OK) {
  482. return sdb_mapSQLError(type, sqlerr);
  483. }
  484. /* failure to create the indexes is not an issue */
  485. newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, cacheTable);
  486. if (newStr == NULL) {
  487. return CKR_OK;
  488. }
  489. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  490. sqlite3_free(newStr);
  491. newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, cacheTable);
  492. if (newStr == NULL) {
  493. return CKR_OK;
  494. }
  495. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  496. sqlite3_free(newStr);
  497. newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, cacheTable);
  498. if (newStr == NULL) {
  499. return CKR_OK;
  500. }
  501. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  502. sqlite3_free(newStr);
  503. newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, cacheTable);
  504. if (newStr == NULL) {
  505. return CKR_OK;
  506. }
  507. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  508. sqlite3_free(newStr);
  509. return CKR_OK;
  510. }
  511. /*
  512. * update the cache and the data records describing it.
  513. * The cache is updated by dropping the temp database and recreating it.
  514. */
  515. static CK_RV
  516. sdb_updateCache(SDBPrivate *sdb_p)
  517. {
  518. int sqlerr = SQLITE_OK;
  519. CK_RV error = CKR_OK;
  520. char *newStr;
  521. /* drop the old table */
  522. newStr = sqlite3_mprintf(DROP_CACHE_CMD, sdb_p->cacheTable);
  523. if (newStr == NULL) {
  524. return CKR_HOST_MEMORY;
  525. }
  526. sqlerr = sqlite3_exec(sdb_p->sqlReadDB, newStr, NULL, 0, NULL);
  527. sqlite3_free(newStr);
  528. if ((sqlerr != SQLITE_OK) && (sqlerr != SQLITE_ERROR)) {
  529. /* something went wrong with the drop, don't try to refresh...
  530. * NOTE: SQLITE_ERROR is returned if the table doesn't exist. In
  531. * that case, we just continue on and try to reload it */
  532. return sdb_mapSQLError(sdb_p->type, sqlerr);
  533. }
  534. /* set up the new table */
  535. error = sdb_buildCache(sdb_p->sqlReadDB, sdb_p->type,
  536. sdb_p->cacheTable, sdb_p->table);
  537. if (error == CKR_OK) {
  538. /* we have a new cache! */
  539. sdb_p->lastUpdateTime = PR_IntervalNow();
  540. }
  541. return error;
  542. }
  543. /*
  544. * The sharing of sqlite3 handles across threads is tricky. Older versions
  545. * couldn't at all, but newer ones can under strict conditions. Basically
  546. * no 2 threads can use the same handle while another thread has an open
  547. * stmt running. Once the sqlite3_stmt is finalized, another thread can then
  548. * use the database handle.
  549. *
  550. * We use monitors to protect against trying to use a database before
  551. * it's sqlite3_stmt is finalized. This is preferable to the opening and
  552. * closing the database each operation because there is significant overhead
  553. * in the open and close. Also continually opening and closing the database
  554. * defeats the cache code as the cache table is lost on close (thus
  555. * requiring us to have to reinitialize the cache every operation).
  556. *
  557. * An execption to the shared handle is transations. All writes happen
  558. * through a transaction. When we are in a transaction, we must use the
  559. * same database pointer for that entire transation. In this case we save
  560. * the transaction database and use it for all accesses on the transaction
  561. * thread. Other threads use the common database.
  562. *
  563. * There can only be once active transaction on the database at a time.
  564. *
  565. * sdb_openDBLocal() provides us with a valid database handle for whatever
  566. * state we are in (reading or in a transaction), and acquires any locks
  567. * appropriate to that state. It also decides when it's time to refresh
  568. * the cache before we start an operation. Any database handle returned
  569. * just eventually be closed with sdb_closeDBLocal().
  570. *
  571. * The table returned either points to the database's physical table, or
  572. * to the cached shadow. Tranactions always return the physical table
  573. * and read operations return either the physical table or the cache
  574. * depending on whether or not the cache exists.
  575. */
  576. static CK_RV
  577. sdb_openDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB, const char **table)
  578. {
  579. *sqlDB = NULL;
  580. PR_EnterMonitor(sdb_p->dbMon);
  581. if (table) {
  582. *table = sdb_p->table;
  583. }
  584. /* We're in a transaction, use the transaction DB */
  585. if ((sdb_p->sqlXactDB) && (sdb_p->sqlXactThread == PR_GetCurrentThread())) {
  586. *sqlDB = sdb_p->sqlXactDB;
  587. /* only one thread can get here, safe to unlock */
  588. PR_ExitMonitor(sdb_p->dbMon);
  589. return CKR_OK;
  590. }
  591. /*
  592. * if we are just reading from the table, we may have the table
  593. * cached in a temporary table (especially if it's on a shared FS).
  594. * In that case we want to see updates to the table, the the granularity
  595. * is on order of human scale, not computer scale.
  596. */
  597. if (table && sdb_p->cacheTable) {
  598. PRIntervalTime now = PR_IntervalNow();
  599. if ((now - sdb_p->lastUpdateTime) > sdb_p->updateInterval) {
  600. sdb_updateCache(sdb_p);
  601. }
  602. *table = sdb_p->cacheTable;
  603. }
  604. *sqlDB = sdb_p->sqlReadDB;
  605. /* leave holding the lock. only one thread can actually use a given
  606. * database connection at once */
  607. return CKR_OK;
  608. }
  609. /* closing the local database currenly means unlocking the monitor */
  610. static CK_RV
  611. sdb_closeDBLocal(SDBPrivate *sdb_p, sqlite3 *sqlDB)
  612. {
  613. if (sdb_p->sqlXactDB != sqlDB) {
  614. /* if we weren't in a transaction, we got a lock */
  615. PR_ExitMonitor(sdb_p->dbMon);
  616. }
  617. return CKR_OK;
  618. }
  619. /*
  620. * wrapper to sqlite3_open which also sets the busy_timeout
  621. */
  622. static int
  623. sdb_openDB(const char *name, sqlite3 **sqlDB, int flags)
  624. {
  625. int sqlerr;
  626. int openFlags;
  627. *sqlDB = NULL;
  628. if (flags & SDB_RDONLY) {
  629. openFlags = SQLITE_OPEN_READONLY;
  630. } else {
  631. openFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  632. }
  633. /* Requires SQLite 3.5.0 or newer. */
  634. sqlerr = sqlite3_open_v2(name, sqlDB, openFlags, NULL);
  635. if (sqlerr != SQLITE_OK) {
  636. return sqlerr;
  637. }
  638. sqlerr = sqlite3_busy_timeout(*sqlDB, SDB_SQLITE_BUSY_TIMEOUT);
  639. if (sqlerr != SQLITE_OK) {
  640. sqlite3_close(*sqlDB);
  641. *sqlDB = NULL;
  642. return sqlerr;
  643. }
  644. return SQLITE_OK;
  645. }
  646. /* Sigh, if we created a new table since we opened the database,
  647. * the database handle will not see the new table, we need to close this
  648. * database and reopen it. Caller must be in a transaction or holding
  649. * the dbMon. sqlDB is changed on success. */
  650. static int
  651. sdb_reopenDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB)
  652. {
  653. sqlite3 *newDB;
  654. int sqlerr;
  655. /* open a new database */
  656. sqlerr = sdb_openDB(sdb_p->sqlDBName, &newDB, SDB_RDONLY);
  657. if (sqlerr != SQLITE_OK) {
  658. return sqlerr;
  659. }
  660. /* if we are in a transaction, we may not be holding the monitor.
  661. * grab it before we update the transaction database. This is
  662. * safe since are using monitors. */
  663. PR_EnterMonitor(sdb_p->dbMon);
  664. /* update our view of the database */
  665. if (sdb_p->sqlReadDB == *sqlDB) {
  666. sdb_p->sqlReadDB = newDB;
  667. } else if (sdb_p->sqlXactDB == *sqlDB) {
  668. sdb_p->sqlXactDB = newDB;
  669. }
  670. PR_ExitMonitor(sdb_p->dbMon);
  671. /* close the old one */
  672. sqlite3_close(*sqlDB);
  673. *sqlDB = newDB;
  674. return SQLITE_OK;
  675. }
  676. struct SDBFindStr {
  677. sqlite3 *sqlDB;
  678. sqlite3_stmt *findstmt;
  679. };
  680. static const char FIND_OBJECTS_CMD[] = "SELECT ALL id FROM %s WHERE %s;";
  681. static const char FIND_OBJECTS_ALL_CMD[] = "SELECT ALL id FROM %s;";
  682. CK_RV
  683. sdb_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *template, CK_ULONG count,
  684. SDBFind **find)
  685. {
  686. SDBPrivate *sdb_p = sdb->private;
  687. sqlite3 *sqlDB = NULL;
  688. const char *table;
  689. char *newStr, *findStr = NULL;
  690. sqlite3_stmt *findstmt = NULL;
  691. char *join = "";
  692. int sqlerr = SQLITE_OK;
  693. CK_RV error = CKR_OK;
  694. unsigned int i;
  695. LOCK_SQLITE()
  696. *find = NULL;
  697. error = sdb_openDBLocal(sdb_p, &sqlDB, &table);
  698. if (error != CKR_OK) {
  699. goto loser;
  700. }
  701. findStr = sqlite3_mprintf("");
  702. for (i = 0; findStr && i < count; i++) {
  703. newStr = sqlite3_mprintf("%s%sa%x=$DATA%d", findStr, join,
  704. template[i].type, i);
  705. join = " AND ";
  706. sqlite3_free(findStr);
  707. findStr = newStr;
  708. }
  709. if (findStr == NULL) {
  710. error = CKR_HOST_MEMORY;
  711. goto loser;
  712. }
  713. if (count == 0) {
  714. newStr = sqlite3_mprintf(FIND_OBJECTS_ALL_CMD, table);
  715. } else {
  716. newStr = sqlite3_mprintf(FIND_OBJECTS_CMD, table, findStr);
  717. }
  718. sqlite3_free(findStr);
  719. if (newStr == NULL) {
  720. error = CKR_HOST_MEMORY;
  721. goto loser;
  722. }
  723. sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &findstmt, NULL);
  724. sqlite3_free(newStr);
  725. for (i = 0; sqlerr == SQLITE_OK && i < count; i++) {
  726. const void *blobData = template[i].pValue;
  727. unsigned int blobSize = template[i].ulValueLen;
  728. if (blobSize == 0) {
  729. blobSize = SQLITE_EXPLICIT_NULL_LEN;
  730. blobData = SQLITE_EXPLICIT_NULL;
  731. }
  732. sqlerr = sqlite3_bind_blob(findstmt, i + 1, blobData, blobSize,
  733. SQLITE_TRANSIENT);
  734. }
  735. if (sqlerr == SQLITE_OK) {
  736. *find = PORT_New(SDBFind);
  737. if (*find == NULL) {
  738. error = CKR_HOST_MEMORY;
  739. goto loser;
  740. }
  741. (*find)->findstmt = findstmt;
  742. (*find)->sqlDB = sqlDB;
  743. UNLOCK_SQLITE()
  744. return CKR_OK;
  745. }
  746. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  747. loser:
  748. if (findstmt) {
  749. sqlite3_reset(findstmt);
  750. sqlite3_finalize(findstmt);
  751. }
  752. if (sqlDB) {
  753. sdb_closeDBLocal(sdb_p, sqlDB);
  754. }
  755. UNLOCK_SQLITE()
  756. return error;
  757. }
  758. CK_RV
  759. sdb_FindObjects(SDB *sdb, SDBFind *sdbFind, CK_OBJECT_HANDLE *object,
  760. CK_ULONG arraySize, CK_ULONG *count)
  761. {
  762. SDBPrivate *sdb_p = sdb->private;
  763. sqlite3_stmt *stmt = sdbFind->findstmt;
  764. int sqlerr = SQLITE_OK;
  765. int retry = 0;
  766. *count = 0;
  767. if (arraySize == 0) {
  768. return CKR_OK;
  769. }
  770. LOCK_SQLITE()
  771. do {
  772. sqlerr = sqlite3_step(stmt);
  773. if (sqlerr == SQLITE_BUSY) {
  774. PR_Sleep(SDB_BUSY_RETRY_TIME);
  775. }
  776. if (sqlerr == SQLITE_ROW) {
  777. /* only care about the id */
  778. *object++ = sqlite3_column_int(stmt, 0);
  779. arraySize--;
  780. (*count)++;
  781. }
  782. } while (!sdb_done(sqlerr, &retry) && (arraySize > 0));
  783. /* we only have some of the objects, there is probably more,
  784. * set the sqlerr to an OK value so we return CKR_OK */
  785. if (sqlerr == SQLITE_ROW && arraySize == 0) {
  786. sqlerr = SQLITE_DONE;
  787. }
  788. UNLOCK_SQLITE()
  789. return sdb_mapSQLError(sdb_p->type, sqlerr);
  790. }
  791. CK_RV
  792. sdb_FindObjectsFinal(SDB *sdb, SDBFind *sdbFind)
  793. {
  794. SDBPrivate *sdb_p = sdb->private;
  795. sqlite3_stmt *stmt = sdbFind->findstmt;
  796. sqlite3 *sqlDB = sdbFind->sqlDB;
  797. int sqlerr = SQLITE_OK;
  798. LOCK_SQLITE()
  799. if (stmt) {
  800. sqlite3_reset(stmt);
  801. sqlerr = sqlite3_finalize(stmt);
  802. }
  803. if (sqlDB) {
  804. sdb_closeDBLocal(sdb_p, sqlDB);
  805. }
  806. PORT_Free(sdbFind);
  807. UNLOCK_SQLITE()
  808. return sdb_mapSQLError(sdb_p->type, sqlerr);
  809. }
  810. static CK_RV
  811. sdb_GetValidAttributeValueNoLock(SDB *sdb, CK_OBJECT_HANDLE object_id,
  812. CK_ATTRIBUTE *template, CK_ULONG count)
  813. {
  814. SDBPrivate *sdb_p = sdb->private;
  815. sqlite3 *sqlDB = NULL;
  816. sqlite3_stmt *stmt = NULL;
  817. const char *table = NULL;
  818. int sqlerr = SQLITE_OK;
  819. CK_RV error = CKR_OK;
  820. int found = 0;
  821. int retry = 0;
  822. unsigned int i;
  823. if (count == 0) {
  824. error = CKR_OBJECT_HANDLE_INVALID;
  825. goto loser;
  826. }
  827. /* open a new db if necessary */
  828. error = sdb_openDBLocal(sdb_p, &sqlDB, &table);
  829. if (error != CKR_OK) {
  830. goto loser;
  831. }
  832. char *columns = NULL;
  833. for (i = 0; i < count; i++) {
  834. char *newColumns;
  835. if (columns) {
  836. newColumns = sqlite3_mprintf("%s, a%x", columns, template[i].type);
  837. sqlite3_free(columns);
  838. columns = NULL;
  839. } else {
  840. newColumns = sqlite3_mprintf("a%x", template[i].type);
  841. }
  842. if (!newColumns) {
  843. error = CKR_HOST_MEMORY;
  844. goto loser;
  845. }
  846. columns = newColumns;
  847. }
  848. PORT_Assert(columns);
  849. char *statement = sqlite3_mprintf("SELECT DISTINCT %s FROM %s where id=$ID LIMIT 1;",
  850. columns, table);
  851. sqlite3_free(columns);
  852. columns = NULL;
  853. if (!statement) {
  854. error = CKR_HOST_MEMORY;
  855. goto loser;
  856. }
  857. sqlerr = sqlite3_prepare_v2(sqlDB, statement, -1, &stmt, NULL);
  858. sqlite3_free(statement);
  859. statement = NULL;
  860. if (sqlerr != SQLITE_OK) {
  861. goto loser;
  862. }
  863. // NB: indices in sqlite3_bind_int are 1-indexed
  864. sqlerr = sqlite3_bind_int(stmt, 1, object_id);
  865. if (sqlerr != SQLITE_OK) {
  866. goto loser;
  867. }
  868. do {
  869. sqlerr = sqlite3_step(stmt);
  870. if (sqlerr == SQLITE_BUSY) {
  871. PR_Sleep(SDB_BUSY_RETRY_TIME);
  872. }
  873. if (sqlerr == SQLITE_ROW) {
  874. PORT_Assert(!found);
  875. for (i = 0; i < count; i++) {
  876. unsigned int blobSize;
  877. const char *blobData;
  878. // NB: indices in sqlite_column_{bytes,blob} are 0-indexed
  879. blobSize = sqlite3_column_bytes(stmt, i);
  880. blobData = sqlite3_column_blob(stmt, i);
  881. if (blobData == NULL) {
  882. /* PKCS 11 requires that get attributes process all the
  883. * attributes in the template, marking the attributes with
  884. * issues with -1. Mark the error but continue */
  885. template[i].ulValueLen = -1;
  886. error = CKR_ATTRIBUTE_TYPE_INVALID;
  887. continue;
  888. }
  889. /* If the blob equals our explicit NULL value, then the
  890. * attribute is a NULL. */
  891. if ((blobSize == SQLITE_EXPLICIT_NULL_LEN) &&
  892. (PORT_Memcmp(blobData, SQLITE_EXPLICIT_NULL,
  893. SQLITE_EXPLICIT_NULL_LEN) == 0)) {
  894. blobSize = 0;
  895. }
  896. if (template[i].pValue) {
  897. if (template[i].ulValueLen < blobSize) {
  898. /* like CKR_ATTRIBUTE_TYPE_INVALID, continue processing */
  899. template[i].ulValueLen = -1;
  900. error = CKR_BUFFER_TOO_SMALL;
  901. continue;
  902. }
  903. PORT_Memcpy(template[i].pValue, blobData, blobSize);
  904. }
  905. template[i].ulValueLen = blobSize;
  906. }
  907. found = 1;
  908. }
  909. } while (!sdb_done(sqlerr, &retry));
  910. sqlite3_reset(stmt);
  911. sqlite3_finalize(stmt);
  912. stmt = NULL;
  913. loser:
  914. /* fix up the error if necessary */
  915. if (error == CKR_OK) {
  916. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  917. if (!found && error == CKR_OK) {
  918. error = CKR_OBJECT_HANDLE_INVALID;
  919. }
  920. }
  921. if (stmt) {
  922. sqlite3_reset(stmt);
  923. sqlite3_finalize(stmt);
  924. }
  925. /* if we had to open a new database, free it now */
  926. if (sqlDB) {
  927. sdb_closeDBLocal(sdb_p, sqlDB);
  928. }
  929. return error;
  930. }
  931. /* NOTE: requires sdb_p->schemaAttrs to be sorted asc. */
  932. inline static PRBool
  933. sdb_attributeExists(SDB *sdb, CK_ATTRIBUTE_TYPE attr)
  934. {
  935. SDBPrivate *sdb_p = sdb->private;
  936. int first = 0;
  937. int last = (int)sdb_p->numSchemaAttrs - 1;
  938. while (last >= first) {
  939. int mid = first + (last - first) / 2;
  940. if (sdb_p->schemaAttrs[mid] == attr) {
  941. return PR_TRUE;
  942. }
  943. if (attr > sdb_p->schemaAttrs[mid]) {
  944. first = mid + 1;
  945. } else {
  946. last = mid - 1;
  947. }
  948. }
  949. return PR_FALSE;
  950. }
  951. CK_RV
  952. sdb_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id,
  953. CK_ATTRIBUTE *template, CK_ULONG count)
  954. {
  955. CK_RV crv = CKR_OK;
  956. unsigned int tmplIdx;
  957. unsigned int resIdx = 0;
  958. unsigned int validCount = 0;
  959. unsigned int i;
  960. if (count == 0) {
  961. return crv;
  962. }
  963. CK_ATTRIBUTE *validTemplate;
  964. PRBool invalidExists = PR_FALSE;
  965. for (tmplIdx = 0; tmplIdx < count; tmplIdx++) {
  966. if (!sdb_attributeExists(sdb, template[tmplIdx].type)) {
  967. template[tmplIdx].ulValueLen = -1;
  968. crv = CKR_ATTRIBUTE_TYPE_INVALID;
  969. invalidExists = PR_TRUE;
  970. break;
  971. }
  972. }
  973. if (!invalidExists) {
  974. validTemplate = template;
  975. validCount = count;
  976. } else {
  977. /* Create a new template containing only the valid subset of
  978. * input |template|, and query with that. */
  979. validCount = tmplIdx;
  980. validTemplate = malloc(sizeof(CK_ATTRIBUTE) * count);
  981. if (!validTemplate) {
  982. return CKR_HOST_MEMORY;
  983. }
  984. /* Copy in what we already know is valid. */
  985. for (i = 0; i < validCount; i++) {
  986. validTemplate[i] = template[i];
  987. }
  988. /* tmplIdx was left at the index of the first invalid
  989. * attribute, which has been handled. We only need to
  990. * deal with the remainder. */
  991. tmplIdx++;
  992. for (; tmplIdx < count; tmplIdx++) {
  993. if (sdb_attributeExists(sdb, template[tmplIdx].type)) {
  994. validTemplate[validCount++] = template[tmplIdx];
  995. } else {
  996. template[tmplIdx].ulValueLen = -1;
  997. }
  998. }
  999. }
  1000. if (validCount) {
  1001. LOCK_SQLITE()
  1002. CK_RV crv2 = sdb_GetValidAttributeValueNoLock(sdb, object_id, validTemplate, validCount);
  1003. UNLOCK_SQLITE()
  1004. /* If an invalid attribute was removed above, let
  1005. * the caller know. Any other error from the actual
  1006. * query should propogate. */
  1007. crv = (crv2 == CKR_OK) ? crv : crv2;
  1008. }
  1009. if (invalidExists) {
  1010. /* Copy out valid lengths. */
  1011. tmplIdx = 0;
  1012. for (resIdx = 0; resIdx < validCount; resIdx++) {
  1013. for (; tmplIdx < count; tmplIdx++) {
  1014. if (template[tmplIdx].type != validTemplate[resIdx].type) {
  1015. continue;
  1016. }
  1017. template[tmplIdx].ulValueLen = validTemplate[resIdx].ulValueLen;
  1018. tmplIdx++;
  1019. break;
  1020. }
  1021. }
  1022. free(validTemplate);
  1023. }
  1024. return crv;
  1025. }
  1026. static const char SET_ATTRIBUTE_CMD[] = "UPDATE %s SET %s WHERE id=$ID;";
  1027. CK_RV
  1028. sdb_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id,
  1029. const CK_ATTRIBUTE *template, CK_ULONG count)
  1030. {
  1031. SDBPrivate *sdb_p = sdb->private;
  1032. sqlite3 *sqlDB = NULL;
  1033. sqlite3_stmt *stmt = NULL;
  1034. char *setStr = NULL;
  1035. char *newStr = NULL;
  1036. int sqlerr = SQLITE_OK;
  1037. int retry = 0;
  1038. CK_RV error = CKR_OK;
  1039. unsigned int i;
  1040. if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
  1041. return CKR_TOKEN_WRITE_PROTECTED;
  1042. }
  1043. if (count == 0) {
  1044. return CKR_OK;
  1045. }
  1046. LOCK_SQLITE()
  1047. setStr = sqlite3_mprintf("");
  1048. for (i = 0; setStr && i < count; i++) {
  1049. if (i == 0) {
  1050. sqlite3_free(setStr);
  1051. setStr = sqlite3_mprintf("a%x=$VALUE%d",
  1052. template[i].type, i);
  1053. continue;
  1054. }
  1055. newStr = sqlite3_mprintf("%s,a%x=$VALUE%d", setStr,
  1056. template[i].type, i);
  1057. sqlite3_free(setStr);
  1058. setStr = newStr;
  1059. }
  1060. newStr = NULL;
  1061. if (setStr == NULL) {
  1062. return CKR_HOST_MEMORY;
  1063. }
  1064. newStr = sqlite3_mprintf(SET_ATTRIBUTE_CMD, sdb_p->table, setStr);
  1065. sqlite3_free(setStr);
  1066. if (newStr == NULL) {
  1067. UNLOCK_SQLITE()
  1068. return CKR_HOST_MEMORY;
  1069. }
  1070. error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
  1071. if (error != CKR_OK) {
  1072. goto loser;
  1073. }
  1074. sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL);
  1075. if (sqlerr != SQLITE_OK)
  1076. goto loser;
  1077. for (i = 0; i < count; i++) {
  1078. if (template[i].ulValueLen != 0) {
  1079. sqlerr = sqlite3_bind_blob(stmt, i + 1, template[i].pValue,
  1080. template[i].ulValueLen, SQLITE_STATIC);
  1081. } else {
  1082. sqlerr = sqlite3_bind_blob(stmt, i + 1, SQLITE_EXPLICIT_NULL,
  1083. SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC);
  1084. }
  1085. if (sqlerr != SQLITE_OK)
  1086. goto loser;
  1087. }
  1088. sqlerr = sqlite3_bind_int(stmt, i + 1, object_id);
  1089. if (sqlerr != SQLITE_OK)
  1090. goto loser;
  1091. do {
  1092. sqlerr = sqlite3_step(stmt);
  1093. if (sqlerr == SQLITE_BUSY) {
  1094. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1095. }
  1096. } while (!sdb_done(sqlerr, &retry));
  1097. loser:
  1098. if (newStr) {
  1099. sqlite3_free(newStr);
  1100. }
  1101. if (error == CKR_OK) {
  1102. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1103. }
  1104. if (stmt) {
  1105. sqlite3_reset(stmt);
  1106. sqlite3_finalize(stmt);
  1107. }
  1108. if (sqlDB) {
  1109. sdb_closeDBLocal(sdb_p, sqlDB);
  1110. }
  1111. UNLOCK_SQLITE()
  1112. return error;
  1113. }
  1114. /*
  1115. * check to see if a candidate object handle already exists.
  1116. */
  1117. static PRBool
  1118. sdb_objectExists(SDB *sdb, CK_OBJECT_HANDLE candidate)
  1119. {
  1120. CK_RV crv;
  1121. CK_ATTRIBUTE template = { CKA_LABEL, NULL, 0 };
  1122. crv = sdb_GetValidAttributeValueNoLock(sdb, candidate, &template, 1);
  1123. if (crv == CKR_OBJECT_HANDLE_INVALID) {
  1124. return PR_FALSE;
  1125. }
  1126. return PR_TRUE;
  1127. }
  1128. /*
  1129. * if we're here, we are in a transaction, so it's safe
  1130. * to examine the current state of the database
  1131. */
  1132. static CK_OBJECT_HANDLE
  1133. sdb_getObjectId(SDB *sdb)
  1134. {
  1135. CK_OBJECT_HANDLE candidate;
  1136. static CK_OBJECT_HANDLE next_obj = CK_INVALID_HANDLE;
  1137. int count;
  1138. /*
  1139. * get an initial object handle to use
  1140. */
  1141. if (next_obj == CK_INVALID_HANDLE) {
  1142. PRTime time;
  1143. time = PR_Now();
  1144. next_obj = (CK_OBJECT_HANDLE)(time & 0x3fffffffL);
  1145. }
  1146. candidate = next_obj++;
  1147. /* detect that we've looped through all the handles... */
  1148. for (count = 0; count < 0x40000000; count++, candidate = next_obj++) {
  1149. /* mask off excess bits */
  1150. candidate &= 0x3fffffff;
  1151. /* if we hit zero, go to the next entry */
  1152. if (candidate == CK_INVALID_HANDLE) {
  1153. continue;
  1154. }
  1155. /* make sure we aren't already using */
  1156. if (!sdb_objectExists(sdb, candidate)) {
  1157. /* this one is free */
  1158. return candidate;
  1159. }
  1160. }
  1161. /* no handle is free, fail */
  1162. return CK_INVALID_HANDLE;
  1163. }
  1164. CK_RV
  1165. sdb_GetNewObjectID(SDB *sdb, CK_OBJECT_HANDLE *object)
  1166. {
  1167. CK_OBJECT_HANDLE id;
  1168. id = sdb_getObjectId(sdb);
  1169. if (id == CK_INVALID_HANDLE) {
  1170. return CKR_DEVICE_MEMORY; /* basically we ran out of resources */
  1171. }
  1172. *object = id;
  1173. return CKR_OK;
  1174. }
  1175. static const char CREATE_CMD[] = "INSERT INTO %s (id%s) VALUES($ID%s);";
  1176. CK_RV
  1177. sdb_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *object_id,
  1178. const CK_ATTRIBUTE *template, CK_ULONG count)
  1179. {
  1180. SDBPrivate *sdb_p = sdb->private;
  1181. sqlite3 *sqlDB = NULL;
  1182. sqlite3_stmt *stmt = NULL;
  1183. char *columnStr = NULL;
  1184. char *valueStr = NULL;
  1185. char *newStr = NULL;
  1186. int sqlerr = SQLITE_OK;
  1187. CK_RV error = CKR_OK;
  1188. CK_OBJECT_HANDLE this_object = CK_INVALID_HANDLE;
  1189. int retry = 0;
  1190. unsigned int i;
  1191. if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
  1192. return CKR_TOKEN_WRITE_PROTECTED;
  1193. }
  1194. LOCK_SQLITE()
  1195. if ((*object_id != CK_INVALID_HANDLE) &&
  1196. !sdb_objectExists(sdb, *object_id)) {
  1197. this_object = *object_id;
  1198. } else {
  1199. this_object = sdb_getObjectId(sdb);
  1200. }
  1201. if (this_object == CK_INVALID_HANDLE) {
  1202. UNLOCK_SQLITE();
  1203. return CKR_HOST_MEMORY;
  1204. }
  1205. columnStr = sqlite3_mprintf("");
  1206. valueStr = sqlite3_mprintf("");
  1207. *object_id = this_object;
  1208. for (i = 0; columnStr && valueStr && i < count; i++) {
  1209. newStr = sqlite3_mprintf("%s,a%x", columnStr, template[i].type);
  1210. sqlite3_free(columnStr);
  1211. columnStr = newStr;
  1212. newStr = sqlite3_mprintf("%s,$VALUE%d", valueStr, i);
  1213. sqlite3_free(valueStr);
  1214. valueStr = newStr;
  1215. }
  1216. newStr = NULL;
  1217. if ((columnStr == NULL) || (valueStr == NULL)) {
  1218. if (columnStr) {
  1219. sqlite3_free(columnStr);
  1220. }
  1221. if (valueStr) {
  1222. sqlite3_free(valueStr);
  1223. }
  1224. UNLOCK_SQLITE()
  1225. return CKR_HOST_MEMORY;
  1226. }
  1227. newStr = sqlite3_mprintf(CREATE_CMD, sdb_p->table, columnStr, valueStr);
  1228. sqlite3_free(columnStr);
  1229. sqlite3_free(valueStr);
  1230. error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
  1231. if (error != CKR_OK) {
  1232. goto loser;
  1233. }
  1234. sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL);
  1235. if (sqlerr != SQLITE_OK)
  1236. goto loser;
  1237. sqlerr = sqlite3_bind_int(stmt, 1, *object_id);
  1238. if (sqlerr != SQLITE_OK)
  1239. goto loser;
  1240. for (i = 0; i < count; i++) {
  1241. if (template[i].ulValueLen) {
  1242. sqlerr = sqlite3_bind_blob(stmt, i + 2, template[i].pValue,
  1243. template[i].ulValueLen, SQLITE_STATIC);
  1244. } else {
  1245. sqlerr = sqlite3_bind_blob(stmt, i + 2, SQLITE_EXPLICIT_NULL,
  1246. SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC);
  1247. }
  1248. if (sqlerr != SQLITE_OK)
  1249. goto loser;
  1250. }
  1251. do {
  1252. sqlerr = sqlite3_step(stmt);
  1253. if (sqlerr == SQLITE_BUSY) {
  1254. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1255. }
  1256. } while (!sdb_done(sqlerr, &retry));
  1257. loser:
  1258. if (newStr) {
  1259. sqlite3_free(newStr);
  1260. }
  1261. if (error == CKR_OK) {
  1262. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1263. }
  1264. if (stmt) {
  1265. sqlite3_reset(stmt);
  1266. sqlite3_finalize(stmt);
  1267. }
  1268. if (sqlDB) {
  1269. sdb_closeDBLocal(sdb_p, sqlDB);
  1270. }
  1271. UNLOCK_SQLITE()
  1272. return error;
  1273. }
  1274. /*
  1275. * Generic destroy that can destroy metadata or objects
  1276. */
  1277. static const char DESTROY_CMD[] = "DELETE FROM %s WHERE (id=$ID);";
  1278. CK_RV
  1279. sdb_destroyAnyObject(SDB *sdb, const char *table,
  1280. CK_OBJECT_HANDLE object_id, const char *string_id)
  1281. {
  1282. SDBPrivate *sdb_p = sdb->private;
  1283. sqlite3 *sqlDB = NULL;
  1284. sqlite3_stmt *stmt = NULL;
  1285. char *newStr = NULL;
  1286. int sqlerr = SQLITE_OK;
  1287. CK_RV error = CKR_OK;
  1288. int retry = 0;
  1289. if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
  1290. return CKR_TOKEN_WRITE_PROTECTED;
  1291. }
  1292. LOCK_SQLITE()
  1293. error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
  1294. if (error != CKR_OK) {
  1295. goto loser;
  1296. }
  1297. newStr = sqlite3_mprintf(DESTROY_CMD, table);
  1298. if (newStr == NULL) {
  1299. error = CKR_HOST_MEMORY;
  1300. goto loser;
  1301. }
  1302. sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL);
  1303. sqlite3_free(newStr);
  1304. if (sqlerr != SQLITE_OK)
  1305. goto loser;
  1306. if (string_id == NULL) {
  1307. sqlerr = sqlite3_bind_int(stmt, 1, object_id);
  1308. } else {
  1309. sqlerr = sqlite3_bind_text(stmt, 1, string_id,
  1310. PORT_Strlen(string_id), SQLITE_STATIC);
  1311. }
  1312. if (sqlerr != SQLITE_OK)
  1313. goto loser;
  1314. do {
  1315. sqlerr = sqlite3_step(stmt);
  1316. if (sqlerr == SQLITE_BUSY) {
  1317. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1318. }
  1319. } while (!sdb_done(sqlerr, &retry));
  1320. loser:
  1321. if (error == CKR_OK) {
  1322. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1323. }
  1324. if (stmt) {
  1325. sqlite3_reset(stmt);
  1326. sqlite3_finalize(stmt);
  1327. }
  1328. if (sqlDB) {
  1329. sdb_closeDBLocal(sdb_p, sqlDB);
  1330. }
  1331. UNLOCK_SQLITE()
  1332. return error;
  1333. }
  1334. CK_RV
  1335. sdb_DestroyObject(SDB *sdb, CK_OBJECT_HANDLE object_id)
  1336. {
  1337. SDBPrivate *sdb_p = sdb->private;
  1338. return sdb_destroyAnyObject(sdb, sdb_p->table, object_id, NULL);
  1339. }
  1340. CK_RV
  1341. sdb_DestroyMetaData(SDB *sdb, const char *id)
  1342. {
  1343. return sdb_destroyAnyObject(sdb, "metaData", 0, id);
  1344. }
  1345. static const char BEGIN_CMD[] = "BEGIN IMMEDIATE TRANSACTION;";
  1346. /*
  1347. * start a transaction.
  1348. *
  1349. * We need to open a new database, then store that new database into
  1350. * the private data structure. We open the database first, then use locks
  1351. * to protect storing the data to prevent deadlocks.
  1352. */
  1353. CK_RV
  1354. sdb_Begin(SDB *sdb)
  1355. {
  1356. SDBPrivate *sdb_p = sdb->private;
  1357. sqlite3 *sqlDB = NULL;
  1358. sqlite3_stmt *stmt = NULL;
  1359. int sqlerr = SQLITE_OK;
  1360. CK_RV error = CKR_OK;
  1361. int retry = 0;
  1362. if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
  1363. return CKR_TOKEN_WRITE_PROTECTED;
  1364. }
  1365. LOCK_SQLITE()
  1366. /* get a new version that we will use for the entire transaction */
  1367. sqlerr = sdb_openDB(sdb_p->sqlDBName, &sqlDB, SDB_RDWR);
  1368. if (sqlerr != SQLITE_OK) {
  1369. goto loser;
  1370. }
  1371. sqlerr = sqlite3_prepare_v2(sqlDB, BEGIN_CMD, -1, &stmt, NULL);
  1372. do {
  1373. sqlerr = sqlite3_step(stmt);
  1374. if (sqlerr == SQLITE_BUSY) {
  1375. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1376. }
  1377. } while (!sdb_done(sqlerr, &retry));
  1378. if (stmt) {
  1379. sqlite3_reset(stmt);
  1380. sqlite3_finalize(stmt);
  1381. }
  1382. loser:
  1383. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1384. /* we are starting a new transaction,
  1385. * and if we succeeded, then save this database for the rest of
  1386. * our transaction */
  1387. if (error == CKR_OK) {
  1388. /* we hold a 'BEGIN TRANSACTION' and a sdb_p->lock. At this point
  1389. * sdb_p->sqlXactDB MUST be null */
  1390. PR_EnterMonitor(sdb_p->dbMon);
  1391. PORT_Assert(sdb_p->sqlXactDB == NULL);
  1392. sdb_p->sqlXactDB = sqlDB;
  1393. sdb_p->sqlXactThread = PR_GetCurrentThread();
  1394. PR_ExitMonitor(sdb_p->dbMon);
  1395. } else {
  1396. /* we failed to start our transaction,
  1397. * free any databases we opened. */
  1398. if (sqlDB) {
  1399. sqlite3_close(sqlDB);
  1400. }
  1401. }
  1402. UNLOCK_SQLITE()
  1403. return error;
  1404. }
  1405. /*
  1406. * Complete a transaction. Basically undo everything we did in begin.
  1407. * There are 2 flavors Abort and Commit. Basically the only differerence between
  1408. * these 2 are what the database will show. (no change in to former, change in
  1409. * the latter).
  1410. */
  1411. static CK_RV
  1412. sdb_complete(SDB *sdb, const char *cmd)
  1413. {
  1414. SDBPrivate *sdb_p = sdb->private;
  1415. sqlite3 *sqlDB = NULL;
  1416. sqlite3_stmt *stmt = NULL;
  1417. int sqlerr = SQLITE_OK;
  1418. CK_RV error = CKR_OK;
  1419. int retry = 0;
  1420. if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
  1421. return CKR_TOKEN_WRITE_PROTECTED;
  1422. }
  1423. /* We must have a transation database, or we shouldn't have arrived here */
  1424. PR_EnterMonitor(sdb_p->dbMon);
  1425. PORT_Assert(sdb_p->sqlXactDB);
  1426. if (sdb_p->sqlXactDB == NULL) {
  1427. PR_ExitMonitor(sdb_p->dbMon);
  1428. return CKR_GENERAL_ERROR; /* shouldn't happen */
  1429. }
  1430. PORT_Assert(sdb_p->sqlXactThread == PR_GetCurrentThread());
  1431. if (sdb_p->sqlXactThread != PR_GetCurrentThread()) {
  1432. PR_ExitMonitor(sdb_p->dbMon);
  1433. return CKR_GENERAL_ERROR; /* shouldn't happen */
  1434. }
  1435. sqlDB = sdb_p->sqlXactDB;
  1436. sdb_p->sqlXactDB = NULL; /* no one else can get to this DB,
  1437. * safe to unlock */
  1438. sdb_p->sqlXactThread = NULL;
  1439. PR_ExitMonitor(sdb_p->dbMon);
  1440. sqlerr = sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL);
  1441. do {
  1442. sqlerr = sqlite3_step(stmt);
  1443. if (sqlerr == SQLITE_BUSY) {
  1444. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1445. }
  1446. } while (!sdb_done(sqlerr, &retry));
  1447. /* Pending BEGIN TRANSACTIONS Can move forward at this point. */
  1448. if (stmt) {
  1449. sqlite3_reset(stmt);
  1450. sqlite3_finalize(stmt);
  1451. }
  1452. /* we we have a cached DB image, update it as well */
  1453. if (sdb_p->cacheTable) {
  1454. PR_EnterMonitor(sdb_p->dbMon);
  1455. sdb_updateCache(sdb_p);
  1456. PR_ExitMonitor(sdb_p->dbMon);
  1457. }
  1458. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1459. /* We just finished a transaction.
  1460. * Free the database, and remove it from the list */
  1461. sqlite3_close(sqlDB);
  1462. return error;
  1463. }
  1464. static const char COMMIT_CMD[] = "COMMIT TRANSACTION;";
  1465. CK_RV
  1466. sdb_Commit(SDB *sdb)
  1467. {
  1468. CK_RV crv;
  1469. LOCK_SQLITE()
  1470. crv = sdb_complete(sdb, COMMIT_CMD);
  1471. UNLOCK_SQLITE()
  1472. return crv;
  1473. }
  1474. static const char ROLLBACK_CMD[] = "ROLLBACK TRANSACTION;";
  1475. CK_RV
  1476. sdb_Abort(SDB *sdb)
  1477. {
  1478. CK_RV crv;
  1479. LOCK_SQLITE()
  1480. crv = sdb_complete(sdb, ROLLBACK_CMD);
  1481. UNLOCK_SQLITE()
  1482. return crv;
  1483. }
  1484. static int tableExists(sqlite3 *sqlDB, const char *tableName);
  1485. static const char GET_PW_CMD[] = "SELECT ALL * FROM metaData WHERE id=$ID;";
  1486. CK_RV
  1487. sdb_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2)
  1488. {
  1489. SDBPrivate *sdb_p = sdb->private;
  1490. sqlite3 *sqlDB = sdb_p->sqlXactDB;
  1491. sqlite3_stmt *stmt = NULL;
  1492. int sqlerr = SQLITE_OK;
  1493. CK_RV error = CKR_OK;
  1494. int found = 0;
  1495. int retry = 0;
  1496. LOCK_SQLITE()
  1497. error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
  1498. if (error != CKR_OK) {
  1499. goto loser;
  1500. }
  1501. /* handle 'test' versions of the sqlite db */
  1502. sqlerr = sqlite3_prepare_v2(sqlDB, GET_PW_CMD, -1, &stmt, NULL);
  1503. /* Sigh, if we created a new table since we opened the database,
  1504. * the database handle will not see the new table, we need to close this
  1505. * database and reopen it. This is safe because we are holding the lock
  1506. * still. */
  1507. if (sqlerr == SQLITE_SCHEMA) {
  1508. sqlerr = sdb_reopenDBLocal(sdb_p, &sqlDB);
  1509. if (sqlerr != SQLITE_OK) {
  1510. goto loser;
  1511. }
  1512. sqlerr = sqlite3_prepare_v2(sqlDB, GET_PW_CMD, -1, &stmt, NULL);
  1513. }
  1514. if (sqlerr != SQLITE_OK)
  1515. goto loser;
  1516. sqlerr = sqlite3_bind_text(stmt, 1, id, PORT_Strlen(id), SQLITE_STATIC);
  1517. do {
  1518. sqlerr = sqlite3_step(stmt);
  1519. if (sqlerr == SQLITE_BUSY) {
  1520. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1521. }
  1522. if (sqlerr == SQLITE_ROW) {
  1523. const char *blobData;
  1524. unsigned int len = item1->len;
  1525. item1->len = sqlite3_column_bytes(stmt, 1);
  1526. if (item1->len > len) {
  1527. error = CKR_BUFFER_TOO_SMALL;
  1528. continue;
  1529. }
  1530. blobData = sqlite3_column_blob(stmt, 1);
  1531. PORT_Memcpy(item1->data, blobData, item1->len);
  1532. if (item2) {
  1533. len = item2->len;
  1534. item2->len = sqlite3_column_bytes(stmt, 2);
  1535. if (item2->len > len) {
  1536. error = CKR_BUFFER_TOO_SMALL;
  1537. continue;
  1538. }
  1539. blobData = sqlite3_column_blob(stmt, 2);
  1540. PORT_Memcpy(item2->data, blobData, item2->len);
  1541. }
  1542. found = 1;
  1543. }
  1544. } while (!sdb_done(sqlerr, &retry));
  1545. loser:
  1546. /* fix up the error if necessary */
  1547. if (error == CKR_OK) {
  1548. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1549. if (!found && error == CKR_OK) {
  1550. error = CKR_OBJECT_HANDLE_INVALID;
  1551. }
  1552. }
  1553. if (stmt) {
  1554. sqlite3_reset(stmt);
  1555. sqlite3_finalize(stmt);
  1556. }
  1557. if (sqlDB) {
  1558. sdb_closeDBLocal(sdb_p, sqlDB);
  1559. }
  1560. UNLOCK_SQLITE()
  1561. return error;
  1562. }
  1563. static const char PW_CREATE_TABLE_CMD[] =
  1564. "CREATE TABLE metaData (id PRIMARY KEY UNIQUE ON CONFLICT REPLACE, item1, item2);";
  1565. static const char PW_CREATE_CMD[] =
  1566. "INSERT INTO metaData (id,item1,item2) VALUES($ID,$ITEM1,$ITEM2);";
  1567. static const char MD_CREATE_CMD[] =
  1568. "INSERT INTO metaData (id,item1) VALUES($ID,$ITEM1);";
  1569. CK_RV
  1570. sdb_PutMetaData(SDB *sdb, const char *id, const SECItem *item1,
  1571. const SECItem *item2)
  1572. {
  1573. SDBPrivate *sdb_p = sdb->private;
  1574. sqlite3 *sqlDB = sdb_p->sqlXactDB;
  1575. sqlite3_stmt *stmt = NULL;
  1576. int sqlerr = SQLITE_OK;
  1577. CK_RV error = CKR_OK;
  1578. int retry = 0;
  1579. const char *cmd = PW_CREATE_CMD;
  1580. if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
  1581. return CKR_TOKEN_WRITE_PROTECTED;
  1582. }
  1583. LOCK_SQLITE()
  1584. error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
  1585. if (error != CKR_OK) {
  1586. goto loser;
  1587. }
  1588. if (!tableExists(sqlDB, "metaData")) {
  1589. sqlerr = sqlite3_exec(sqlDB, PW_CREATE_TABLE_CMD, NULL, 0, NULL);
  1590. if (sqlerr != SQLITE_OK)
  1591. goto loser;
  1592. }
  1593. if (item2 == NULL) {
  1594. cmd = MD_CREATE_CMD;
  1595. }
  1596. sqlerr = sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL);
  1597. if (sqlerr != SQLITE_OK)
  1598. goto loser;
  1599. sqlerr = sqlite3_bind_text(stmt, 1, id, PORT_Strlen(id), SQLITE_STATIC);
  1600. if (sqlerr != SQLITE_OK)
  1601. goto loser;
  1602. sqlerr = sqlite3_bind_blob(stmt, 2, item1->data, item1->len, SQLITE_STATIC);
  1603. if (sqlerr != SQLITE_OK)
  1604. goto loser;
  1605. if (item2) {
  1606. sqlerr = sqlite3_bind_blob(stmt, 3, item2->data,
  1607. item2->len, SQLITE_STATIC);
  1608. if (sqlerr != SQLITE_OK)
  1609. goto loser;
  1610. }
  1611. do {
  1612. sqlerr = sqlite3_step(stmt);
  1613. if (sqlerr == SQLITE_BUSY) {
  1614. PR_Sleep(SDB_BUSY_RETRY_TIME);
  1615. }
  1616. } while (!sdb_done(sqlerr, &retry));
  1617. loser:
  1618. /* fix up the error if necessary */
  1619. if (error == CKR_OK) {
  1620. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1621. }
  1622. if (stmt) {
  1623. sqlite3_reset(stmt);
  1624. sqlite3_finalize(stmt);
  1625. }
  1626. if (sqlDB) {
  1627. sdb_closeDBLocal(sdb_p, sqlDB);
  1628. }
  1629. UNLOCK_SQLITE()
  1630. return error;
  1631. }
  1632. static const char RESET_CMD[] = "DELETE FROM %s;";
  1633. CK_RV
  1634. sdb_Reset(SDB *sdb)
  1635. {
  1636. SDBPrivate *sdb_p = sdb->private;
  1637. sqlite3 *sqlDB = NULL;
  1638. char *newStr;
  1639. int sqlerr = SQLITE_OK;
  1640. CK_RV error = CKR_OK;
  1641. /* only Key databases can be reset */
  1642. if (sdb_p->type != SDB_KEY) {
  1643. return CKR_OBJECT_HANDLE_INVALID;
  1644. }
  1645. LOCK_SQLITE()
  1646. error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
  1647. if (error != CKR_OK) {
  1648. goto loser;
  1649. }
  1650. if (tableExists(sqlDB, sdb_p->table)) {
  1651. /* delete the contents of the key table */
  1652. newStr = sqlite3_mprintf(RESET_CMD, sdb_p->table);
  1653. if (newStr == NULL) {
  1654. error = CKR_HOST_MEMORY;
  1655. goto loser;
  1656. }
  1657. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  1658. sqlite3_free(newStr);
  1659. if (sqlerr != SQLITE_OK)
  1660. goto loser;
  1661. }
  1662. /* delete the password entry table */
  1663. sqlerr = sqlite3_exec(sqlDB, "DROP TABLE IF EXISTS metaData;",
  1664. NULL, 0, NULL);
  1665. loser:
  1666. /* fix up the error if necessary */
  1667. if (error == CKR_OK) {
  1668. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  1669. }
  1670. if (sqlDB) {
  1671. sdb_closeDBLocal(sdb_p, sqlDB);
  1672. }
  1673. UNLOCK_SQLITE()
  1674. return error;
  1675. }
  1676. CK_RV
  1677. sdb_Close(SDB *sdb)
  1678. {
  1679. SDBPrivate *sdb_p = sdb->private;
  1680. int sqlerr = SQLITE_OK;
  1681. sdbDataType type = sdb_p->type;
  1682. sqlerr = sqlite3_close(sdb_p->sqlReadDB);
  1683. PORT_Free(sdb_p->sqlDBName);
  1684. if (sdb_p->cacheTable) {
  1685. sqlite3_free(sdb_p->cacheTable);
  1686. }
  1687. if (sdb_p->dbMon) {
  1688. PR_DestroyMonitor(sdb_p->dbMon);
  1689. }
  1690. free(sdb_p->schemaAttrs);
  1691. free(sdb_p);
  1692. free(sdb);
  1693. return sdb_mapSQLError(type, sqlerr);
  1694. }
  1695. /*
  1696. * functions to support open
  1697. */
  1698. static const char CHECK_TABLE_CMD[] = "SELECT ALL * FROM %s LIMIT 0;";
  1699. /* return 1 if sqlDB contains table 'tableName */
  1700. static int
  1701. tableExists(sqlite3 *sqlDB, const char *tableName)
  1702. {
  1703. char *cmd = sqlite3_mprintf(CHECK_TABLE_CMD, tableName);
  1704. int sqlerr = SQLITE_OK;
  1705. if (cmd == NULL) {
  1706. return 0;
  1707. }
  1708. sqlerr = sqlite3_exec(sqlDB, cmd, NULL, 0, 0);
  1709. sqlite3_free(cmd);
  1710. return (sqlerr == SQLITE_OK) ? 1 : 0;
  1711. }
  1712. void
  1713. sdb_SetForkState(PRBool forked)
  1714. {
  1715. /* XXXright now this is a no-op. The global fork state in the softokn3
  1716. * shared library is already taken care of at the PKCS#11 level.
  1717. * If and when we add fork state to the sqlite shared library and extern
  1718. * interface, we will need to set it and reset it from here */
  1719. }
  1720. static int
  1721. sdb_attributeComparator(const void *a, const void *b)
  1722. {
  1723. if (*(CK_ATTRIBUTE_TYPE *)a < *(CK_ATTRIBUTE_TYPE *)b) {
  1724. return -1;
  1725. }
  1726. if (*(CK_ATTRIBUTE_TYPE *)a > *(CK_ATTRIBUTE_TYPE *)b) {
  1727. return 1;
  1728. }
  1729. return 0;
  1730. }
  1731. /*
  1732. * initialize a single database
  1733. */
  1734. static const char INIT_CMD[] =
  1735. "CREATE TABLE %s (id PRIMARY KEY UNIQUE ON CONFLICT ABORT%s)";
  1736. CK_RV
  1737. sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate,
  1738. int *newInit, int inFlags, PRUint32 accessOps, SDB **pSdb)
  1739. {
  1740. int i;
  1741. char *initStr = NULL;
  1742. char *newStr;
  1743. char *queryStr = NULL;
  1744. int inTransaction = 0;
  1745. SDB *sdb = NULL;
  1746. SDBPrivate *sdb_p = NULL;
  1747. sqlite3 *sqlDB = NULL;
  1748. int sqlerr = SQLITE_OK;
  1749. CK_RV error = CKR_OK;
  1750. char *cacheTable = NULL;
  1751. PRIntervalTime now = 0;
  1752. char *env;
  1753. PRBool enableCache = PR_FALSE;
  1754. PRBool checkFSType = PR_FALSE;
  1755. PRBool measureSpeed = PR_FALSE;
  1756. PRBool create;
  1757. int flags = inFlags & 0x7;
  1758. *pSdb = NULL;
  1759. *inUpdate = 0;
  1760. /* sqlite3 doesn't have a flag to specify that we want to
  1761. * open the database read only. If the db doesn't exist,
  1762. * sqlite3 will always create it.
  1763. */
  1764. LOCK_SQLITE();
  1765. create = (_NSSUTIL_Access(dbname, PR_ACCESS_EXISTS) != PR_SUCCESS);
  1766. if ((flags == SDB_RDONLY) && create) {
  1767. error = sdb_mapSQLError(type, SQLITE_CANTOPEN);
  1768. goto loser;
  1769. }
  1770. sqlerr = sdb_openDB(dbname, &sqlDB, flags);
  1771. if (sqlerr != SQLITE_OK) {
  1772. error = sdb_mapSQLError(type, sqlerr);
  1773. goto loser;
  1774. }
  1775. /*
  1776. * SQL created the file, but it doesn't set appropriate modes for
  1777. * a database.
  1778. *
  1779. * NO NSPR call for chmod? :(
  1780. */
  1781. if (create && sdb_chmod(dbname, 0600) != 0) {
  1782. error = sdb_mapSQLError(type, SQLITE_CANTOPEN);
  1783. goto loser;
  1784. }
  1785. if (flags != SDB_RDONLY) {
  1786. sqlerr = sqlite3_exec(sqlDB, BEGIN_CMD, NULL, 0, NULL);
  1787. if (sqlerr != SQLITE_OK) {
  1788. error = sdb_mapSQLError(type, sqlerr);
  1789. goto loser;
  1790. }
  1791. inTransaction = 1;
  1792. }
  1793. if (!tableExists(sqlDB, table)) {
  1794. *newInit = 1;
  1795. if (flags != SDB_CREATE) {
  1796. error = sdb_mapSQLError(type, SQLITE_CANTOPEN);
  1797. goto loser;
  1798. }
  1799. initStr = sqlite3_mprintf("");
  1800. for (i = 0; initStr && i < known_attributes_size; i++) {
  1801. newStr = sqlite3_mprintf("%s, a%x", initStr, known_attributes[i]);
  1802. sqlite3_free(initStr);
  1803. initStr = newStr;
  1804. }
  1805. if (initStr == NULL) {
  1806. error = CKR_HOST_MEMORY;
  1807. goto loser;
  1808. }
  1809. newStr = sqlite3_mprintf(INIT_CMD, table, initStr);
  1810. sqlite3_free(initStr);
  1811. if (newStr == NULL) {
  1812. error = CKR_HOST_MEMORY;
  1813. goto loser;
  1814. }
  1815. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  1816. sqlite3_free(newStr);
  1817. if (sqlerr != SQLITE_OK) {
  1818. error = sdb_mapSQLError(type, sqlerr);
  1819. goto loser;
  1820. }
  1821. newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, table);
  1822. if (newStr == NULL) {
  1823. error = CKR_HOST_MEMORY;
  1824. goto loser;
  1825. }
  1826. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  1827. sqlite3_free(newStr);
  1828. if (sqlerr != SQLITE_OK) {
  1829. error = sdb_mapSQLError(type, sqlerr);
  1830. goto loser;
  1831. }
  1832. newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, table);
  1833. if (newStr == NULL) {
  1834. error = CKR_HOST_MEMORY;
  1835. goto loser;
  1836. }
  1837. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  1838. sqlite3_free(newStr);
  1839. if (sqlerr != SQLITE_OK) {
  1840. error = sdb_mapSQLError(type, sqlerr);
  1841. goto loser;
  1842. }
  1843. newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, table);
  1844. if (newStr == NULL) {
  1845. error = CKR_HOST_MEMORY;
  1846. goto loser;
  1847. }
  1848. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  1849. sqlite3_free(newStr);
  1850. if (sqlerr != SQLITE_OK) {
  1851. error = sdb_mapSQLError(type, sqlerr);
  1852. goto loser;
  1853. }
  1854. newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, table);
  1855. if (newStr == NULL) {
  1856. error = CKR_HOST_MEMORY;
  1857. goto loser;
  1858. }
  1859. sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
  1860. sqlite3_free(newStr);
  1861. if (sqlerr != SQLITE_OK) {
  1862. error = sdb_mapSQLError(type, sqlerr);
  1863. goto loser;
  1864. }
  1865. }
  1866. /*
  1867. * detect the case where we have created the database, but have
  1868. * not yet updated it.
  1869. *
  1870. * We only check the Key database because only the key database has
  1871. * a metaData table. The metaData table is created when a password
  1872. * is set, or in the case of update, when a password is supplied.
  1873. * If no key database exists, then the update would have happened immediately
  1874. * on noticing that the cert database didn't exist (see newInit set above).
  1875. */
  1876. if (type == SDB_KEY && !tableExists(sqlDB, "metaData")) {
  1877. *newInit = 1;
  1878. }
  1879. /* access to network filesystems are significantly slower than local ones
  1880. * for database operations. In those cases we need to create a cached copy
  1881. * of the database in a temporary location on the local disk. SQLITE
  1882. * already provides a way to create a temporary table and initialize it,
  1883. * so we use it for the cache (see sdb_buildCache for how it's done).*/
  1884. /*
  1885. * we decide whether or not to use the cache based on the following input.
  1886. *
  1887. * NSS_SDB_USE_CACHE environment variable is set to anything other than
  1888. * "yes" or "no" (for instance, "auto"): NSS will measure the performance
  1889. * of access to the temp database versus the access to the user's
  1890. * passed-in database location. If the temp database location is
  1891. * "significantly" faster we will use the cache.
  1892. *
  1893. * NSS_SDB_USE_CACHE environment variable is nonexistent or set to "no":
  1894. * cache will not be used.
  1895. *
  1896. * NSS_SDB_USE_CACHE environment variable is set to "yes": cache will
  1897. * always be used.
  1898. *
  1899. * It is expected that most applications will not need this feature, and
  1900. * thus it is disabled by default.
  1901. */
  1902. env = PR_GetEnvSecure("NSS_SDB_USE_CACHE");
  1903. /* Variables enableCache, checkFSType, measureSpeed are PR_FALSE by default,
  1904. * which is the expected behavior for NSS_SDB_USE_CACHE="no".
  1905. * We don't need to check for "no" here. */
  1906. if (!env) {
  1907. /* By default, with no variable set, we avoid expensive measuring for
  1908. * most FS types. We start with inexpensive FS type checking, and
  1909. * might perform measuring for some types. */
  1910. checkFSType = PR_TRUE;
  1911. } else if (PORT_Strcasecmp(env, "yes") == 0) {
  1912. enableCache = PR_TRUE;
  1913. } else if (PORT_Strcasecmp(env, "no") != 0) { /* not "no" => "auto" */
  1914. measureSpeed = PR_TRUE;
  1915. }
  1916. if (checkFSType) {
  1917. #if defined(LINUX) && !defined(ANDROID)
  1918. struct statfs statfs_s;
  1919. if (statfs(dbname, &statfs_s) == 0) {
  1920. switch (statfs_s.f_type) {
  1921. case SMB_SUPER_MAGIC:
  1922. case 0xff534d42: /* CIFS_MAGIC_NUMBER */
  1923. case NFS_SUPER_MAGIC:
  1924. /* We assume these are slow. */
  1925. enableCache = PR_TRUE;
  1926. break;
  1927. case CODA_SUPER_MAGIC:
  1928. case 0x65735546: /* FUSE_SUPER_MAGIC */
  1929. case NCP_SUPER_MAGIC:
  1930. /* It's uncertain if this FS is fast or slow.
  1931. * It seems reasonable to perform slow measuring for users
  1932. * with questionable FS speed. */
  1933. measureSpeed = PR_TRUE;
  1934. break;
  1935. case AFS_SUPER_MAGIC: /* Already implements caching. */
  1936. default:
  1937. break;
  1938. }
  1939. }
  1940. #endif
  1941. }
  1942. if (measureSpeed) {
  1943. char *tempDir = NULL;
  1944. PRUint32 tempOps = 0;
  1945. /*
  1946. * Use PR_Access to determine how expensive it
  1947. * is to check for the existance of a local file compared to the same
  1948. * check in the temp directory. If the temp directory is faster, cache
  1949. * the database there. */
  1950. tempDir = sdb_getTempDir(sqlDB);
  1951. if (tempDir) {
  1952. tempOps = sdb_measureAccess(tempDir);
  1953. PORT_Free(tempDir);
  1954. /* There is a cost to continually copying the database.
  1955. * Account for that cost with the arbitrary factor of 10 */
  1956. enableCache = (PRBool)(tempOps > accessOps * 10);
  1957. }
  1958. }
  1959. if (enableCache) {
  1960. /* try to set the temp store to memory.*/
  1961. sqlite3_exec(sqlDB, "PRAGMA temp_store=MEMORY", NULL, 0, NULL);
  1962. /* Failure to set the temp store to memory is not fatal,
  1963. * ignore the error */
  1964. cacheTable = sqlite3_mprintf("%sCache", table);
  1965. if (cacheTable == NULL) {
  1966. error = CKR_HOST_MEMORY;
  1967. goto loser;
  1968. }
  1969. /* build the cache table */
  1970. error = sdb_buildCache(sqlDB, type, cacheTable, table);
  1971. if (error != CKR_OK) {
  1972. goto loser;
  1973. }
  1974. /* initialize the last cache build time */
  1975. now = PR_IntervalNow();
  1976. }
  1977. sdb = (SDB *)malloc(sizeof(SDB));
  1978. if (!sdb) {
  1979. error = CKR_HOST_MEMORY;
  1980. goto loser;
  1981. }
  1982. sdb_p = (SDBPrivate *)malloc(sizeof(SDBPrivate));
  1983. if (!sdb_p) {
  1984. error = CKR_HOST_MEMORY;
  1985. goto loser;
  1986. }
  1987. /* Cache the attributes that are held in the table, so we can later check
  1988. * that queried attributes actually exist. We don't assume the schema
  1989. * to be exactly |known_attributes|, as it may change over time. */
  1990. sdb_p->schemaAttrs = NULL;
  1991. if (!PORT_Strcmp("nssPublic", table) ||
  1992. !PORT_Strcmp("nssPrivate", table)) {
  1993. sqlite3_stmt *stmt = NULL;
  1994. int retry = 0;
  1995. unsigned int backedAttrs = 0;
  1996. /* Can't bind parameters to a PRAGMA. */
  1997. queryStr = sqlite3_mprintf("PRAGMA table_info(%s);", table);
  1998. if (queryStr == NULL) {
  1999. error = CKR_HOST_MEMORY;
  2000. goto loser;
  2001. }
  2002. sqlerr = sqlite3_prepare_v2(sqlDB, queryStr, -1, &stmt, NULL);
  2003. sqlite3_free(queryStr);
  2004. queryStr = NULL;
  2005. if (sqlerr != SQLITE_OK) {
  2006. goto loser;
  2007. }
  2008. unsigned int schemaAttrsCapacity = known_attributes_size;
  2009. sdb_p->schemaAttrs = malloc(schemaAttrsCapacity * sizeof(CK_ATTRIBUTE));
  2010. if (!sdb_p->schemaAttrs) {
  2011. error = CKR_HOST_MEMORY;
  2012. goto loser;
  2013. }
  2014. do {
  2015. sqlerr = sqlite3_step(stmt);
  2016. if (sqlerr == SQLITE_BUSY) {
  2017. PR_Sleep(SDB_BUSY_RETRY_TIME);
  2018. }
  2019. if (sqlerr == SQLITE_ROW) {
  2020. if (backedAttrs == schemaAttrsCapacity) {
  2021. schemaAttrsCapacity += known_attributes_size;
  2022. sdb_p->schemaAttrs = realloc(sdb_p->schemaAttrs,
  2023. schemaAttrsCapacity * sizeof(CK_ATTRIBUTE));
  2024. if (!sdb_p->schemaAttrs) {
  2025. error = CKR_HOST_MEMORY;
  2026. goto loser;
  2027. }
  2028. }
  2029. /* Record the ULONG attribute value. */
  2030. char *val = (char *)sqlite3_column_text(stmt, 1);
  2031. if (val && val[0] == 'a') {
  2032. CK_ATTRIBUTE_TYPE attr = strtoul(&val[1], NULL, 16);
  2033. sdb_p->schemaAttrs[backedAttrs++] = attr;
  2034. }
  2035. }
  2036. } while (!sdb_done(sqlerr, &retry));
  2037. if (sqlerr != SQLITE_DONE) {
  2038. goto loser;
  2039. }
  2040. sqlerr = sqlite3_reset(stmt);
  2041. if (sqlerr != SQLITE_OK) {
  2042. goto loser;
  2043. }
  2044. sqlerr = sqlite3_finalize(stmt);
  2045. if (sqlerr != SQLITE_OK) {
  2046. goto loser;
  2047. }
  2048. sdb_p->numSchemaAttrs = backedAttrs;
  2049. /* Sort these once so we can shortcut invalid attribute searches. */
  2050. qsort(sdb_p->schemaAttrs, sdb_p->numSchemaAttrs,
  2051. sizeof(CK_ATTRIBUTE_TYPE), sdb_attributeComparator);
  2052. }
  2053. /* invariant fields */
  2054. sdb_p->sqlDBName = PORT_Strdup(dbname);
  2055. sdb_p->type = type;
  2056. sdb_p->table = table;
  2057. sdb_p->cacheTable = cacheTable;
  2058. sdb_p->lastUpdateTime = now;
  2059. /* set the cache delay time. This is how long we will wait before we
  2060. * decide the existing cache is stale. Currently set to 10 sec */
  2061. sdb_p->updateInterval = PR_SecondsToInterval(10);
  2062. sdb_p->dbMon = PR_NewMonitor();
  2063. /* these fields are protected by the lock */
  2064. sdb_p->sqlXactDB = NULL;
  2065. sdb_p->sqlXactThread = NULL;
  2066. sdb->private = sdb_p;
  2067. sdb->version = 1;
  2068. sdb->sdb_flags = inFlags | SDB_HAS_META;
  2069. sdb->app_private = NULL;
  2070. sdb->sdb_FindObjectsInit = sdb_FindObjectsInit;
  2071. sdb->sdb_FindObjects = sdb_FindObjects;
  2072. sdb->sdb_FindObjectsFinal = sdb_FindObjectsFinal;
  2073. sdb->sdb_GetAttributeValue = sdb_GetAttributeValue;
  2074. sdb->sdb_SetAttributeValue = sdb_SetAttributeValue;
  2075. sdb->sdb_CreateObject = sdb_CreateObject;
  2076. sdb->sdb_DestroyObject = sdb_DestroyObject;
  2077. sdb->sdb_GetMetaData = sdb_GetMetaData;
  2078. sdb->sdb_PutMetaData = sdb_PutMetaData;
  2079. sdb->sdb_DestroyMetaData = sdb_DestroyMetaData;
  2080. sdb->sdb_Begin = sdb_Begin;
  2081. sdb->sdb_Commit = sdb_Commit;
  2082. sdb->sdb_Abort = sdb_Abort;
  2083. sdb->sdb_Reset = sdb_Reset;
  2084. sdb->sdb_Close = sdb_Close;
  2085. sdb->sdb_SetForkState = sdb_SetForkState;
  2086. sdb->sdb_GetNewObjectID = sdb_GetNewObjectID;
  2087. if (inTransaction) {
  2088. sqlerr = sqlite3_exec(sqlDB, COMMIT_CMD, NULL, 0, NULL);
  2089. if (sqlerr != SQLITE_OK) {
  2090. error = sdb_mapSQLError(sdb_p->type, sqlerr);
  2091. goto loser;
  2092. }
  2093. inTransaction = 0;
  2094. }
  2095. sdb_p->sqlReadDB = sqlDB;
  2096. *pSdb = sdb;
  2097. UNLOCK_SQLITE();
  2098. return CKR_OK;
  2099. loser:
  2100. /* lots of stuff to do */
  2101. if (inTransaction) {
  2102. sqlite3_exec(sqlDB, ROLLBACK_CMD, NULL, 0, NULL);
  2103. }
  2104. if (sdb) {
  2105. free(sdb);
  2106. }
  2107. if (sdb_p) {
  2108. if (sdb_p->schemaAttrs) {
  2109. free(sdb_p->schemaAttrs);
  2110. }
  2111. free(sdb_p);
  2112. }
  2113. if (sqlDB) {
  2114. sqlite3_close(sqlDB);
  2115. }
  2116. UNLOCK_SQLITE();
  2117. return error;
  2118. }
  2119. /* sdbopen */
  2120. CK_RV
  2121. s_open(const char *directory, const char *certPrefix, const char *keyPrefix,
  2122. int cert_version, int key_version, int flags,
  2123. SDB **certdb, SDB **keydb, int *newInit)
  2124. {
  2125. char *cert = sdb_BuildFileName(directory, certPrefix,
  2126. "cert", cert_version);
  2127. char *key = sdb_BuildFileName(directory, keyPrefix,
  2128. "key", key_version);
  2129. CK_RV error = CKR_OK;
  2130. int inUpdate;
  2131. PRUint32 accessOps;
  2132. if (certdb)
  2133. *certdb = NULL;
  2134. if (keydb)
  2135. *keydb = NULL;
  2136. *newInit = 0;
  2137. #ifdef SQLITE_UNSAFE_THREADS
  2138. if (sqlite_lock == NULL) {
  2139. sqlite_lock = PR_NewLock();
  2140. if (sqlite_lock == NULL) {
  2141. error = CKR_HOST_MEMORY;
  2142. goto loser;
  2143. }
  2144. }
  2145. #endif
  2146. /* how long does it take to test for a non-existant file in our working
  2147. * directory? Allows us to test if we may be on a network file system */
  2148. accessOps = 1;
  2149. {
  2150. char *env;
  2151. env = PR_GetEnvSecure("NSS_SDB_USE_CACHE");
  2152. /* If the environment variable is undefined or set to yes or no,
  2153. * sdb_init() will ignore the value of accessOps, and we can skip the
  2154. * measuring.*/
  2155. if (env && PORT_Strcasecmp(env, "no") != 0 &&
  2156. PORT_Strcasecmp(env, "yes") != 0) {
  2157. accessOps = sdb_measureAccess(directory);
  2158. }
  2159. }
  2160. /*
  2161. * open the cert data base
  2162. */
  2163. if (certdb) {
  2164. /* initialize Certificate database */
  2165. error = sdb_init(cert, "nssPublic", SDB_CERT, &inUpdate,
  2166. newInit, flags, accessOps, certdb);
  2167. if (error != CKR_OK) {
  2168. goto loser;
  2169. }
  2170. }
  2171. /*
  2172. * open the key data base:
  2173. * NOTE:if we want to implement a single database, we open
  2174. * the same database file as the certificate here.
  2175. *
  2176. * cert an key db's have different tables, so they will not
  2177. * conflict.
  2178. */
  2179. if (keydb) {
  2180. /* initialize the Key database */
  2181. error = sdb_init(key, "nssPrivate", SDB_KEY, &inUpdate,
  2182. newInit, flags, accessOps, keydb);
  2183. if (error != CKR_OK) {
  2184. goto loser;
  2185. }
  2186. }
  2187. loser:
  2188. if (cert) {
  2189. sqlite3_free(cert);
  2190. }
  2191. if (key) {
  2192. sqlite3_free(key);
  2193. }
  2194. if (error != CKR_OK) {
  2195. /* currently redundant, but could be necessary if more code is added
  2196. * just before loser */
  2197. if (keydb && *keydb) {
  2198. sdb_Close(*keydb);
  2199. }
  2200. if (certdb && *certdb) {
  2201. sdb_Close(*certdb);
  2202. }
  2203. }
  2204. return error;
  2205. }
  2206. CK_RV
  2207. s_shutdown()
  2208. {
  2209. #ifdef SQLITE_UNSAFE_THREADS
  2210. if (sqlite_lock) {
  2211. PR_DestroyLock(sqlite_lock);
  2212. sqlite_lock = NULL;
  2213. }
  2214. #endif
  2215. return CKR_OK;
  2216. }