2 * Copyright (c) 2005-2007,2009-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
27 * This is to fool os services to not provide the Keychain manager
28 * interface tht doens't work since we don't have unified headers
29 * between iOS and OS X. rdar://23405418/
31 #define __KEYCHAINCORE__ 1
34 #import <Foundation/Foundation.h>
40 #include <sys/types.h>
49 #include <utilities/debugging.h>
50 #include <utilities/SecCFRelease.h>
51 #include <utilities/SecCFWrappers.h>
52 #include <utilities/SecFileLocations.h>
54 #include <dispatch/dispatch.h>
56 #include "keychain/ckks/CKKS.h"
58 int test_strict_bats = 1;
60 int test_onebatstest = 0;
61 int test_check_leaks = 0;
64 #include "keychain/securityd/spi.h"
66 static int current_dir = -1;
67 static char scratch_dir[50];
68 static char *home_var;
71 rmdir_recursive(const char *path)
73 #if (!TARGET_OS_SIMULATOR)
74 char command_buf[256];
75 if (strlen(path) + 10 > sizeof(command_buf) || strchr(path, '\''))
77 fprintf(stdout, "# rmdir_recursive: invalid path: %s", path);
81 sprintf(command_buf, "/bin/rm -rf '%s'", path);
82 return system(command_buf);
84 fprintf(stdout, "# rmdir_recursive: simulator can't rmdir, leaving path: %s\n", path);
90 static int tests_init(void) {
98 NSString* pid = [NSString stringWithFormat: @"tst-%d", [[NSProcessInfo processInfo] processIdentifier]];
99 NSURL* tmpDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:pid];
101 ok = ok(tmpDirURL, "Got error setting up tmp dir: %@", error);
103 ok = ok && ok([[NSFileManager defaultManager] createDirectoryAtURL:tmpDirURL
104 withIntermediateDirectories:NO
107 "Failed to make %@: %@", tmpDirURL, error);
109 NSURL* libraryURL = [tmpDirURL URLByAppendingPathComponent:@"Library"];
110 NSURL* preferencesURL = [tmpDirURL URLByAppendingPathComponent:@"Preferences"];
112 ok = (ok && ok_unix(current_dir = open(".", O_RDONLY), "open")
113 && ok_unix(chdir([tmpDirURL fileSystemRepresentation]), "chdir")
114 && ok_unix(setenv("HOME", [tmpDirURL fileSystemRepresentation], 1), "setenv")
115 && ok(home_var = getenv("HOME"), "getenv"));
117 ok = ok && ok([[NSFileManager defaultManager] createDirectoryAtURL:libraryURL
118 withIntermediateDirectories:NO
121 "Failed to make %@: %@", libraryURL, error);
123 ok = ok && ok([[NSFileManager defaultManager] createDirectoryAtURL:preferencesURL
124 withIntermediateDirectories:NO
127 "Failed to make %@: %@", preferencesURL, error);
130 securityd_init((__bridge CFURLRef) tmpDirURL);
145 /* Restore previous cwd and remove scratch dir. */
146 ok_unix(fchdir(current_dir), "fchdir");
147 ok_unix(close(current_dir), "close");
148 ok_unix(rmdir_recursive(scratch_dir), "rmdir_recursive");
152 static void usage(const char *progname)
154 fprintf(stderr, "usage: %s [-w][testname [testargs] ...]\n", progname);
158 /* run one test, described by test, return info in test struct */
159 static int tests_run_test(struct one_test_s *test, int argc, char * const *argv)
163 while ((ch = getopt(argc, argv, "v")) != -1)
175 if (test_onebatstest)
176 fprintf(stdout, "[TEST] %s\n", test->name);
178 fprintf(stdout, "[BEGIN] %s\n", test->name);
180 const char *token = "PASS";
181 if (test->entry == NULL) {
182 fprintf(stdout, "%s:%d: error, no entry\n", __FILE__, __LINE__);
183 test->failed_tests = 1;
185 struct timeval start, stop;
186 gettimeofday(&start, NULL);
188 test->entry(argc, argv);
190 gettimeofday(&stop, NULL);
191 /* this may overflow... */
192 test->duration = (stop.tv_sec-start.tv_sec) * 1000 + (stop.tv_usec / 1000) - (start.tv_usec / 1000);
193 if (test_plan_ok()) {
199 * Check if we have any leaks, allow skipping test
202 if (test_check_leaks) {
206 asprintf(&cmd, "leaks %d >/dev/null", getpid());
212 fprintf(stdout, "leaks found in test %s\n", test->name);
217 test_plan_final(&test->failed_tests, &test->todo_pass_tests, &test->todo_tests,
218 &test->actual_tests, &test->planned_tests,
219 &test->plan_file, &test->plan_line);
221 // TODO Use ccperf timing and printing routines that use proper si scaling
222 fprintf(stdout, "%s took %lu ms\n", test->name, test->duration);
224 if (test->failed_tests) {
227 fprintf(stdout, "[%s] %s\n", token, test->name);
229 return test->failed_tests;
232 static int strcmp_under_is_dash(const char *s, const char *t) {
234 char a = *s++, b = *t++;
236 if (a != '_' || b != '-')
244 static int tests_named_index(const char *testcase)
248 for (i = 0; testlist[i].name; ++i) {
249 if (strcmp_under_is_dash(testlist[i].name, testcase) == 0) {
257 static int tests_run_all(int argc, char * const *argv)
259 int curroptind = optind;
263 for (i = 0; testlist[i].name; ++i) {
264 if(!testlist[i].off) {
266 failcount+=tests_run_test(&testlist[i], argc, argv);
276 tests_summary(const char *progname) {
277 int failed_tests = 0;
278 int todo_pass_tests = 0;
280 int actual_tests = 0;
281 int planned_tests = 0;
283 // First compute the totals to help decide if we need to print headers or not.
284 for (int i = 0; testlist[i].name; ++i) {
285 if (!testlist[i].off) {
286 failed_tests += testlist[i].failed_tests;
287 todo_pass_tests += testlist[i].todo_pass_tests;
288 todo_tests += testlist[i].todo_tests;
289 actual_tests += testlist[i].actual_tests;
290 planned_tests += testlist[i].planned_tests;
294 if (!test_onebatstest) {
295 fprintf(stdout, "[%s] %s\n", failed_tests ? "FAIL" : (actual_tests == planned_tests ? "PASS" : "WARN"), progname);
298 fprintf(stdout, "[SUMMARY]\n");
300 // -v -v makes the summary verbose as well.
301 fprintf(stdout, "Test name failed !failed todo total plan\n");
302 if (test_verbose > 1 || failed_tests || todo_pass_tests || actual_tests != planned_tests || (test_verbose && todo_tests)) {
303 fprintf(stdout, "============================================================================================\n");
305 for (int i = 0; testlist[i].name; ++i) {
306 if (!testlist[i].off) {
307 const char *token = NULL;
308 if (testlist[i].failed_tests) {
310 } else if (testlist[i].actual_tests != testlist[i].planned_tests) {
312 } else if (testlist[i].todo_pass_tests) {
314 } else if (test_verbose > 1 || (test_verbose && testlist[i].todo_tests)) {
318 fprintf(stdout, "[%s] %-50s %6d %6d %6d %6d %6d\n", token, testlist[i].name, testlist[i].failed_tests, testlist[i].todo_pass_tests, testlist[i].todo_tests, testlist[i].actual_tests, testlist[i].planned_tests);
322 if (test_verbose > 1 || failed_tests || todo_pass_tests || actual_tests != planned_tests || (test_verbose && todo_tests)) {
323 fprintf(stdout, "============================================================================================\n");
325 fprintf(stdout, "Totals %6d %6d %6d %6d %6d\n", failed_tests, todo_pass_tests, todo_tests, actual_tests, planned_tests);
329 #define ASYNC_LOGGING 0
330 #define DATE_LOGGING 0
333 tests_begin(int argc, char * const *argv) {
334 const char *testcase = NULL;
335 bool initialized = false;
336 __block bool print_security_logs = false;
344 dispatch_queue_t show_queue = dispatch_queue_create("sec log queue", DISPATCH_QUEUE_SERIAL);
349 security_log_handler handle_logs = ^(int level, CFStringRef scope, const char *function, const char *file, int line, CFStringRef message) {
350 time_t now = time(NULL);
353 char *date = ctime(&now);
355 CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
356 CFSTR("%s %@{} %s %@\n"), date + 4,
357 scope ? scope : CFSTR(""), function, message);
359 CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
360 CFSTR("%lu %@{} %s %@\n"), now,
361 scope ? scope : CFSTR(""), function, message);
364 dispatch_async(show_queue, ^{ CFShow(logStr); CFReleaseSafe(logStr); });
367 CFReleaseSafe(logStr);
374 while (!testcase && (ch = getopt(argc, argv, "blL1vwqs")) != -1)
379 if (!print_security_logs) {
380 //add_security_log_handler(handle_logs);
381 print_security_logs = true;
386 test_strict_bats = 0;
407 printf("invalid option %c\n",ch);
413 testix = tests_named_index(argv[optind]);
415 printf("invalid test %s\n",argv[optind]);
420 if(!print_security_logs) secLogDisable();
423 if (!list && !initialized && !test_onebatstest)
424 fprintf(stdout, "[TEST] %s\n", getprogname());
431 failcount+=tests_run_all(argc, argv);
438 for (int i = 0; testlist[i].name; ++i) {
443 testlist[testix].off = 0;
446 failcount+=tests_run_test(&testlist[testix], argc, argv);
453 for (int i = 0; testlist[i].name; ++i) {
454 if (!testlist[i].off) {
455 fprintf(stdout, "%s\n", testlist[i].name);
459 tests_summary(getprogname());
462 // remove_security_log_handler(handle_logs);
470 printf("Looping until key press 'q'. You can run leaks now.\n");
471 while(getchar()!='q');