testing_common.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. extern const char tor_git_revision[];
  6. /* Ordinarily defined in tor_main.c; this bit is just here to provide one
  7. * since we're not linking to tor_main.c */
  8. const char tor_git_revision[] = "";
  9. /**
  10. * \file test_common.c
  11. * \brief Common pieces to implement unit tests.
  12. **/
  13. #include "orconfig.h"
  14. #include "or.h"
  15. #include "control.h"
  16. #include "config.h"
  17. #include "rephist.h"
  18. #include "backtrace.h"
  19. #include "test.h"
  20. #include <stdio.h>
  21. #ifdef HAVE_FCNTL_H
  22. #include <fcntl.h>
  23. #endif
  24. #ifdef _WIN32
  25. /* For mkdir() */
  26. #include <direct.h>
  27. #else
  28. #include <dirent.h>
  29. #endif
  30. #include "or.h"
  31. #ifdef USE_DMALLOC
  32. #include <dmalloc.h>
  33. #include <openssl/crypto.h>
  34. #include "main.h"
  35. #endif
  36. /** Temporary directory (set up by setup_directory) under which we store all
  37. * our files during testing. */
  38. static char temp_dir[256];
  39. #ifdef _WIN32
  40. #define pid_t int
  41. #endif
  42. static pid_t temp_dir_setup_in_pid = 0;
  43. /** Select and create the temporary directory we'll use to run our unit tests.
  44. * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
  45. * idempotent. */
  46. static void
  47. setup_directory(void)
  48. {
  49. static int is_setup = 0;
  50. int r;
  51. char rnd[256], rnd32[256];
  52. if (is_setup) return;
  53. /* Due to base32 limitation needs to be a multiple of 5. */
  54. #define RAND_PATH_BYTES 5
  55. crypto_rand(rnd, RAND_PATH_BYTES);
  56. base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
  57. #ifdef _WIN32
  58. {
  59. char buf[MAX_PATH];
  60. const char *tmp = buf;
  61. const char *extra_backslash = "";
  62. /* If this fails, we're probably screwed anyway */
  63. if (!GetTempPathA(sizeof(buf),buf))
  64. tmp = "c:\\windows\\temp\\";
  65. if (strcmpend(tmp, "\\")) {
  66. /* According to MSDN, it should be impossible for GetTempPath to give us
  67. * an answer that doesn't end with \. But let's make sure. */
  68. extra_backslash = "\\";
  69. }
  70. tor_snprintf(temp_dir, sizeof(temp_dir),
  71. "%s%stor_test_%d_%s", tmp, extra_backslash,
  72. (int)getpid(), rnd32);
  73. r = mkdir(temp_dir);
  74. }
  75. #else
  76. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s",
  77. (int) getpid(), rnd32);
  78. r = mkdir(temp_dir, 0700);
  79. if (!r) {
  80. /* undo sticky bit so tests don't get confused. */
  81. r = chown(temp_dir, getuid(), getgid());
  82. }
  83. #endif
  84. if (r) {
  85. fprintf(stderr, "Can't create directory %s:", temp_dir);
  86. perror("");
  87. exit(1);
  88. }
  89. is_setup = 1;
  90. temp_dir_setup_in_pid = getpid();
  91. }
  92. /** Return a filename relative to our testing temporary directory, based on
  93. * name and suffix. If name is NULL, return the name of the testing temporary
  94. * directory. */
  95. static const char *
  96. get_fname_suffix(const char *name, const char *suffix)
  97. {
  98. static char buf[1024];
  99. setup_directory();
  100. if (!name)
  101. return temp_dir;
  102. tor_snprintf(buf,sizeof(buf),"%s/%s%s%s",temp_dir,name,suffix ? "_" : "",
  103. suffix ? suffix : "");
  104. return buf;
  105. }
  106. /** Return a filename relative to our testing temporary directory. If name is
  107. * NULL, return the name of the testing temporary directory. */
  108. const char *
  109. get_fname(const char *name)
  110. {
  111. return get_fname_suffix(name, NULL);
  112. }
  113. /** Return a filename with a random suffix, relative to our testing temporary
  114. * directory. If name is NULL, return the name of the testing temporary
  115. * directory, without any suffix. */
  116. const char *
  117. get_fname_rnd(const char *name)
  118. {
  119. char rnd[256], rnd32[256];
  120. crypto_rand(rnd, RAND_PATH_BYTES);
  121. base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
  122. return get_fname_suffix(name, rnd32);
  123. }
  124. /* Remove a directory and all of its subdirectories */
  125. static void
  126. rm_rf(const char *dir)
  127. {
  128. struct stat st;
  129. smartlist_t *elements;
  130. elements = tor_listdir(dir);
  131. if (elements) {
  132. SMARTLIST_FOREACH_BEGIN(elements, const char *, cp) {
  133. char *tmp = NULL;
  134. tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
  135. if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
  136. rm_rf(tmp);
  137. } else {
  138. if (unlink(tmp)) {
  139. fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
  140. }
  141. }
  142. tor_free(tmp);
  143. } SMARTLIST_FOREACH_END(cp);
  144. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  145. smartlist_free(elements);
  146. }
  147. if (rmdir(dir))
  148. fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
  149. }
  150. /** Remove all files stored under the temporary directory, and the directory
  151. * itself. Called by atexit(). */
  152. static void
  153. remove_directory(void)
  154. {
  155. if (getpid() != temp_dir_setup_in_pid) {
  156. /* Only clean out the tempdir when the main process is exiting. */
  157. return;
  158. }
  159. rm_rf(temp_dir);
  160. }
  161. /** Define this if unit tests spend too much time generating public keys*/
  162. #define CACHE_GENERATED_KEYS
  163. #define N_PREGEN_KEYS 11
  164. static crypto_pk_t *pregen_keys[N_PREGEN_KEYS];
  165. static int next_key_idx;
  166. /** Generate and return a new keypair for use in unit tests. If we're using
  167. * the key cache optimization, we might reuse keys. "idx" is ignored.
  168. * Our only guarantee is that we won't reuse a key till this function has been
  169. * called several times. The order in which keys are returned is slightly
  170. * randomized, so that tests that depend on a particular order will not be
  171. * reliable. */
  172. crypto_pk_t *
  173. pk_generate(int idx)
  174. {
  175. (void) idx;
  176. #ifdef CACHE_GENERATED_KEYS
  177. /* Either skip 1 or 2 keys. */
  178. next_key_idx += crypto_rand_int_range(1,3);
  179. next_key_idx %= N_PREGEN_KEYS;
  180. return crypto_pk_dup_key(pregen_keys[next_key_idx]);
  181. #else
  182. crypto_pk_t *result;
  183. int res;
  184. result = crypto_pk_new();
  185. res = crypto_pk_generate_key__real(result);
  186. tor_assert(!res);
  187. return result;
  188. #endif
  189. }
  190. #ifdef CACHE_GENERATED_KEYS
  191. static int
  192. crypto_pk_generate_key_with_bits__get_cached(crypto_pk_t *env, int bits)
  193. {
  194. if (bits != 1024)
  195. return crypto_pk_generate_key_with_bits__real(env, bits);
  196. crypto_pk_t *newkey = pk_generate(0);
  197. crypto_pk_assign_(env, newkey);
  198. crypto_pk_free(newkey);
  199. return 0;
  200. }
  201. #endif
  202. /** Free all storage used for the cached key optimization. */
  203. static void
  204. free_pregenerated_keys(void)
  205. {
  206. unsigned idx;
  207. for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
  208. if (pregen_keys[idx]) {
  209. crypto_pk_free(pregen_keys[idx]);
  210. pregen_keys[idx] = NULL;
  211. }
  212. }
  213. }
  214. static void *
  215. passthrough_test_setup(const struct testcase_t *testcase)
  216. {
  217. /* Make sure the passthrough doesn't unintentionally fail or skip tests */
  218. tor_assert(testcase->setup_data);
  219. tor_assert(testcase->setup_data != (void*)TT_SKIP);
  220. return testcase->setup_data;
  221. }
  222. static int
  223. passthrough_test_cleanup(const struct testcase_t *testcase, void *ptr)
  224. {
  225. (void)testcase;
  226. (void)ptr;
  227. return 1;
  228. }
  229. static void *
  230. ed25519_testcase_setup(const struct testcase_t *testcase)
  231. {
  232. crypto_ed25519_testing_force_impl(testcase->setup_data);
  233. return testcase->setup_data;
  234. }
  235. static int
  236. ed25519_testcase_cleanup(const struct testcase_t *testcase, void *ptr)
  237. {
  238. (void)testcase;
  239. (void)ptr;
  240. crypto_ed25519_testing_restore_impl();
  241. return 1;
  242. }
  243. const struct testcase_setup_t ed25519_test_setup = {
  244. ed25519_testcase_setup, ed25519_testcase_cleanup
  245. };
  246. const struct testcase_setup_t passthrough_setup = {
  247. passthrough_test_setup, passthrough_test_cleanup
  248. };
  249. static void
  250. an_assertion_failed(void)
  251. {
  252. tinytest_set_test_failed_();
  253. }
  254. /** Main entry point for unit test code: parse the command line, and run
  255. * some unit tests. */
  256. int
  257. main(int c, const char **v)
  258. {
  259. or_options_t *options;
  260. char *errmsg = NULL;
  261. int i, i_out;
  262. int loglevel = LOG_ERR;
  263. int accel_crypto = 0;
  264. /* We must initialise logs before we call tor_assert() */
  265. init_logging(1);
  266. #ifdef USE_DMALLOC
  267. {
  268. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  269. tor_assert(r);
  270. }
  271. #endif
  272. update_approx_time(time(NULL));
  273. options = options_new();
  274. tor_threads_init();
  275. network_init();
  276. monotime_init();
  277. struct tor_libevent_cfg cfg;
  278. memset(&cfg, 0, sizeof(cfg));
  279. tor_libevent_initialize(&cfg);
  280. control_initialize_event_queue();
  281. configure_backtrace_handler(get_version());
  282. for (i_out = i = 1; i < c; ++i) {
  283. if (!strcmp(v[i], "--warn")) {
  284. loglevel = LOG_WARN;
  285. } else if (!strcmp(v[i], "--notice")) {
  286. loglevel = LOG_NOTICE;
  287. } else if (!strcmp(v[i], "--info")) {
  288. loglevel = LOG_INFO;
  289. } else if (!strcmp(v[i], "--debug")) {
  290. loglevel = LOG_DEBUG;
  291. } else if (!strcmp(v[i], "--accel")) {
  292. accel_crypto = 1;
  293. } else {
  294. v[i_out++] = v[i];
  295. }
  296. }
  297. c = i_out;
  298. {
  299. log_severity_list_t s;
  300. memset(&s, 0, sizeof(s));
  301. set_log_severity_config(loglevel, LOG_ERR, &s);
  302. /* ALWAYS log bug warnings. */
  303. s.masks[LOG_WARN-LOG_ERR] |= LD_BUG;
  304. add_stream_log(&s, "", fileno(stdout));
  305. }
  306. options->command = CMD_RUN_UNITTESTS;
  307. if (crypto_global_init(accel_crypto, NULL, NULL)) {
  308. printf("Can't initialize crypto subsystem; exiting.\n");
  309. return 1;
  310. }
  311. crypto_set_tls_dh_prime();
  312. if (crypto_seed_rng() < 0) {
  313. printf("Couldn't seed RNG; exiting.\n");
  314. return 1;
  315. }
  316. rep_hist_init();
  317. setup_directory();
  318. options_init(options);
  319. options->DataDirectory = tor_strdup(temp_dir);
  320. options->EntryStatistics = 1;
  321. if (set_options(options, &errmsg) < 0) {
  322. printf("Failed to set initial options: %s\n", errmsg);
  323. tor_free(errmsg);
  324. return 1;
  325. }
  326. tor_set_failed_assertion_callback(an_assertion_failed);
  327. #ifdef CACHE_GENERATED_KEYS
  328. for (i = 0; i < N_PREGEN_KEYS; ++i) {
  329. pregen_keys[i] = crypto_pk_new();
  330. int r = crypto_pk_generate_key(pregen_keys[i]);
  331. tor_assert(r == 0);
  332. }
  333. MOCK(crypto_pk_generate_key_with_bits,
  334. crypto_pk_generate_key_with_bits__get_cached);
  335. #endif
  336. atexit(remove_directory);
  337. int have_failed = (tinytest_main(c, v, testgroups) != 0);
  338. free_pregenerated_keys();
  339. #ifdef USE_DMALLOC
  340. tor_free_all(0);
  341. dmalloc_log_unfreed();
  342. #endif
  343. crypto_global_cleanup();
  344. if (have_failed)
  345. return 1;
  346. else
  347. return 0;
  348. }