cpuworker.c 15 KB

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