1 /* Copyright (c) 2012-2014 Apple Inc. All Rights Reserved. */
11 #include <sqlite3_private.h>
12 #include <CoreFoundation/CoreFoundation.h>
14 #include "authutilities.h"
20 #define AUTHDB "/var/db/auth.db"
21 #define AUTHDB_DATA "/System/Library/Security/authorization.plist"
23 #define AUTH_STR(x) #x
24 #define AUTH_STRINGIFY(x) AUTH_STR(x)
26 #define AUTHDB_VERSION 1
27 #define AUTHDB_VERSION_STRING AUTH_STRINGIFY(AUTHDB_VERSION)
29 #define AUTHDB_BUSY_DELAY 1
30 #define AUTHDB_MAX_HANDLES 3
32 struct _authdb_connection_s
{
33 __AUTH_BASE_STRUCT_HEADER__
;
40 __AUTH_BASE_STRUCT_HEADER__
;
43 dispatch_queue_t queue
;
44 CFMutableArrayRef connections
;
47 static const char * const authdb_upgrade_sql
[] = {
50 "CREATE TABLE delegates_map ("
51 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
52 "d_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
53 "ord INTEGER NOT NULL"
55 "CREATE INDEX d_map_d_id ON delegates_map(d_id);"
56 "CREATE INDEX d_map_r_id ON delegates_map(r_id);"
57 "CREATE INDEX d_map_r_id_ord ON delegates_map (r_id, ord);"
58 "CREATE TABLE mechanisms ("
59 "id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,"
60 "plugin TEXT NOT NULL,"
61 "param TEXT NOT NULL,"
62 "privileged INTEGER CHECK (privileged = 0 OR privileged = 1) NOT NULL DEFAULT (0)"
64 "CREATE UNIQUE INDEX mechanisms_lookup ON mechanisms (plugin,param,privileged);"
65 "CREATE TABLE mechanisms_map ("
66 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
67 "m_id INTEGER NOT NULL REFERENCES mechanisms(id) ON DELETE CASCADE,"
68 "ord INTEGER NOT NULL"
70 "CREATE INDEX m_map_m_id ON mechanisms_map (m_id);"
71 "CREATE INDEX m_map_r_id ON mechanisms_map (r_id);"
72 "CREATE INDEX m_map_r_id_ord ON mechanisms_map (r_id, ord);"
73 "CREATE TABLE rules ("
74 "id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,"
75 "name TEXT NOT NULL UNIQUE,"
76 "type INTEGER CHECK (type = 1 OR type = 2) NOT NULL,"
77 "class INTEGER CHECK (class > 0),"
83 "version INTEGER NOT NULL DEFAULT (0),"
84 "created REAL NOT NULL DEFAULT (0),"
85 "modified REAL NOT NULL DEFAULT (0),"
91 "CREATE INDEX a_type ON rules (type);"
92 "CREATE TABLE config ("
93 "'key' TEXT PRIMARY KEY NOT NULL UNIQUE,"
96 "CREATE TABLE prompts ("
97 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
101 "CREATE INDEX p_r_id ON prompts(r_id);"
102 "CREATE TABLE buttons ("
103 "r_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE,"
104 "lang TEXT NOT NULL,"
105 "value TEXT NOT NULL"
107 "CREATE INDEX b_r_id ON buttons(r_id);"
108 "INSERT INTO config VALUES('version', "AUTHDB_VERSION_STRING
");"
111 static sqlite3
* _create_handle(authdb_t db
);
114 _sqlite3_exec(sqlite3
* handle
, const char * query
)
116 int32_t rc
= SQLITE_ERROR
;
117 require(query
!= NULL
, done
);
119 char * errmsg
= NULL
;
120 rc
= sqlite3_exec(handle
, query
, NULL
, NULL
, &errmsg
);
122 os_log_error(AUTHD_LOG
, "authdb: exec, (%i) %{public}s", rc
, errmsg
);
123 sqlite3_free(errmsg
);
130 struct _db_upgrade_stages
{
136 static struct _db_upgrade_stages auth_upgrade_script
[] = {
137 { .pre
= -1, .main
= 0, .post
= -1 } // Create version AUTHDB_VERSION databse.
140 static int32_t _db_run_script(authdb_connection_t dbconn
, int number
)
144 /* Script -1 == skip this step. */
148 /* If we are attempting to run a script we don't have, fail. */
149 if ((size_t)number
>= sizeof(authdb_upgrade_sql
) / sizeof(char*))
150 return SQLITE_CORRUPT
;
152 s3e
= _sqlite3_exec(dbconn
->handle
, authdb_upgrade_sql
[number
]);
157 static int32_t _db_upgrade_from_version(authdb_connection_t dbconn
, int32_t version
)
161 /* If we are attempting to upgrade to a version greater than what we have
162 an upgrade script for, fail. */
164 (size_t)version
>= sizeof(auth_upgrade_script
) / sizeof(struct _db_upgrade_stages
))
165 return SQLITE_CORRUPT
;
167 struct _db_upgrade_stages
*script
= &auth_upgrade_script
[version
];
168 s3e
= _db_run_script(dbconn
, script
->pre
);
169 if (s3e
== SQLITE_OK
)
170 s3e
= _db_run_script(dbconn
, script
->main
);
171 if (s3e
== SQLITE_OK
)
172 s3e
= _db_run_script(dbconn
, script
->post
);
177 static void _db_load_data(authdb_connection_t dbconn
, auth_items_t config
)
179 CFURLRef authURL
= NULL
;
180 CFPropertyListRef plist
= NULL
;
181 CFDataRef data
= NULL
;
183 CFErrorRef err
= NULL
;
184 CFTypeRef value
= NULL
;
185 CFAbsoluteTime ts
= 0;
186 CFAbsoluteTime old_ts
= 0;
189 authURL
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, CFSTR(AUTHDB_DATA
), kCFURLPOSIXPathStyle
, false);
190 require_action(authURL
!= NULL
, done
, os_log_error(AUTHD_LOG
, "authdb: file not found %{public}s", AUTHDB_DATA
));
192 ok
= CFURLCopyResourcePropertyForKey(authURL
, kCFURLContentModificationDateKey
, &value
, &err
);
193 require_action(ok
&& value
!= NULL
, done
, os_log_error(AUTHD_LOG
, "authdb: failed to get modification date: %{public}@", err
));
195 if (CFGetTypeID(value
) == CFDateGetTypeID()) {
196 ts
= CFDateGetAbsoluteTime(value
);
199 old_ts
= auth_items_get_double(config
, "data_ts");
201 // <rdar://problem/17484375> SEED: BUG: Fast User Switching Not Working
202 // After Mavericks => Yosemite upgrade install, the new Yosemite rule "system.login.fus" was missing.
203 // Somehow (probably during install) ts < old_ts, even though that should never happen.
204 // Solution: always import plist and update db when time stamps don't match.
205 // After a successful import, old_ts = ts below.
207 os_log_debug(AUTHD_LOG
, "authdb: %{public}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
, os_log_error(AUTHD_LOG
, "authdb: failed to load %{public}s", AUTHDB_DATA
));
211 plist
= CFPropertyListCreateWithData(kCFAllocatorDefault
, data
, kCFPropertyListImmutable
, NULL
, &err
);
212 require_action(err
== NULL
, done
, os_log_error(AUTHD_LOG
, "authdb: failed to read plist: %{public}@", err
));
214 if (authdb_import_plist(dbconn
, plist
, true)) {
215 os_log_debug(AUTHD_LOG
, "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 os_log_debug(AUTHD_LOG
, "Failed to delete db handle! SQLite error %i.", 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 os_log_error(AUTHD_LOG
, "Database at path %{public}s is corrupt. Copying it to %{public}s for further investigation.", dbconn
->db
->db_path
, buf
);
263 os_log_error(AUTHD_LOG
, "Tried to copy corrupt database at path %{public}s, but we failed with SQLite error %i.", dbconn
->db
->db_path
, rc
);
267 // SQLite documentation says:
268 // Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.
270 sqlite3_close(corrupt_db
);
272 _truncate_db(dbconn
);
275 static int32_t _db_maintenance(authdb_connection_t dbconn
)
277 __block
int32_t s3e
= SQLITE_OK
;
278 __block auth_items_t config
= NULL
;
280 authdb_transaction(dbconn
, AuthDBTransactionNormal
, ^bool(void) {
282 authdb_get_key_value(dbconn
, "config", true, &config
);
284 // We don't have a config table
285 if (NULL
== config
) {
286 os_log_debug(AUTHD_LOG
, "authdb: initializing database");
287 s3e
= _db_upgrade_from_version(dbconn
, 0);
288 require_noerr_action(s3e
, done
, os_log_error(AUTHD_LOG
, "authdb: failed to initialize database %i", s3e
));
290 s3e
= authdb_get_key_value(dbconn
, "config", true, &config
);
291 require_noerr_action(s3e
, done
, os_log_error(AUTHD_LOG
, "authdb: failed to get config %i", s3e
));
294 int64_t currentVersion
= auth_items_get_int64(config
, "version");
295 os_log_debug(AUTHD_LOG
, "authdb: current db ver=%lli", currentVersion
);
296 if (currentVersion
< AUTHDB_VERSION
) {
297 os_log_debug(AUTHD_LOG
, "authdb: upgrading schema");
298 s3e
= _db_upgrade_from_version(dbconn
, (int32_t)currentVersion
);
300 auth_items_set_int64(config
, "version", AUTHDB_VERSION
);
301 authdb_set_key_value(dbconn
, "config", config
);
308 CFReleaseSafe(config
);
312 //static void unlock_notify_cb(void **apArg, int nArg AUTH_UNUSED){
313 // dispatch_semaphore_t semaphore = (dispatch_semaphore_t)apArg[0];
314 // dispatch_semaphore_signal(semaphore);
317 //static int32_t _wait_for_unlock_notify(authdb_connection_t dbconn, sqlite3_stmt * stmt)
320 // dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
322 // rc = sqlite3_unlock_notify(dbconn->handle, unlock_notify_cb, semaphore);
323 // require(!rc, done);
325 // if (dispatch_semaphore_wait(semaphore, 5*NSEC_PER_SEC) != 0) {
326 // os_log_debug(AUTHD_LOG, "authdb: timeout occurred!");
327 // sqlite3_unlock_notify(dbconn->handle, NULL, NULL);
328 // rc = SQLITE_LOCKED;
330 // sqlite3_reset(stmt);
334 // dispatch_release(semaphore);
338 static bool _is_busy(int32_t rc
)
340 return SQLITE_BUSY
== rc
|| SQLITE_LOCKED
== rc
;
343 static void _checkResult(authdb_connection_t dbconn
, int32_t rc
, const char * fn_name
, sqlite3_stmt
* stmt
, const bool skip_maintenance
)
345 bool isCorrupt
= (SQLITE_CORRUPT
== rc
) || (SQLITE_NOTADB
== rc
) || (SQLITE_IOERR
== rc
);
348 if (skip_maintenance
) {
349 os_log_debug(AUTHD_LOG
, "authdb: corrupted db, skipping maintenance %{public}s %{public}s", fn_name
, sqlite3_errmsg(dbconn
->handle
));
351 _handle_corrupt_db(dbconn
);
352 authdb_maintenance(dbconn
);
354 } else if (SQLITE_CONSTRAINT
== rc
|| SQLITE_READONLY
== rc
) {
356 os_log_debug(AUTHD_LOG
, "authdb: %{public}s %{public}s for %{public}s", fn_name
, sqlite3_errmsg(dbconn
->handle
), sqlite3_sql(stmt
));
358 os_log_debug(AUTHD_LOG
, "authdb: %{public}s %{public}s", fn_name
, sqlite3_errmsg(dbconn
->handle
));
363 char * authdb_copy_sql_string(sqlite3_stmt
* sql
,int32_t col
)
365 char * result
= NULL
;
366 const char * sql_str
= (const char *)sqlite3_column_text(sql
, col
);
368 size_t len
= strlen(sql_str
) + 1;
369 result
= (char*)calloc(1u, len
);
370 check(result
!= NULL
);
372 strlcpy(result
, sql_str
, len
);
378 #pragma mark authdb_t
381 _authdb_finalize(CFTypeRef value
)
383 authdb_t db
= (authdb_t
)value
;
385 CFReleaseNull(db
->connections
);
386 dispatch_release(db
->queue
);
387 free_safe(db
->db_path
);
390 AUTH_TYPE_INSTANCE(authdb
,
393 .finalize
= _authdb_finalize
,
396 .copyFormattingDesc
= NULL
,
397 .copyDebugDesc
= NULL
400 static CFTypeID
authdb_get_type_id() {
401 static CFTypeID type_id
= _kCFRuntimeNotATypeID
;
402 static dispatch_once_t onceToken
;
404 dispatch_once(&onceToken
, ^{
405 type_id
= _CFRuntimeRegisterClass(&_auth_type_authdb
);
416 db
= (authdb_t
)_CFRuntimeCreateInstance(kCFAllocatorDefault
, authdb_get_type_id(), AUTH_CLASS_SIZE(authdb
), NULL
);
417 require(db
!= NULL
, done
);
419 db
->queue
= dispatch_queue_create(NULL
, DISPATCH_QUEUE_SERIAL
);
420 db
->connections
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, NULL
);
422 if (getenv("__OSINSTALL_ENVIRONMENT") != NULL
) {
423 os_log_debug(AUTHD_LOG
, "authdb: running from installer");
424 db
->db_path
= _copy_string("file::memory:?cache=shared");
426 db
->db_path
= _copy_string(AUTHDB
);
433 authdb_connection_t
authdb_connection_acquire(authdb_t db
)
435 __block authdb_connection_t dbconn
= NULL
;
437 static int32_t total
= 0;
439 dispatch_sync(db
->queue
, ^{
440 CFIndex count
= CFArrayGetCount(db
->connections
);
442 dbconn
= (authdb_connection_t
)CFArrayGetValueAtIndex(db
->connections
, 0);
443 CFArrayRemoveValueAtIndex(db
->connections
, 0);
445 dbconn
= authdb_connection_create(db
);
448 os_log_debug(AUTHD_LOG
, "authdb: no handles available total: %i", total
);
456 void authdb_connection_release(authdb_connection_t
* dbconn
)
461 authdb_connection_t tmp
= *dbconn
;
464 dispatch_async(tmp
->db
->queue
, ^{
465 CFIndex count
= CFArrayGetCount(tmp
->db
->connections
);
466 if (count
<= AUTHDB_MAX_HANDLES
) {
467 CFArrayAppendValue(tmp
->db
->connections
, tmp
);
469 os_log_debug(AUTHD_LOG
, "authdb: freeing extra connection");
475 static bool _db_check_corrupted(authdb_connection_t dbconn
)
477 bool isCorrupted
= true;
478 sqlite3_stmt
*stmt
= NULL
;
484 rc
= sqlite3_prepare_v2(dbconn
->handle
, "PRAGMA integrity_check;", -1, &stmt
, NULL
);
485 if (rc
== SQLITE_LOCKED
|| rc
== SQLITE_BUSY
) {
486 os_log_debug(AUTHD_LOG
, "authdb: warning error %i when running integrity check", rc
);
489 } else if (rc
== SQLITE_OK
) {
490 rc
= sqlite3_step(stmt
);
492 if (rc
== SQLITE_LOCKED
|| rc
== SQLITE_BUSY
) {
493 os_log_debug(AUTHD_LOG
, "authdb: warning error %i when running integrity check", rc
);
495 } else if (rc
== SQLITE_ROW
) {
496 const char * result
= (const char*)sqlite3_column_text(stmt
, 0);
498 if (result
&& strncasecmp(result
, "ok", 3) == 0) {
504 sqlite3_finalize(stmt
);
508 bool authdb_maintenance(authdb_connection_t dbconn
)
510 os_log_debug(AUTHD_LOG
, "authdb: starting maintenance");
511 int32_t rc
= SQLITE_ERROR
;
512 auth_items_t config
= NULL
;
514 bool isCorrupted
= _db_check_corrupted(dbconn
);
515 os_log_debug(AUTHD_LOG
, "authdb: integrity check=%{public}s", isCorrupted
? "fail" : "pass");
518 _handle_corrupt_db(dbconn
);
521 if (dbconn
->handle
== NULL
) {
522 dbconn
->handle
= _create_handle(dbconn
->db
);
525 require_action(dbconn
->handle
, done
, os_log_error(AUTHD_LOG
, "authdb: maintenance cannot open database"));
527 _db_maintenance(dbconn
);
529 rc
= authdb_get_key_value(dbconn
, "config", true, &config
);
530 require_noerr_action(rc
, done
, os_log_debug(AUTHD_LOG
, "authdb: maintenance failed %i", rc
));
532 _db_load_data(dbconn
, config
);
535 CFReleaseSafe(config
);
536 os_log_debug(AUTHD_LOG
, "authdb: finished maintenance");
537 return rc
== SQLITE_OK
;
541 authdb_exec(authdb_connection_t dbconn
, const char * query
)
543 int32_t rc
= SQLITE_ERROR
;
544 require(query
!= NULL
, done
);
546 rc
= _sqlite3_exec(dbconn
->handle
, query
);
547 _checkResult(dbconn
, rc
, __FUNCTION__
, NULL
, false);
553 static int32_t _prepare(authdb_connection_t dbconn
, const char * sql
, const bool skip_maintenance
, sqlite3_stmt
** out_stmt
)
556 sqlite3_stmt
* stmt
= NULL
;
558 require_action(sql
!= NULL
, done
, rc
= SQLITE_ERROR
);
559 require_action(out_stmt
!= NULL
, done
, rc
= SQLITE_ERROR
);
561 rc
= sqlite3_prepare_v2(dbconn
->handle
, sql
, -1, &stmt
, NULL
);
562 require_noerr_action(rc
, done
, os_log_debug(AUTHD_LOG
, "authdb: prepare (%i) %{public}s", rc
, sqlite3_errmsg(dbconn
->handle
)));
567 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
, skip_maintenance
);
571 static void _parseItemsAtIndex(sqlite3_stmt
* stmt
, int32_t col
, auth_items_t items
, const char * key
)
573 switch (sqlite3_column_type(stmt
, col
)) {
575 auth_items_set_double(items
, key
, sqlite3_column_double(stmt
, col
));
578 auth_items_set_int64(items
, key
, sqlite3_column_int64(stmt
, col
));
581 auth_items_set_data(items
,
583 sqlite3_column_blob(stmt
, col
),
584 (size_t)sqlite3_column_bytes(stmt
, col
));
590 auth_items_set_string(items
, key
, (const char *)sqlite3_column_text(stmt
, col
));
594 // LOGD("authdb: col=%s, val=%s, type=%i", sqlite3_column_name(stmt, col), sqlite3_column_text(stmt, col), sqlite3_column_type(stmt,col));
597 static int32_t _bindItemsAtIndex(sqlite3_stmt
* stmt
, int col
, auth_items_t items
, const char * key
)
600 switch (auth_items_get_type(items
, key
)) {
602 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_int(items
, key
));
605 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_uint(items
, key
));
608 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_int64(items
, key
));
611 rc
= sqlite3_bind_int64(stmt
, col
, (int64_t)auth_items_get_uint64(items
, key
));
614 rc
= sqlite3_bind_double(stmt
, col
, auth_items_get_double(items
, key
));
617 rc
= sqlite3_bind_int64(stmt
, col
, auth_items_get_bool(items
, key
));
622 const void * blob
= auth_items_get_data(items
, key
, &blobLen
);
623 rc
= sqlite3_bind_blob(stmt
, col
, blob
, (int32_t)blobLen
, NULL
);
627 rc
= sqlite3_bind_text(stmt
, col
, auth_items_get_string(items
, key
), -1, NULL
);
630 rc
= sqlite3_bind_null(stmt
, col
);
633 if (rc
!= SQLITE_OK
) {
634 os_log_debug(AUTHD_LOG
, "authdb: auth_items bind failed (%i)", rc
);
639 int32_t authdb_get_key_value(authdb_connection_t dbconn
, const char * table
, const bool skip_maintenance
, auth_items_t
* out_items
)
641 int32_t rc
= SQLITE_ERROR
;
643 sqlite3_stmt
* stmt
= NULL
;
644 auth_items_t items
= NULL
;
646 require(table
!= NULL
, done
);
647 require(out_items
!= NULL
, done
);
649 asprintf(&query
, "SELECT * FROM %s", table
);
651 rc
= _prepare(dbconn
, query
, skip_maintenance
, &stmt
);
652 require_noerr(rc
, done
);
654 items
= auth_items_create();
655 while ((rc
= sqlite3_step(stmt
)) != SQLITE_DONE
) {
658 _parseItemsAtIndex(stmt
, 1, items
, (const char*)sqlite3_column_text(stmt
, 0));
661 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
, skip_maintenance
);
663 sleep(AUTHDB_BUSY_DELAY
);
665 require_noerr_action(rc
, done
, os_log_debug(AUTHD_LOG
, "authdb: get_key_value (%i) %{public}s", rc
, sqlite3_errmsg(dbconn
->handle
)));
676 CFReleaseSafe(items
);
678 sqlite3_finalize(stmt
);
682 int32_t authdb_set_key_value(authdb_connection_t dbconn
, const char * table
, auth_items_t items
)
684 __block
int32_t rc
= SQLITE_ERROR
;
686 sqlite3_stmt
* stmt
= NULL
;
688 require(table
!= NULL
, done
);
689 require(items
!= NULL
, done
);
691 asprintf(&query
, "INSERT OR REPLACE INTO %s VALUES (?,?)", table
);
693 rc
= _prepare(dbconn
, query
, false, &stmt
);
694 require_noerr(rc
, done
);
696 auth_items_iterate(items
, ^bool(const char *key
) {
698 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
, false);
700 sqlite3_bind_text(stmt
, 1, key
, -1, NULL
);
701 _bindItemsAtIndex(stmt
, 2, items
, key
);
703 rc
= sqlite3_step(stmt
);
704 if (rc
!= SQLITE_DONE
) {
705 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
, false);
706 os_log_debug(AUTHD_LOG
, "authdb: set_key_value, step (%i) %{public}s", rc
, sqlite3_errmsg(dbconn
->handle
));
714 sqlite3_finalize(stmt
);
718 static int32_t _begin_transaction_type(authdb_connection_t dbconn
, AuthDBTransactionType type
)
720 int32_t result
= SQLITE_ERROR
;
722 const char * query
= NULL
;
724 case AuthDBTransactionImmediate
:
725 query
= "BEGIN IMMEDIATE;";
727 case AuthDBTransactionExclusive
:
728 query
= "BEGIN EXCLUSIVE;";
730 case AuthDBTransactionNormal
:
739 if (query
!= NULL
&& sqlite3_get_autocommit(dbconn
->handle
) != 0) {
740 result
= _sqlite3_exec(dbconn
->handle
, query
);
746 static int32_t _end_transaction(authdb_connection_t dbconn
, bool commit
)
749 return _sqlite3_exec(dbconn
->handle
, "END;");
751 return _sqlite3_exec(dbconn
->handle
, "ROLLBACK;");
755 bool authdb_transaction(authdb_connection_t dbconn
, AuthDBTransactionType type
, bool (^t
)(void))
757 int32_t result
= SQLITE_ERROR
;
760 result
= _begin_transaction_type(dbconn
, type
);
761 require_action(result
== SQLITE_OK
, done
, os_log_debug(AUTHD_LOG
, "authdb: transaction begin failed %i", result
));
765 result
= _end_transaction(dbconn
, commit
);
766 require_action(result
== SQLITE_OK
, done
, commit
= false; os_log_debug(AUTHD_LOG
, "authdb: transaction end failed %i", result
));
772 bool authdb_step(authdb_connection_t dbconn
, const char * sql
, void (^bind_stmt
)(sqlite3_stmt
*), authdb_iterator_t iter
)
775 sqlite3_stmt
* stmt
= NULL
;
776 int32_t rc
= SQLITE_ERROR
;
778 require_action(sql
!= NULL
, done
, rc
= SQLITE_ERROR
);
780 rc
= _prepare(dbconn
, sql
, false, &stmt
);
781 require_noerr(rc
, done
);
787 int32_t count
= sqlite3_column_count(stmt
);
789 auth_items_t items
= NULL
;
790 while ((rc
= sqlite3_step(stmt
)) != SQLITE_DONE
) {
795 items
= auth_items_create();
796 for (int i
= 0; i
< count
; i
++) {
797 _parseItemsAtIndex(stmt
, i
, items
, sqlite3_column_name(stmt
, i
));
799 result
= iter(items
);
800 CFReleaseNull(items
);
809 os_log_debug(AUTHD_LOG
, "authdb: %{public}s", sqlite3_errmsg(dbconn
->handle
));
810 sleep(AUTHDB_BUSY_DELAY
);
813 require_noerr_action(rc
, done
, os_log_debug(AUTHD_LOG
, "authdb: step (%i) %{public}s", rc
, sqlite3_errmsg(dbconn
->handle
)));
820 _checkResult(dbconn
, rc
, __FUNCTION__
, stmt
, false);
821 sqlite3_finalize(stmt
);
822 return rc
== SQLITE_DONE
;
825 void authdb_checkpoint(authdb_connection_t dbconn
)
827 int32_t rc
= sqlite3_wal_checkpoint(dbconn
->handle
, NULL
);
828 if (rc
!= SQLITE_OK
) {
829 os_log_debug(AUTHD_LOG
, "authdb: checkpoit failed %i", rc
);
833 static CFMutableArrayRef
834 _copy_rules_dict(RuleType type
, CFDictionaryRef plist
, authdb_connection_t dbconn
)
836 CFMutableArrayRef result
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
837 require(result
!= NULL
, done
);
839 _cf_dictionary_iterate(plist
, ^bool(CFTypeRef key
, CFTypeRef value
) {
840 if (CFGetTypeID(key
) != CFStringGetTypeID()) {
844 if (CFGetTypeID(value
) != CFDictionaryGetTypeID()) {
848 rule_t rule
= rule_create_with_plist(type
, key
, value
, dbconn
);
850 CFArrayAppendValue(result
, rule
);
862 _import_rules(authdb_connection_t dbconn
, CFMutableArrayRef rules
, bool version_check
, CFAbsoluteTime now
)
864 CFMutableArrayRef notcommited
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
865 CFIndex count
= CFArrayGetCount(rules
);
867 for (CFIndex i
= 0; i
< count
; i
++) {
868 rule_t rule
= (rule_t
)CFArrayGetValueAtIndex(rules
, i
);
872 if (rule_get_id(rule
) != 0) { // rule already exists see if we need to update
873 rule_t current
= rule_create_with_string(rule_get_name(rule
), dbconn
);
874 if (rule_get_version(rule
) > rule_get_version(current
)) {
877 CFReleaseSafe(current
);
885 __block
bool delayCommit
= false;
887 switch (rule_get_type(rule
)) {
889 rule_delegates_iterator(rule
, ^bool(rule_t delegate
) {
890 if (rule_get_id(delegate
) == 0) {
891 // fetch the rule from the database if it was previously committed
892 rule_sql_fetch(delegate
, dbconn
);
894 if (rule_get_id(delegate
) == 0) {
895 os_log_debug(AUTHD_LOG
, "authdb: delaying %{public}s waiting for delegate %{public}s", rule_get_name(rule
), rule_get_name(delegate
));
907 bool success
= rule_sql_commit(rule
, dbconn
, now
, NULL
);
908 os_log_debug(AUTHD_LOG
, "authdb: %{public}s %{public}s %{public}s %{public}s",
909 update
? "updating" : "importing",
910 rule_get_type(rule
) == RT_RULE
? "rule" : "right",
911 rule_get_name(rule
), success
? "success" : "FAIL");
913 CFArrayAppendValue(notcommited
, rule
);
916 CFArrayAppendValue(notcommited
, rule
);
919 CFArrayRemoveAllValues(rules
);
920 CFArrayAppendArray(rules
, notcommited
, CFRangeMake(0, CFArrayGetCount(notcommited
)));
921 CFReleaseSafe(notcommited
);
925 authdb_import_plist(authdb_connection_t dbconn
, CFDictionaryRef plist
, bool version_check
)
929 os_log_debug(AUTHD_LOG
, "authdb: starting import");
931 CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
932 CFMutableArrayRef rights
= NULL
;
933 CFMutableArrayRef rules
= NULL
;
934 require(plist
!= NULL
, done
);
936 CFTypeRef rightsDict
= CFDictionaryGetValue(plist
, CFSTR("rights"));
937 if (rightsDict
&& CFGetTypeID(rightsDict
) == CFDictionaryGetTypeID()) {
938 rights
= _copy_rules_dict(RT_RIGHT
, rightsDict
, dbconn
);
941 CFTypeRef rulesDict
= CFDictionaryGetValue(plist
, CFSTR("rules"));
942 if (rulesDict
&& CFGetTypeID(rulesDict
) == CFDictionaryGetTypeID()) {
943 rules
= _copy_rules_dict(RT_RULE
, rulesDict
, dbconn
);
946 os_log_debug(AUTHD_LOG
, "authdb: rights = %li", CFArrayGetCount(rights
));
947 os_log_debug(AUTHD_LOG
, "authdb: rules = %li", CFArrayGetCount(rules
));
950 // first pass import base rules without delegations
951 // remaining import rules that delegate to other rules
952 // loop upto 3 times to commit dependent rules first
953 for (int32_t j
= 0; j
< 3; j
++) {
954 count
= CFArrayGetCount(rules
);
958 _import_rules(dbconn
, rules
, version_check
, now
);
961 _import_rules(dbconn
, rights
, version_check
, now
);
963 if (CFArrayGetCount(rights
) == 0) {
967 authdb_checkpoint(dbconn
);
970 CFReleaseSafe(rights
);
971 CFReleaseSafe(rules
);
973 os_log_debug(AUTHD_LOG
, "authdb: finished import, %{public}s", result
? "succeeded" : "failed");
979 #pragma mark authdb_connection_t
981 static bool _sql_profile_enabled(void)
983 static bool profile_enabled
= false;
986 static dispatch_once_t onceToken
;
988 //sudo defaults write /Library/Preferences/com.apple.security.auth profile -bool true
989 dispatch_once(&onceToken
, ^{
990 CFTypeRef profile
= (CFNumberRef
)CFPreferencesCopyValue(CFSTR("profile"), CFSTR(SECURITY_AUTH_NAME
), kCFPreferencesAnyUser
, kCFPreferencesCurrentHost
);
992 if (profile
&& CFGetTypeID(profile
) == CFBooleanGetTypeID()) {
993 profile_enabled
= CFBooleanGetValue((CFBooleanRef
)profile
);
996 os_log_debug(AUTHD_LOG
, "authdb: sql profile: %{public}s", profile_enabled
? "enabled" : "disabled");
998 CFReleaseSafe(profile
);
1002 return profile_enabled
;
1005 static void _profile(void *context AUTH_UNUSED
, const char *sql
, sqlite3_uint64 ns
) {
1006 os_log_debug(AUTHD_LOG
, "==\nauthdb: %{private}s\nTime: %llu ms\n", sql
, ns
>> 20);
1009 static sqlite3
* _create_handle(authdb_t db
)
1011 bool dbcreated
= false;
1012 sqlite3
* handle
= NULL
;
1013 int32_t rc
= sqlite3_open_v2(db
->db_path
, &handle
, SQLITE_OPEN_READWRITE
, NULL
);
1015 if (rc
!= SQLITE_OK
) {
1016 os_log_error(AUTHD_LOG
, "authdb: open %{public}s (%i) %{public}s", db
->db_path
, rc
, handle
? sqlite3_errmsg(handle
) : "no memory for handle");
1018 sqlite3_close(handle
);
1020 char * tmp
= dirname(db
->db_path
);
1022 mkpath_np(tmp
, 0700);
1024 rc
= sqlite3_open_v2(db
->db_path
, &handle
, SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
, NULL
);
1027 if (rc
!= SQLITE_OK
) {
1028 os_log_error(AUTHD_LOG
, "authdb: create %{public}s (%i) %{public}s", db
->db_path
, rc
, handle
? sqlite3_errmsg(handle
) : "no memory for handle");
1030 sqlite3_close(handle
);
1037 if (_sql_profile_enabled()) {
1038 sqlite3_profile(handle
, _profile
, NULL
);
1041 _sqlite3_exec(handle
, "PRAGMA foreign_keys = ON");
1042 _sqlite3_exec(handle
, "PRAGMA temp_store = MEMORY");
1045 _sqlite3_exec(handle
, "PRAGMA auto_vacuum = FULL");
1046 _sqlite3_exec(handle
, "PRAGMA journal_mode = WAL");
1049 sqlite3_file_control(handle
, 0, SQLITE_FCNTL_PERSIST_WAL
, &on
);
1051 chmod(db
->db_path
, S_IRUSR
| S_IWUSR
);
1059 _authdb_connection_finalize(CFTypeRef value
)
1061 authdb_connection_t dbconn
= (authdb_connection_t
)value
;
1063 if (dbconn
->handle
) {
1064 sqlite3_close(dbconn
->handle
);
1066 CFReleaseNull(dbconn
->db
);
1069 AUTH_TYPE_INSTANCE(authdb_connection
,
1072 .finalize
= _authdb_connection_finalize
,
1075 .copyFormattingDesc
= NULL
,
1076 .copyDebugDesc
= NULL
1079 static CFTypeID
authdb_connection_get_type_id() {
1080 static CFTypeID type_id
= _kCFRuntimeNotATypeID
;
1081 static dispatch_once_t onceToken
;
1083 dispatch_once(&onceToken
, ^{
1084 type_id
= _CFRuntimeRegisterClass(&_auth_type_authdb_connection
);
1091 authdb_connection_create(authdb_t db
)
1093 authdb_connection_t dbconn
= NULL
;
1095 dbconn
= (authdb_connection_t
)_CFRuntimeCreateInstance(kCFAllocatorDefault
, authdb_connection_get_type_id(), AUTH_CLASS_SIZE(authdb_connection
), NULL
);
1096 require(dbconn
!= NULL
, done
);
1098 dbconn
->db
= (authdb_t
)CFRetain(db
);
1099 dbconn
->handle
= _create_handle(dbconn
->db
);