cpuworker.c 15 KB

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