cpuworker.c 15 KB

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