cpuworker.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file cpuworker.c
  7. * \brief Implements a farm of 'CPU worker' processes to perform
  8. * CPU-intensive tasks in another thread or process, to not
  9. * interrupt the main thread.
  10. *
  11. * Right now, we only use this for processing onionskins.
  12. **/
  13. #include "or.h"
  14. #include "buffers.h"
  15. #include "circuitbuild.h"
  16. #include "circuitlist.h"
  17. #include "config.h"
  18. #include "connection.h"
  19. #include "cpuworker.h"
  20. #include "main.h"
  21. #include "onion.h"
  22. #include "router.h"
  23. /** The maximum number of cpuworker processes we will keep around. */
  24. #define MAX_CPUWORKERS 16
  25. /** The minimum number of cpuworker processes we will keep around. */
  26. #define MIN_CPUWORKERS 1
  27. /** The tag specifies which circuit this onionskin was from. */
  28. #define TAG_LEN 10
  29. /** How many bytes are sent from the cpuworker back to tor? */
  30. #define LEN_ONION_RESPONSE \
  31. (1+TAG_LEN+ONIONSKIN_REPLY_LEN+CPATH_KEY_MATERIAL_LEN)
  32. /** How many cpuworkers we have running right now. */
  33. static int num_cpuworkers=0;
  34. /** How many of the running cpuworkers have an assigned task right now. */
  35. static int num_cpuworkers_busy=0;
  36. /** We need to spawn new cpuworkers whenever we rotate the onion keys
  37. * on platforms where execution contexts==processes. This variable stores
  38. * the last time we got a key rotation event. */
  39. static time_t last_rotation_time=0;
  40. static void cpuworker_main(void *data) ATTR_NORETURN;
  41. static int spawn_cpuworker(void);
  42. static void spawn_enough_cpuworkers(void);
  43. static void process_pending_task(connection_t *cpuworker);
  44. /** Initialize the cpuworker subsystem.
  45. */
  46. void
  47. cpu_init(void)
  48. {
  49. cpuworkers_rotate();
  50. }
  51. /** Called when we're done sending a request to a cpuworker. */
  52. int
  53. connection_cpu_finished_flushing(connection_t *conn)
  54. {
  55. tor_assert(conn);
  56. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  57. return 0;
  58. }
  59. /** Pack global_id and circ_id; set *tag to the result. (See note on
  60. * cpuworker_main for wire format.) */
  61. static void
  62. tag_pack(char *tag, uint64_t conn_id, circid_t circ_id)
  63. {
  64. /*XXXX RETHINK THIS WHOLE MESS !!!! !NM NM NM NM*/
  65. set_uint64(tag, conn_id);
  66. set_uint16(tag+8, circ_id);
  67. }
  68. /** Unpack <b>tag</b> into addr, port, and circ_id.
  69. */
  70. static void
  71. tag_unpack(const char *tag, uint64_t *conn_id, circid_t *circ_id)
  72. {
  73. *conn_id = get_uint64(tag);
  74. *circ_id = get_uint16(tag+8);
  75. }
  76. /** Called when the onion key has changed and we need to spawn new
  77. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  78. * rotation time as now.
  79. */
  80. void
  81. cpuworkers_rotate(void)
  82. {
  83. connection_t *cpuworker;
  84. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  85. CPUWORKER_STATE_IDLE))) {
  86. connection_mark_for_close(cpuworker);
  87. --num_cpuworkers;
  88. }
  89. last_rotation_time = time(NULL);
  90. if (server_mode(get_options()))
  91. spawn_enough_cpuworkers();
  92. }
  93. /** If the cpuworker closes the connection,
  94. * mark it as closed and spawn a new one as needed. */
  95. int
  96. connection_cpu_reached_eof(connection_t *conn)
  97. {
  98. log_warn(LD_GENERAL,"Read eof. CPU worker died unexpectedly.");
  99. if (conn->state != CPUWORKER_STATE_IDLE) {
  100. /* the circ associated with this cpuworker will have to wait until
  101. * it gets culled in run_connection_housekeeping(), since we have
  102. * no way to find out which circ it was. */
  103. log_warn(LD_GENERAL,"...and it left a circuit queued; abandoning circ.");
  104. num_cpuworkers_busy--;
  105. }
  106. num_cpuworkers--;
  107. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up
  108. spinning. */
  109. connection_mark_for_close(conn);
  110. return 0;
  111. }
  112. /** Called when we get data from a cpuworker. If the answer is not complete,
  113. * wait for a complete answer. If the answer is complete,
  114. * process it as appropriate.
  115. */
  116. int
  117. connection_cpu_process_inbuf(connection_t *conn)
  118. {
  119. char success;
  120. char buf[LEN_ONION_RESPONSE];
  121. uint64_t conn_id;
  122. circid_t circ_id;
  123. connection_t *tmp_conn;
  124. or_connection_t *p_conn = NULL;
  125. circuit_t *circ;
  126. tor_assert(conn);
  127. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  128. if (!connection_get_inbuf_len(conn))
  129. return 0;
  130. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  131. if (connection_get_inbuf_len(conn) < LEN_ONION_RESPONSE)
  132. return 0; /* not yet */
  133. tor_assert(connection_get_inbuf_len(conn) == LEN_ONION_RESPONSE);
  134. connection_fetch_from_buf(&success,1,conn);
  135. connection_fetch_from_buf(buf,LEN_ONION_RESPONSE-1,conn);
  136. /* parse out the circ it was talking about */
  137. tag_unpack(buf, &conn_id, &circ_id);
  138. circ = NULL;
  139. tmp_conn = connection_get_by_global_id(conn_id);
  140. if (tmp_conn && !tmp_conn->marked_for_close &&
  141. tmp_conn->type == CONN_TYPE_OR)
  142. p_conn = TO_OR_CONN(tmp_conn);
  143. if (p_conn)
  144. circ = circuit_get_by_circid_orconn(circ_id, p_conn);
  145. if (success == 0) {
  146. log_debug(LD_OR,
  147. "decoding onionskin failed. "
  148. "(Old key or bad software.) Closing.");
  149. if (circ)
  150. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  151. goto done_processing;
  152. }
  153. if (!circ) {
  154. /* This happens because somebody sends us a destroy cell and the
  155. * circuit goes away, while the cpuworker is working. This is also
  156. * why our tag doesn't include a pointer to the circ, because we'd
  157. * never know if it's still valid.
  158. */
  159. log_debug(LD_OR,"processed onion for a circ that's gone. Dropping.");
  160. goto done_processing;
  161. }
  162. tor_assert(! CIRCUIT_IS_ORIGIN(circ));
  163. if (onionskin_answer(TO_OR_CIRCUIT(circ), CELL_CREATED, buf+TAG_LEN,
  164. buf+TAG_LEN+ONIONSKIN_REPLY_LEN) < 0) {
  165. log_warn(LD_OR,"onionskin_answer failed. Closing.");
  166. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  167. goto done_processing;
  168. }
  169. log_debug(LD_OR,"onionskin_answer succeeded. Yay.");
  170. } else {
  171. tor_assert(0); /* don't ask me to do handshakes yet */
  172. }
  173. done_processing:
  174. conn->state = CPUWORKER_STATE_IDLE;
  175. num_cpuworkers_busy--;
  176. if (conn->timestamp_created < last_rotation_time) {
  177. connection_mark_for_close(conn);
  178. num_cpuworkers--;
  179. spawn_enough_cpuworkers();
  180. } else {
  181. process_pending_task(conn);
  182. }
  183. return 0;
  184. }
  185. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  186. * Read and writes from fdarray[1]. Reads requests, writes answers.
  187. *
  188. * Request format:
  189. * Task type [1 byte, always CPUWORKER_TASK_ONION]
  190. * Opaque tag TAG_LEN
  191. * Onionskin challenge ONIONSKIN_CHALLENGE_LEN
  192. * Response format:
  193. * Success/failure [1 byte, boolean.]
  194. * Opaque tag TAG_LEN
  195. * Onionskin challenge ONIONSKIN_REPLY_LEN
  196. * Negotiated keys KEY_LEN*2+DIGEST_LEN*2
  197. *
  198. * (Note: this _should_ be by addr/port, since we're concerned with specific
  199. * connections, not with routers (where we'd use identity).)
  200. */
  201. static void
  202. cpuworker_main(void *data)
  203. {
  204. char question[ONIONSKIN_CHALLENGE_LEN];
  205. uint8_t question_type;
  206. tor_socket_t *fdarray = data;
  207. tor_socket_t fd;
  208. /* variables for onion processing */
  209. char keys[CPATH_KEY_MATERIAL_LEN];
  210. char reply_to_proxy[ONIONSKIN_REPLY_LEN];
  211. char buf[LEN_ONION_RESPONSE];
  212. char tag[TAG_LEN];
  213. crypto_pk_t *onion_key = NULL, *last_onion_key = NULL;
  214. fd = fdarray[1]; /* this side is ours */
  215. #ifndef TOR_IS_MULTITHREADED
  216. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  217. * parent uses */
  218. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  219. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  220. #endif
  221. tor_free(data);
  222. dup_onion_keys(&onion_key, &last_onion_key);
  223. for (;;) {
  224. ssize_t r;
  225. if ((r = recv(fd, (void *)&question_type, 1, 0)) != 1) {
  226. // log_fn(LOG_ERR,"read type failed. Exiting.");
  227. if (r == 0) {
  228. log_info(LD_OR,
  229. "CPU worker exiting because Tor process closed connection "
  230. "(either rotated keys or died).");
  231. } else {
  232. log_info(LD_OR,
  233. "CPU worker exiting because of error on connection to Tor "
  234. "process.");
  235. log_info(LD_OR,"(Error on %d was %s)",
  236. fd, tor_socket_strerror(tor_socket_errno(fd)));
  237. }
  238. goto end;
  239. }
  240. tor_assert(question_type == CPUWORKER_TASK_ONION);
  241. if (read_all(fd, tag, TAG_LEN, 1) != TAG_LEN) {
  242. log_err(LD_BUG,"read tag failed. Exiting.");
  243. goto end;
  244. }
  245. if (read_all(fd, question, ONIONSKIN_CHALLENGE_LEN, 1) !=
  246. ONIONSKIN_CHALLENGE_LEN) {
  247. log_err(LD_BUG,"read question failed. Exiting.");
  248. goto end;
  249. }
  250. if (question_type == CPUWORKER_TASK_ONION) {
  251. if (onion_skin_server_handshake(question, onion_key, last_onion_key,
  252. reply_to_proxy, keys, CPATH_KEY_MATERIAL_LEN) < 0) {
  253. /* failure */
  254. log_debug(LD_OR,"onion_skin_server_handshake failed.");
  255. *buf = 0; /* indicate failure in first byte */
  256. memcpy(buf+1,tag,TAG_LEN);
  257. /* send all zeros as answer */
  258. memset(buf+1+TAG_LEN, 0, LEN_ONION_RESPONSE-(1+TAG_LEN));
  259. } else {
  260. /* success */
  261. log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
  262. buf[0] = 1; /* 1 means success */
  263. memcpy(buf+1,tag,TAG_LEN);
  264. memcpy(buf+1+TAG_LEN,reply_to_proxy,ONIONSKIN_REPLY_LEN);
  265. memcpy(buf+1+TAG_LEN+ONIONSKIN_REPLY_LEN,keys,CPATH_KEY_MATERIAL_LEN);
  266. }
  267. if (write_all(fd, buf, LEN_ONION_RESPONSE, 1) != LEN_ONION_RESPONSE) {
  268. log_err(LD_BUG,"writing response buf failed. Exiting.");
  269. goto end;
  270. }
  271. log_debug(LD_OR,"finished writing response.");
  272. }
  273. }
  274. end:
  275. if (onion_key)
  276. crypto_pk_free(onion_key);
  277. if (last_onion_key)
  278. crypto_pk_free(last_onion_key);
  279. tor_close_socket(fd);
  280. crypto_thread_cleanup();
  281. spawn_exit();
  282. }
  283. /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
  284. */
  285. static int
  286. spawn_cpuworker(void)
  287. {
  288. tor_socket_t *fdarray;
  289. tor_socket_t fd;
  290. connection_t *conn;
  291. int err;
  292. fdarray = tor_malloc(sizeof(tor_socket_t)*2);
  293. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  294. log_warn(LD_NET, "Couldn't construct socketpair for cpuworker: %s",
  295. tor_socket_strerror(-err));
  296. tor_free(fdarray);
  297. return -1;
  298. }
  299. tor_assert(SOCKET_OK(fdarray[0]));
  300. tor_assert(SOCKET_OK(fdarray[1]));
  301. fd = fdarray[0];
  302. spawn_func(cpuworker_main, (void*)fdarray);
  303. log_debug(LD_OR,"just spawned a cpu worker.");
  304. #ifndef TOR_IS_MULTITHREADED
  305. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  306. tor_free(fdarray);
  307. #endif
  308. conn = connection_new(CONN_TYPE_CPUWORKER, AF_UNIX);
  309. set_socket_nonblocking(fd);
  310. /* set up conn so it's got all the data we need to remember */
  311. conn->s = fd;
  312. conn->address = tor_strdup("localhost");
  313. tor_addr_make_unspec(&conn->addr);
  314. if (connection_add(conn) < 0) { /* no space, forget it */
  315. log_warn(LD_NET,"connection_add for cpuworker failed. Giving up.");
  316. connection_free(conn); /* this closes fd */
  317. return -1;
  318. }
  319. conn->state = CPUWORKER_STATE_IDLE;
  320. connection_start_reading(conn);
  321. return 0; /* success */
  322. }
  323. /** If we have too few or too many active cpuworkers, try to spawn new ones
  324. * or kill idle ones.
  325. */
  326. static void
  327. spawn_enough_cpuworkers(void)
  328. {
  329. int num_cpuworkers_needed = get_num_cpus(get_options());
  330. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  331. num_cpuworkers_needed = MIN_CPUWORKERS;
  332. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  333. num_cpuworkers_needed = MAX_CPUWORKERS;
  334. while (num_cpuworkers < num_cpuworkers_needed) {
  335. if (spawn_cpuworker() < 0) {
  336. log_warn(LD_GENERAL,"Cpuworker spawn failed. Will try again later.");
  337. return;
  338. }
  339. num_cpuworkers++;
  340. }
  341. }
  342. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  343. static void
  344. process_pending_task(connection_t *cpuworker)
  345. {
  346. or_circuit_t *circ;
  347. char *onionskin = NULL;
  348. tor_assert(cpuworker);
  349. /* for now only process onion tasks */
  350. circ = onion_next_task(&onionskin);
  351. if (!circ)
  352. return;
  353. if (assign_onionskin_to_cpuworker(cpuworker, circ, onionskin))
  354. log_warn(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  355. }
  356. /** How long should we let a cpuworker stay busy before we give
  357. * up on it and decide that we have a bug or infinite loop?
  358. * This value is high because some servers with low memory/cpu
  359. * sometimes spend an hour or more swapping, and Tor starves. */
  360. #define CPUWORKER_BUSY_TIMEOUT (60*60*12)
  361. /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers get
  362. * stuck in the 'busy' state, even though the cpuworker process thinks of
  363. * itself as idle. I don't know why. But here's a workaround to kill any
  364. * cpuworker that's been busy for more than CPUWORKER_BUSY_TIMEOUT.
  365. */
  366. static void
  367. cull_wedged_cpuworkers(void)
  368. {
  369. time_t now = time(NULL);
  370. smartlist_t *conns = get_connection_array();
  371. SMARTLIST_FOREACH(conns, connection_t *, conn,
  372. {
  373. if (!conn->marked_for_close &&
  374. conn->type == CONN_TYPE_CPUWORKER &&
  375. conn->state == CPUWORKER_STATE_BUSY_ONION &&
  376. conn->timestamp_lastwritten + CPUWORKER_BUSY_TIMEOUT < now) {
  377. log_notice(LD_BUG,
  378. "closing wedged cpuworker. Can somebody find the bug?");
  379. num_cpuworkers_busy--;
  380. num_cpuworkers--;
  381. connection_mark_for_close(conn);
  382. }
  383. });
  384. }
  385. /** Try to tell a cpuworker to perform the public key operations necessary to
  386. * respond to <b>onionskin</b> for the circuit <b>circ</b>.
  387. *
  388. * If <b>cpuworker</b> is defined, assert that he's idle, and use him. Else,
  389. * look for an idle cpuworker and use him. If none idle, queue task onto the
  390. * pending onion list and return. Return 0 if we successfully assign the
  391. * task, or -1 on failure.
  392. */
  393. int
  394. assign_onionskin_to_cpuworker(connection_t *cpuworker,
  395. or_circuit_t *circ, char *onionskin)
  396. {
  397. char qbuf[1];
  398. char tag[TAG_LEN];
  399. time_t now = approx_time();
  400. static time_t last_culled_cpuworkers = 0;
  401. /* Checking for wedged cpuworkers requires a linear search over all
  402. * connections, so let's do it only once a minute.
  403. */
  404. #define CULL_CPUWORKERS_INTERVAL 60
  405. if (last_culled_cpuworkers + CULL_CPUWORKERS_INTERVAL <= now) {
  406. cull_wedged_cpuworkers();
  407. spawn_enough_cpuworkers();
  408. last_culled_cpuworkers = now;
  409. }
  410. if (1) {
  411. if (num_cpuworkers_busy == num_cpuworkers) {
  412. log_debug(LD_OR,"No idle cpuworkers. Queuing.");
  413. if (onion_pending_add(circ, onionskin) < 0) {
  414. tor_free(onionskin);
  415. return -1;
  416. }
  417. return 0;
  418. }
  419. if (!cpuworker)
  420. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  421. CPUWORKER_STATE_IDLE);
  422. tor_assert(cpuworker);
  423. if (!circ->p_conn) {
  424. log_info(LD_OR,"circ->p_conn gone. Failing circ.");
  425. tor_free(onionskin);
  426. return -1;
  427. }
  428. tag_pack(tag, circ->p_conn->_base.global_identifier,
  429. circ->p_circ_id);
  430. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  431. /* touch the lastwritten timestamp, since that's how we check to
  432. * see how long it's been since we asked the question, and sometimes
  433. * we check before the first call to connection_handle_write(). */
  434. cpuworker->timestamp_lastwritten = time(NULL);
  435. num_cpuworkers_busy++;
  436. qbuf[0] = CPUWORKER_TASK_ONION;
  437. connection_write_to_buf(qbuf, 1, cpuworker);
  438. connection_write_to_buf(tag, sizeof(tag), cpuworker);
  439. connection_write_to_buf(onionskin, ONIONSKIN_CHALLENGE_LEN, cpuworker);
  440. tor_free(onionskin);
  441. }
  442. return 0;
  443. }