1 /* Copyright (c) 2012-2014 Apple Inc. All Rights Reserved. */
11 #include <sqlite3_private.h>
12 #include <CoreFoundation/CoreFoundation.h>
14 #include "authutilities.h"
18 #define AUTHDB "/var/db/auth.db"
19 #define AUTHDB_DATA "/System/Library/Security/authorization.plist"
21 #define AUTH_STR(x) #x
22 #define AUTH_STRINGIFY(x) AUTH_STR(x)
24 #define AUTHDB_VERSION 1
25 #define AUTHDB_VERSION_STRING AUTH_STRINGIFY(AUTHDB_VERSION)
27 #define AUTHDB_BUSY_DELAY 1
28 #define AUTHDB_MAX_HANDLES 3
30 struct _authdb_connection_s
{
31 __AUTH_BASE_STRUCT_HEADER__
;
38 __AUTH_BASE_STRUCT_HEADER__
;
41 dispatch_queue_t queue
;
42 CFMutableArrayRef connections
;
45 static const char * const authdb_upgrade_sql
[] = {
48 "CREATE TABLE delegates_map ("
49 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
50 "d_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
51 "ord INTEGER NOT NULL"
53 "CREATE INDEX d_map_d_id ON delegates_map(d_id);"
54 "CREATE INDEX d_map_r_id ON delegates_map(r_id);"
55 "CREATE INDEX d_map_r_id_ord ON delegates_map (r_id, ord);"
56 "CREATE TABLE mechanisms ("
57 "id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,"
58 "plugin TEXT NOT NULL,"
59 "param TEXT NOT NULL,"
60 "privileged INTEGER CHECK (privileged = 0 OR privileged = 1) NOT NULL DEFAULT (0)"
62 "CREATE UNIQUE INDEX mechanisms_lookup ON mechanisms (plugin,param,privileged);"
63 "CREATE TABLE mechanisms_map ("
64 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
65 "m_id INTEGER NOT NULL REFERENCES mechanisms(id) ON DELETE CASCADE,"
66 "ord INTEGER NOT NULL"
68 "CREATE INDEX m_map_m_id ON mechanisms_map (m_id);"
69 "CREATE INDEX m_map_r_id ON mechanisms_map (r_id);"
70 "CREATE INDEX m_map_r_id_ord ON mechanisms_map (r_id, ord);"
71 "CREATE TABLE rules ("
72 "id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,"
73 "name TEXT NOT NULL UNIQUE,"
74 "type INTEGER CHECK (type = 1 OR type = 2) NOT NULL,"
75 "class INTEGER CHECK (class > 0),"
81 "version INTEGER NOT NULL DEFAULT (0),"
82 "created REAL NOT NULL DEFAULT (0),"
83 "modified REAL NOT NULL DEFAULT (0),"
89 "CREATE INDEX a_type ON rules (type);"
90 "CREATE TABLE config ("
91 "'key' TEXT PRIMARY KEY NOT NULL UNIQUE,"
94 "CREATE TABLE prompts ("
95 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
99 "CREATE INDEX p_r_id ON prompts(r_id);"
100 "CREATE TABLE buttons ("
101 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
102 "lang TEXT NOT NULL,"
103 "value TEXT NOT NULL"
105 "CREATE INDEX b_r_id ON buttons(r_id);"
106 "INSERT INTO config VALUES('version', "AUTHDB_VERSION_STRING
");"
110 _sqlite3_exec(sqlite3
* handle
, const char * query
)
112 int32_t rc
= SQLITE_ERROR
;
113 require(query
!= NULL
, done
);
115 char * errmsg
= NULL
;
116 rc
= sqlite3_exec(handle
, query
, NULL
, NULL
, &errmsg
);
118 LOGE("authdb: exec, (%i) %s", rc
, errmsg
);
119 sqlite3_free(errmsg
);
126 struct _db_upgrade_stages
{
132 static struct _db_upgrade_stages auth_upgrade_script
[] = {
133 { .pre
= -1, .main
= 0, .post
= -1 } // Create version AUTHDB_VERSION databse.
136 static int32_t _db_run_script(authdb_connection_t dbconn
, int number
)
140 /* Script -1 == skip this step. */
144 /* If we are attempting to run a script we don't have, fail. */
145 if ((size_t)number
>= sizeof(authdb_upgrade_sql
) / sizeof(char*))
146 return SQLITE_CORRUPT
;
148 s3e
= _sqlite3_exec(dbconn
->handle
, authdb_upgrade_sql
[number
]);
153 static int32_t _db_upgrade_from_version(authdb_connection_t dbconn
, int32_t version
)
157 /* If we are attempting to upgrade to a version greater than what we have
158 an upgrade script for, fail. */
160 (size_t)version
>= sizeof(auth_upgrade_script
) / sizeof(struct _db_upgrade_stages
))
161 return SQLITE_CORRUPT
;
163 struct _db_upgrade_stages
*script
= &auth_upgrade_script
[version
];
164 s3e
= _db_run_script(dbconn
, script
->pre
);
165 if (s3e
== SQLITE_OK
)
166 s3e
= _db_run_script(dbconn
, script
->main
);
167 if (s3e
== SQLITE_OK
)
168 s3e
= _db_run_script(dbconn
, script
->post
);
173 static void _printCFError(const char * errmsg
, CFErrorRef err
)
175 CFStringRef errString
= NULL
;
176 errString
= CFErrorCopyDescription(err
);
177 char * tmp
= _copy_cf_string(errString
, NULL
);
178 LOGV("%s, %s", errmsg
, tmp
);
180 CFReleaseSafe(errString
);
183 static void _db_load_data(authdb_connection_t dbconn
, auth_items_t config
)
185 CFURLRef authURL
= NULL
;
186 CFPropertyListRef plist
= NULL
;
187 CFDataRef data
= NULL
;
189 CFErrorRef err
= NULL
;
190 CFTypeRef value
= NULL
;
191 CFAbsoluteTime ts
= 0;
192 CFAbsoluteTime old_ts
= 0;
194 authURL
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, CFSTR(AUTHDB_DATA
), kCFURLPOSIXPathStyle
, false);
195 require_action(authURL
!= NULL
, done
, LOGE("authdb: file not found %s", AUTHDB_DATA
));
197 CFURLCopyResourcePropertyForKey(authURL
, kCFURLContentModificationDateKey
, &value
, &err
);
198 require_action(err
== NULL
, done
, _printCFError("authdb: failed to get modification date", err
));
200 if (CFGetTypeID(value
) == CFDateGetTypeID()) {
201 ts
= CFDateGetAbsoluteTime(value
);
204 old_ts
= auth_items_get_double(config
, "data_ts");
207 LOGV("authdb: %s modified old=%f, new=%f", AUTHDB_DATA
, old_ts
, ts
);
208 CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault
, authURL
, &data
, NULL
, NULL
, (SInt32
*)&rc
);
209 require_noerr_action(rc
, done
, LOGE("authdb: failed to load %s", AUTHDB_DATA
));
211 plist
= CFPropertyListCreateWithData(kCFAllocatorDefault
, data
, kCFPropertyListImmutable
, NULL
, &err
);
212 require_action(err
== NULL
, done
, _printCFError("authdb: failed to read plist", err
));
214 if (authdb_import_plist(dbconn
, plist
, true)) {
215 LOGD("authdb: updating data_ts");
216 auth_items_t update
= auth_items_create();
217 auth_items_set_double(update
, "data_ts", ts
);
218 authdb_set_key_value(dbconn
, "config", update
);
219 CFReleaseSafe(update
);
224 CFReleaseSafe(value
);
225 CFReleaseSafe(authURL
);
226 CFReleaseSafe(plist
);
231 static bool _truncate_db(authdb_connection_t dbconn
)
233 int32_t rc
= SQLITE_ERROR
;
234 int32_t flags
= SQLITE_TRUNCATE_JOURNALMODE_WAL
| SQLITE_TRUNCATE_AUTOVACUUM_FULL
;
235 rc
= sqlite3_file_control(dbconn
->handle
, NULL
, SQLITE_TRUNCATE_DATABASE
, &flags
);
236 if (rc
!= SQLITE_OK
) {
237 LOGV("Failed to delete db handle! SQLite error %i.\n", rc
);
238 if (rc
== SQLITE_IOERR
) {
239 // Unable to recover successfully if we can't truncate
244 return rc
== SQLITE_OK
;
247 static void _handle_corrupt_db(authdb_connection_t dbconn
)
249 int32_t rc
= SQLITE_ERROR
;
250 char buf
[PATH_MAX
+1];
251 sqlite3
*corrupt_db
= NULL
;
253 snprintf(buf
, sizeof(buf
), "%s-corrupt", dbconn
->db
->db_path
);
254 if (sqlite3_open(buf
, &corrupt_db
) == SQLITE_OK
) {
257 sqlite3_file_control(corrupt_db
, 0, SQLITE_FCNTL_PERSIST_WAL
, &on
);
259 rc
= sqlite3_file_control(corrupt_db
, NULL
, SQLITE_REPLACE_DATABASE
, (void *)dbconn
->handle
);
260 if (SQLITE_OK
== rc
) {
261 LOGE("Database at path %s is corrupt. Copying it to %s for further investigation.", dbconn
->db
->db_path
, buf
);
263 LOGE("Tried to copy corrupt database at path %s, but we failed with SQLite error %i.", dbconn
->db
->db_path
, rc
);
265 sqlite3_close(corrupt_db
);
268 _truncate_db(dbconn
);
271 static int32_t _db_maintenance(authdb_connection_t dbconn
)
273 __block
int32_t s3e
= SQLITE_OK
;
274 __block auth_items_t config
= NULL
;
276 authdb_transaction(dbconn
, AuthDBTransactionNormal
, ^bool(void) {
278 authdb_get_key_value(dbconn
, "config", &config
);
280 // We don't have a config table
281 if (NULL
== config
) {
282 LOGV("authdb: initializing database");
283 s3e
= _db_upgrade_from_version(dbconn
, 0);
284 require_noerr_action(s3e
, done
, LOGE("authdb: failed to initialize database %i", s3e
));
286 s3e
= authdb_get_key_value(dbconn
, "config", &config
);
287 require_noerr_action(s3e
, done
, LOGE("authdb: failed to get config %i", s3e
));
290 int64_t currentVersion
= auth_items_get_int64(config
, "version");
291 LOGV("authdb: current db ver=%lli", currentVersion
);
292 if (currentVersion
< AUTHDB_VERSION
) {
293 LOGV("authdb: upgrading schema");
294 s3e
= _db_upgrade_from_version(dbconn
, (int32_t)currentVersion
);
296 auth_items_set_int64(config
, "version", AUTHDB_VERSION
);
297 authdb_set_key_value(dbconn
, "config", config
);
304 CFReleaseSafe(config
);
308 //static void unlock_notify_cb(void **apArg, int nArg AUTH_UNUSED){
309 // dispatch_semaphore_t semaphore = (dispatch_semaphore_t)apArg[0];
310 // dispatch_semaphore_signal(semaphore);
313 //static int32_t _wait_for_unlock_notify(authdb_connection_t dbconn, sqlite3_stmt * stmt)
316 // dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
318 // rc = sqlite3_unlock_notify(dbconn->handle, unlock_notify_cb, semaphore);
319 // require(!rc, done);
321 // if (dispatch_semaphore_wait(semaphore, 5*NSEC_PER_SEC) != 0) {
322 // LOGV("authdb: timeout occurred!");
323 // sqlite3_unlock_notify(dbconn->handle, NULL, NULL);
324 // rc = SQLITE_LOCKED;
326 // sqlite3_reset(stmt);
330 // dispatch_release(semaphore);
334 static bool _is_busy(int32_t rc
)
336 return SQLITE_BUSY
== rc
|| SQLITE_LOCKED
== rc
;
339 static void _checkResult(authdb_connection_t dbconn
, int32_t rc
, const char * fn_name
, sqlite3_stmt
* stmt
)
341 bool isCorrupt
= (SQLITE_CORRUPT
== rc
) || (SQLITE_NOTADB
== rc
) || (SQLITE_IOERR
== rc
);
344 _handle_corrupt_db(dbconn
);
345 authdb_maintenance(dbconn
);
346 } else if (SQLITE_CONSTRAINT
== rc
|| SQLITE_READONLY
== rc
) {
348 LOGV("authdb: %s %s for %s", fn_name
, sqlite3_errmsg(dbconn
->handle
), sqlite3_sql(stmt
));
350 LOGV("authdb: %s %s", fn_name
, sqlite3_errmsg(dbconn
->handle
));
355 char * authdb_copy_sql_string(sqlite3_stmt
* sql
,int32_t col
)
357 char * result
= NULL
;
358 const char * sql_str
= (const char *)sqlite3_column_text(sql
, col
);
360 size_t len
= strlen(sql_str
) + 1;
361 result
= (char*)calloc(1u, len
);
362 check(result
!= NULL
);
364 strlcpy(result
, sql_str
, len
);
370 #pragma mark authdb_t
373 _authdb_finalize(CFTypeRef value
)
375 authdb_t db
= (authdb_t
)value
;
377 CFReleaseSafe(db
->connections
);
378 dispatch_release(db
->queue
);
379 free_safe(db
->db_path
);
382 AUTH_TYPE_INSTANCE(authdb
,
385 .finalize
= _authdb_finalize
,
388 .copyFormattingDesc
= NULL
,
389 .copyDebugDesc
= NULL
392 static CFTypeID
authdb_get_type_id() {
393 static CFTypeID type_id
= _kCFRuntimeNotATypeID
;
394 static dispatch_once_t onceToken
;
396 dispatch_once(&onceToken
, ^{
397 type_id
= _CFRuntimeRegisterClass(&_auth_type_authdb
);
408 db
= (authdb_t
)_CFRuntimeCreateInstance(kCFAllocatorDefault
, authdb_get_type_id(), AUTH_CLASS_SIZE(authdb
), NULL
);
409 require(db
!= NULL
, done
);
411 db
->queue
= dispatch_queue_create(NULL
, DISPATCH_QUEUE_SERIAL
);
412 db
->connections
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, NULL
);
414 if (getenv("__OSINSTALL_ENVIRONMENT") != NULL
) {
415 LOGV("authdb: running from installer");
416 db
->db_path
= _copy_string("file::memory:?cache=shared");
418 db
->db_path
= _copy_string(AUTHDB
);
425 authdb_connection_t
authdb_connection_acquire(authdb_t db
)
427 __block authdb_connection_t dbconn
= NULL
;
429 static int32_t total
= 0;
431 dispatch_sync(db
->queue
, ^{
432 CFIndex count
= CFArrayGetCount(db
->connections
);
434 dbconn
= (authdb_connection_t
)CFArrayGetValueAtIndex(db
->connections
, 0);
435 CFArrayRemoveValueAtIndex(db
->connections
, 0);
437 dbconn
= authdb_connection_create(db
);
440 LOGV("authdb: no handles available total: %i", total
);
448 void authdb_connection_release(authdb_connection_t
* dbconn
)
450 if (!dbconn
|| !(*dbconn
))
453 authdb_connection_t tmp
= *dbconn
;
456 dispatch_async(tmp
->db
->queue
, ^{
457 CFIndex count
= CFArrayGetCount(tmp
->db
->connections
);
458 if (count
<= AUTHDB_MAX_HANDLES
) {
459 CFArrayAppendValue(tmp
->db
->connections
, tmp
);
461 LOGD("authdb: freeing extra connection");
467 static bool _db_check_corrupted(authdb_connection_t dbconn
)
469 bool isCorrupted
= true;
470 sqlite3_stmt
*stmt
= NULL
;
473 rc
= sqlite3_prepare_v2(dbconn
->handle
, "PRAGMA integrity_check;", -1, &stmt
, NULL
);
474 if (rc
== SQLITE_LOCKED
|| rc
== SQLITE_BUSY
) {
475 LOGV("authdb: warning error %i when running integrity check", rc
);
478 } else if (rc
== SQLITE_OK
) {
479 rc
= sqlite3_step(stmt
);
481 if (rc
== SQLITE_LOCKED
|| rc
== SQLITE_BUSY
) {
482 LOGV("authdb: warning error %i when running integrity check", rc
);
484 } else if (rc
== SQLITE_ROW
) {
485 const char * result
= (const char*)sqlite3_column_text(stmt
, 0);
487 if (result
&& strncasecmp(result
, "ok", 3) == 0) {
493 sqlite3_finalize(stmt
);
497 bool authdb_maintenance(authdb_connection_t dbconn
)
499 LOGD("authdb: starting maintenance");
500 int32_t rc
= SQLITE_ERROR
;
501 auth_items_t config
= NULL
;
503 bool isCorrupted
= _db_check_corrupted(dbconn
);
504 LOGD("authdb: integrity check=%s", isCorrupted
? "fail" : "pass");
507 _handle_corrupt_db(dbconn
);
510 _db_maintenance(dbconn
);
512 rc
= authdb_get_key_value(dbconn
, "config", &config
);
513 require_noerr_action(rc
, done
, LOGV("authdb: maintenance failed %i", rc
));
515 _db_load_data(dbconn
, config
);
518 CFReleaseSafe(config
);
519 LOGD("authdb: finished maintenance");
520 return rc
== SQLITE_OK
;
524 authdb_exec(authdb_connection_t dbconn
, const char * query
)
526 int32_t rc
= SQLITE_ERROR
;
527 require(query
!= NULL
, done
);
529 rc
= _sqlite3_exec(dbconn
->handle
, query
);
530 _checkResult(dbconn
, rc
, __FUNCTION__
, NULL
);
536 static int32_t _prepare(authdb_connection_t dbconn
, const char * sql
, sqlite3_stmt
** out_stmt
)
539 sqlite3_stmt
* stmt
= NULL
;
541 require_action(sql
!= NULL
, done
, rc
= SQLITE_ERROR
);
542 require_action(out_stmt
!= NULL
, done
, rc
= SQLITE_ERROR
);
544 rc
= sqlite3_prepare_v2(dbconn
->handle
, sql
, -1, &stmt
, NULL
);
545 require_noerr_action(rc
, done
, LOGV("authdb: prepare (%i) %s", rc
, sqlite3_errmsg(dbconn
->handle
)));
550 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
);
554 static void _parseItemsAtIndex(sqlite3_stmt
* stmt
, int32_t col
, auth_items_t items
, const char * key
)
556 switch (sqlite3_column_type(stmt
, col
)) {
558 auth_items_set_double(items
, key
, sqlite3_column_double(stmt
, col
));
561 auth_items_set_int64(items
, key
, sqlite3_column_int64(stmt
, col
));
564 auth_items_set_data(items
,
566 sqlite3_column_blob(stmt
, col
),
567 (size_t)sqlite3_column_bytes(stmt
, col
));
573 auth_items_set_string(items
, key
, (const char *)sqlite3_column_text(stmt
, col
));
577 // LOGD("authdb: col=%s, val=%s, type=%i", sqlite3_column_name(stmt, col), sqlite3_column_text(stmt, col), sqlite3_column_type(stmt,col));
580 static int32_t _bindItemsAtIndex(sqlite3_stmt
* stmt
, int col
, auth_items_t items
, const char * key
)
583 switch (auth_items_get_type(items
, key
)) {
585 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_int(items
, key
));
588 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_uint(items
, key
));
591 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_int64(items
, key
));
594 rc
= sqlite3_bind_int64(stmt
, col
, (int64_t)auth_items_get_uint64(items
, key
));
597 rc
= sqlite3_bind_double(stmt
, col
, auth_items_get_double(items
, key
));
600 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_bool(items
, key
));
605 const void * blob
= auth_items_get_data(items
, key
, &blobLen
);
606 rc
= sqlite3_bind_blob(stmt
, col
, blob
, (int32_t)blobLen
, NULL
);
610 rc
= sqlite3_bind_text(stmt
, col
, auth_items_get_string(items
, key
), -1, NULL
);
613 rc
= sqlite3_bind_null(stmt
, col
);
616 if (rc
!= SQLITE_OK
) {
617 LOGV("authdb: auth_items bind failed (%i)", rc
);
622 int32_t authdb_get_key_value(authdb_connection_t dbconn
, const char * table
, auth_items_t
* out_items
)
624 int32_t rc
= SQLITE_ERROR
;
626 sqlite3_stmt
* stmt
= NULL
;
627 auth_items_t items
= NULL
;
629 require(table
!= NULL
, done
);
630 require(out_items
!= NULL
, done
);
632 asprintf(&query
, "SELECT * FROM %s", table
);
634 rc
= _prepare(dbconn
, query
, &stmt
);
635 require_noerr(rc
, done
);
637 items
= auth_items_create();
638 while ((rc
= sqlite3_step(stmt
)) != SQLITE_DONE
) {
641 _parseItemsAtIndex(stmt
, 1, items
, (const char*)sqlite3_column_text(stmt
, 0));
644 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
);
646 sleep(AUTHDB_BUSY_DELAY
);
648 require_noerr_action(rc
, done
, LOGV("authdb: get_key_value (%i) %s", rc
, sqlite3_errmsg(dbconn
->handle
)));
659 CFReleaseSafe(items
);
661 sqlite3_finalize(stmt
);
665 int32_t authdb_set_key_value(authdb_connection_t dbconn
, const char * table
, auth_items_t items
)
667 __block
int32_t rc
= SQLITE_ERROR
;
669 sqlite3_stmt
* stmt
= NULL
;
671 require(table
!= NULL
, done
);
672 require(items
!= NULL
, done
);
674 asprintf(&query
, "INSERT OR REPLACE INTO %s VALUES (?,?)", table
);
676 rc
= _prepare(dbconn
, query
, &stmt
);
677 require_noerr(rc
, done
);
679 auth_items_iterate(items
, ^bool(const char *key
) {
681 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
);
683 sqlite3_bind_text(stmt
, 1, key
, -1, NULL
);
684 _bindItemsAtIndex(stmt
, 2, items
, key
);
686 rc
= sqlite3_step(stmt
);
687 if (rc
!= SQLITE_DONE
) {
688 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
);
689 LOGV("authdb: set_key_value, step (%i) %s", rc
, sqlite3_errmsg(dbconn
->handle
));
697 sqlite3_finalize(stmt
);
701 static int32_t _begin_transaction_type(authdb_connection_t dbconn
, AuthDBTransactionType type
)
703 int32_t result
= SQLITE_ERROR
;
705 const char * query
= NULL
;
707 case AuthDBTransactionImmediate
:
708 query
= "BEGIN IMMEDATE;";
710 case AuthDBTransactionExclusive
:
711 query
= "BEGIN EXCLUSIVE;";
713 case AuthDBTransactionNormal
:
722 if (query
!= NULL
&& sqlite3_get_autocommit(dbconn
->handle
) != 0) {
723 result
= _sqlite3_exec(dbconn
->handle
, query
);
729 static int32_t _end_transaction(authdb_connection_t dbconn
, bool commit
)
732 return _sqlite3_exec(dbconn
->handle
, "END;");
734 return _sqlite3_exec(dbconn
->handle
, "ROLLBACK;");
738 bool authdb_transaction(authdb_connection_t dbconn
, AuthDBTransactionType type
, bool (^t
)(void))
740 int32_t result
= SQLITE_ERROR
;
743 result
= _begin_transaction_type(dbconn
, type
);
744 require_action(result
== SQLITE_OK
, done
, LOGV("authdb: transaction begin failed %i", result
));
748 result
= _end_transaction(dbconn
, commit
);
749 require_action(result
== SQLITE_OK
, done
, commit
= false; LOGV("authdb: transaction end failed %i", result
));
755 bool authdb_step(authdb_connection_t dbconn
, const char * sql
, void (^bind_stmt
)(sqlite3_stmt
*), authdb_iterator_t iter
)
758 sqlite3_stmt
* stmt
= NULL
;
759 int32_t rc
= SQLITE_ERROR
;
761 require_action(sql
!= NULL
, done
, rc
= SQLITE_ERROR
);
763 rc
= _prepare(dbconn
, sql
, &stmt
);
764 require_noerr(rc
, done
);
770 int32_t count
= sqlite3_column_count(stmt
);
772 auth_items_t items
= NULL
;
773 while ((rc
= sqlite3_step(stmt
)) != SQLITE_DONE
) {
778 items
= auth_items_create();
779 for (int i
= 0; i
< count
; i
++) {
780 _parseItemsAtIndex(stmt
, i
, items
, sqlite3_column_name(stmt
, i
));
782 result
= iter(items
);
783 CFReleaseNull(items
);
792 LOGV("authdb: %s", sqlite3_errmsg(dbconn
->handle
));
793 sleep(AUTHDB_BUSY_DELAY
);
796 require_noerr_action(rc
, done
, LOGV("authdb: step (%i) %s", rc
, sqlite3_errmsg(dbconn
->handle
)));
803 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
);
804 sqlite3_finalize(stmt
);
805 return rc
== SQLITE_DONE
;
808 void authdb_checkpoint(authdb_connection_t dbconn
)
810 int32_t rc
= sqlite3_wal_checkpoint(dbconn
->handle
, NULL
);
811 if (rc
!= SQLITE_OK
) {
812 LOGV("authdb: checkpoit failed %i", rc
);
816 static CFMutableArrayRef
817 _copy_rules_dict(RuleType type
, CFDictionaryRef plist
, authdb_connection_t dbconn
)
819 CFMutableArrayRef result
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
820 require(result
!= NULL
, done
);
822 _cf_dictionary_iterate(plist
, ^bool(CFTypeRef key
, CFTypeRef value
) {
823 if (CFGetTypeID(key
) != CFStringGetTypeID()) {
827 if (CFGetTypeID(value
) != CFDictionaryGetTypeID()) {
831 rule_t rule
= rule_create_with_plist(type
, key
, value
, dbconn
);
833 CFArrayAppendValue(result
, rule
);
845 _import_rules(authdb_connection_t dbconn
, CFMutableArrayRef rules
, bool version_check
, CFAbsoluteTime now
)
847 CFMutableArrayRef notcommited
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
848 CFIndex count
= CFArrayGetCount(rules
);
850 for (CFIndex i
= 0; i
< count
; i
++) {
851 rule_t rule
= (rule_t
)CFArrayGetValueAtIndex(rules
, i
);
855 if (rule_get_id(rule
) != 0) { // rule already exists see if we need to update
856 rule_t current
= rule_create_with_string(rule_get_name(rule
), dbconn
);
857 if (rule_get_version(rule
) > rule_get_version(current
)) {
860 CFReleaseSafe(current
);
868 __block
bool delayCommit
= false;
870 switch (rule_get_type(rule
)) {
872 rule_delegates_iterator(rule
, ^bool(rule_t delegate
) {
873 if (rule_get_id(delegate
) == 0) {
874 // fetch the rule from the database if it was previously committed
875 rule_sql_fetch(delegate
, dbconn
);
877 if (rule_get_id(delegate
) == 0) {
878 LOGD("authdb: delaying %s waiting for delegate %s", rule_get_name(rule
), rule_get_name(delegate
));
890 bool success
= rule_sql_commit(rule
, dbconn
, now
, NULL
);
891 LOGV("authdb: %s %s %s %s",
892 update
? "updating" : "importing",
893 rule_get_type(rule
) == RT_RULE
? "rule" : "right",
894 rule_get_name(rule
), success
? "success" : "FAIL");
896 CFArrayAppendValue(notcommited
, rule
);
899 CFArrayAppendValue(notcommited
, rule
);
902 CFArrayRemoveAllValues(rules
);
903 CFArrayAppendArray(rules
, notcommited
, CFRangeMake(0, CFArrayGetCount(notcommited
)));
904 CFReleaseSafe(notcommited
);
908 authdb_import_plist(authdb_connection_t dbconn
, CFDictionaryRef plist
, bool version_check
)
912 LOGV("authdb: starting import");
914 CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
915 CFMutableArrayRef rights
= NULL
;
916 CFMutableArrayRef rules
= NULL
;
917 require(plist
!= NULL
, done
);
919 CFTypeRef rightsDict
= CFDictionaryGetValue(plist
, CFSTR("rights"));
920 if (rightsDict
&& CFGetTypeID(rightsDict
) == CFDictionaryGetTypeID()) {
921 rights
= _copy_rules_dict(RT_RIGHT
, rightsDict
, dbconn
);
924 CFTypeRef rulesDict
= CFDictionaryGetValue(plist
, CFSTR("rules"));
925 if (rulesDict
&& CFGetTypeID(rulesDict
) == CFDictionaryGetTypeID()) {
926 rules
= _copy_rules_dict(RT_RULE
, rulesDict
, dbconn
);
929 LOGV("authdb: rights = %li", CFArrayGetCount(rights
));
930 LOGV("authdb: rules = %li", CFArrayGetCount(rules
));
933 // first pass import base rules without delegations
934 // remaining import rules that delegate to other rules
935 // loop upto 3 times to commit dependent rules first
936 for (int32_t j
= 0; j
< 3; j
++) {
937 count
= CFArrayGetCount(rules
);
941 _import_rules(dbconn
, rules
, version_check
, now
);
944 _import_rules(dbconn
, rights
, version_check
, now
);
946 if (CFArrayGetCount(rights
) == 0) {
950 authdb_checkpoint(dbconn
);
953 CFReleaseSafe(rights
);
954 CFReleaseSafe(rules
);
956 LOGV("authdb: finished import, %s", result
? "succeeded" : "failed");
962 #pragma mark authdb_connection_t
964 static bool _sql_profile_enabled(void)
966 static bool profile_enabled
= false;
969 static dispatch_once_t onceToken
;
971 //sudo defaults write /Library/Preferences/com.apple.security.auth profile -bool true
972 dispatch_once(&onceToken
, ^{
973 CFTypeRef profile
= (CFNumberRef
)CFPreferencesCopyValue(CFSTR("profile"), CFSTR(SECURITY_AUTH_NAME
), kCFPreferencesAnyUser
, kCFPreferencesCurrentHost
);
975 if (profile
&& CFGetTypeID(profile
) == CFBooleanGetTypeID()) {
976 profile_enabled
= CFBooleanGetValue((CFBooleanRef
)profile
);
979 LOGV("authdb: sql profile: %s", profile_enabled
? "enabled" : "disabled");
981 CFReleaseSafe(profile
);
985 return profile_enabled
;
988 static void _profile(void *context AUTH_UNUSED
, const char *sql
, sqlite3_uint64 ns
) {
989 LOGV("==\nauthdb: %s\nTime: %llu ms\n", sql
, ns
>> 20);
992 static sqlite3
* _create_handle(authdb_t db
)
994 bool dbcreated
= false;
995 sqlite3
* handle
= NULL
;
996 int32_t rc
= sqlite3_open_v2(db
->db_path
, &handle
, SQLITE_OPEN_READWRITE
, NULL
);
998 if (rc
!= SQLITE_OK
) {
999 char * tmp
= dirname(db
->db_path
);
1001 mkpath_np(tmp
, 0700);
1003 rc
= sqlite3_open_v2(db
->db_path
, &handle
, SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, NULL
);
1006 require_noerr_action(rc
, done
, LOGE("authdb: open %s (%i) %s", db
->db_path
, rc
, sqlite3_errmsg(handle
)));
1008 if (_sql_profile_enabled()) {
1009 sqlite3_profile(handle
, _profile
, NULL
);
1012 _sqlite3_exec(handle
, "PRAGMA foreign_keys = ON");
1013 _sqlite3_exec(handle
, "PRAGMA temp_store = MEMORY");
1016 _sqlite3_exec(handle
, "PRAGMA auto_vacuum = FULL");
1017 _sqlite3_exec(handle
, "PRAGMA journal_mode = WAL");
1020 sqlite3_file_control(handle
, 0, SQLITE_FCNTL_PERSIST_WAL
, &on
);
1022 chmod(db
->db_path
, S_IRUSR
| S_IWUSR
);
1030 _authdb_connection_finalize(CFTypeRef value
)
1032 authdb_connection_t dbconn
= (authdb_connection_t
)value
;
1034 if (dbconn
->handle
) {
1035 sqlite3_close(dbconn
->handle
);
1037 CFReleaseSafe(dbconn
->db
);
1040 AUTH_TYPE_INSTANCE(authdb_connection
,
1043 .finalize
= _authdb_connection_finalize
,
1046 .copyFormattingDesc
= NULL
,
1047 .copyDebugDesc
= NULL
1050 static CFTypeID
authdb_connection_get_type_id() {
1051 static CFTypeID type_id
= _kCFRuntimeNotATypeID
;
1052 static dispatch_once_t onceToken
;
1054 dispatch_once(&onceToken
, ^{
1055 type_id
= _CFRuntimeRegisterClass(&_auth_type_authdb_connection
);
1062 authdb_connection_create(authdb_t db
)
1064 authdb_connection_t dbconn
= NULL
;
1066 dbconn
= (authdb_connection_t
)_CFRuntimeCreateInstance(kCFAllocatorDefault
, authdb_connection_get_type_id(), AUTH_CLASS_SIZE(authdb_connection
), NULL
);
1067 require(dbconn
!= NULL
, done
);
1069 dbconn
->db
= (authdb_t
)CFRetain(db
);
1070 dbconn
->handle
= _create_handle(dbconn
->db
);