cpuworker.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. debug(LD_OR,"onion was from %s:%d, circ_id %d.", addrbuf, *port, *circ_id);
  77. }
  78. /** Called when the onion key has changed and we need to spawn new
  79. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  80. * rotation time as now.
  81. */
  82. void
  83. cpuworkers_rotate(void)
  84. {
  85. connection_t *cpuworker;
  86. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  87. CPUWORKER_STATE_IDLE))) {
  88. connection_mark_for_close(cpuworker);
  89. --num_cpuworkers;
  90. }
  91. last_rotation_time = time(NULL);
  92. if (server_mode(get_options()))
  93. spawn_enough_cpuworkers();
  94. }
  95. /** If the cpuworker closes the connection,
  96. * mark it as closed and spawn a new one as needed. */
  97. int
  98. connection_cpu_reached_eof(connection_t *conn)
  99. {
  100. warn(LD_GENERAL,"Read eof. Worker died unexpectedly.");
  101. if (conn->state != CPUWORKER_STATE_IDLE) {
  102. /* the circ associated with this cpuworker will have to wait until
  103. * it gets culled in run_connection_housekeeping(), since we have
  104. * no way to find out which circ it was. */
  105. warn(LD_GENERAL,"...and it left a circuit queued; abandoning circ.");
  106. num_cpuworkers_busy--;
  107. }
  108. num_cpuworkers--;
  109. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up
  110. spinning. */
  111. connection_mark_for_close(conn);
  112. return 0;
  113. }
  114. /** Called when we get data from a cpuworker. If the answer is not complete,
  115. * wait for a complete answer. If the answer is complete,
  116. * process it as appropriate.
  117. */
  118. int
  119. connection_cpu_process_inbuf(connection_t *conn)
  120. {
  121. char success;
  122. char buf[LEN_ONION_RESPONSE];
  123. uint32_t addr;
  124. uint16_t port;
  125. uint16_t circ_id;
  126. connection_t *p_conn;
  127. circuit_t *circ;
  128. tor_assert(conn);
  129. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  130. if (!buf_datalen(conn->inbuf))
  131. return 0;
  132. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  133. if (buf_datalen(conn->inbuf) < LEN_ONION_RESPONSE) /* answer available? */
  134. return 0; /* not yet */
  135. tor_assert(buf_datalen(conn->inbuf) == LEN_ONION_RESPONSE);
  136. connection_fetch_from_buf(&success,1,conn);
  137. connection_fetch_from_buf(buf,LEN_ONION_RESPONSE-1,conn);
  138. /* parse out the circ it was talking about */
  139. tag_unpack(buf, &addr, &port, &circ_id);
  140. circ = NULL;
  141. /* (Here we use connection_or_exact_get_by_addr_port rather than
  142. * get_by_identity_digest: we want a specific port here in
  143. * case there are multiple connections.) */
  144. p_conn = connection_or_exact_get_by_addr_port(addr,port);
  145. if (p_conn)
  146. circ = circuit_get_by_circid_orconn(circ_id, p_conn);
  147. if (success == 0) {
  148. debug(LD_OR,
  149. "decoding onionskin failed. (Old key or bad software.) Closing.");
  150. if (circ)
  151. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  152. goto done_processing;
  153. }
  154. if (!circ) {
  155. /* This happens because somebody sends us a destroy cell and the
  156. * circuit goes away, while the cpuworker is working. This is also
  157. * why our tag doesn't include a pointer to the circ, because we'd
  158. * never know if it's still valid.
  159. */
  160. debug(LD_OR,"processed onion for a circ that's gone. Dropping.");
  161. goto done_processing;
  162. }
  163. tor_assert(circ->p_conn);
  164. if (onionskin_answer(circ, CELL_CREATED, buf+TAG_LEN,
  165. buf+TAG_LEN+ONIONSKIN_REPLY_LEN) < 0) {
  166. warn(LD_OR,"onionskin_answer failed. Closing.");
  167. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  168. goto done_processing;
  169. }
  170. debug(LD_OR,"onionskin_answer succeeded. Yay.");
  171. } else {
  172. tor_assert(0); /* don't ask me to do handshakes yet */
  173. }
  174. done_processing:
  175. conn->state = CPUWORKER_STATE_IDLE;
  176. num_cpuworkers_busy--;
  177. if (conn->timestamp_created < last_rotation_time) {
  178. connection_mark_for_close(conn);
  179. num_cpuworkers--;
  180. spawn_enough_cpuworkers();
  181. } else {
  182. process_pending_task(conn);
  183. }
  184. return 0;
  185. }
  186. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  187. * Read and writes from fdarray[1]. Reads requests, writes answers.
  188. *
  189. * Request format:
  190. * Task type [1 byte, always CPUWORKER_TASK_ONION]
  191. * Opaque tag TAG_LEN
  192. * Onionskin challenge ONIONSKIN_CHALLENGE_LEN
  193. * Response format:
  194. * Success/failure [1 byte, boolean.]
  195. * Opaque tag TAG_LEN
  196. * Onionskin challenge ONIONSKIN_REPLY_LEN
  197. * Negotiated keys KEY_LEN*2+DIGEST_LEN*2
  198. *
  199. * (Note: this _should_ be by addr/port, since we're concerned with specific
  200. * connections, not with routers (where we'd use identity).)
  201. */
  202. static int
  203. cpuworker_main(void *data)
  204. {
  205. char question[ONIONSKIN_CHALLENGE_LEN];
  206. uint8_t question_type;
  207. int *fdarray = data;
  208. int fd;
  209. /* variables for onion processing */
  210. char keys[CPATH_KEY_MATERIAL_LEN];
  211. char reply_to_proxy[ONIONSKIN_REPLY_LEN];
  212. char buf[LEN_ONION_RESPONSE];
  213. char tag[TAG_LEN];
  214. crypto_pk_env_t *onion_key = NULL, *last_onion_key = NULL;
  215. fd = fdarray[1]; /* this side is ours */
  216. #ifndef TOR_IS_MULTITHREADED
  217. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  218. * parent uses */
  219. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  220. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  221. #endif
  222. tor_free(data);
  223. dup_onion_keys(&onion_key, &last_onion_key);
  224. for (;;) {
  225. int r;
  226. if ((r = recv(fd, &question_type, 1, 0)) != 1) {
  227. // log_fn(LOG_ERR,"read type failed. Exiting.");
  228. if (r == 0) {
  229. info(LD_OR,"CPU worker exiting because Tor process closed connection "
  230. "(either rotated keys or died).");
  231. } else {
  232. info(LD_OR,"CPU worker editing because of error on connection to Tor "
  233. "process.");
  234. info(LD_OR,"(Error on %d was %s)",
  235. fd, tor_socket_strerror(tor_socket_errno(fd)));
  236. }
  237. goto end;
  238. }
  239. tor_assert(question_type == CPUWORKER_TASK_ONION);
  240. if (read_all(fd, tag, TAG_LEN, 1) != TAG_LEN) {
  241. err(LD_BUG,"read tag failed. Exiting.");
  242. goto end;
  243. }
  244. if (read_all(fd, question, ONIONSKIN_CHALLENGE_LEN, 1) !=
  245. ONIONSKIN_CHALLENGE_LEN) {
  246. err(LD_BUG,"read question failed. Exiting.");
  247. goto end;
  248. }
  249. if (question_type == CPUWORKER_TASK_ONION) {
  250. if (onion_skin_server_handshake(question, onion_key, last_onion_key,
  251. reply_to_proxy, keys, CPATH_KEY_MATERIAL_LEN) < 0) {
  252. /* failure */
  253. debug(LD_OR,"onion_skin_server_handshake failed.");
  254. memset(buf,0,LEN_ONION_RESPONSE); /* send all zeros for failure */
  255. } else {
  256. /* success */
  257. debug(LD_OR,"onion_skin_server_handshake succeeded.");
  258. buf[0] = 1; /* 1 means success */
  259. memcpy(buf+1,tag,TAG_LEN);
  260. memcpy(buf+1+TAG_LEN,reply_to_proxy,ONIONSKIN_REPLY_LEN);
  261. memcpy(buf+1+TAG_LEN+ONIONSKIN_REPLY_LEN,keys,CPATH_KEY_MATERIAL_LEN);
  262. }
  263. if (write_all(fd, buf, LEN_ONION_RESPONSE, 1) != LEN_ONION_RESPONSE) {
  264. err(LD_BUG,"writing response buf failed. Exiting.");
  265. goto end;
  266. }
  267. debug(LD_OR,"finished writing response.");
  268. }
  269. }
  270. end:
  271. if (onion_key)
  272. crypto_free_pk_env(onion_key);
  273. if (last_onion_key)
  274. crypto_free_pk_env(last_onion_key);
  275. tor_close_socket(fd);
  276. crypto_thread_cleanup();
  277. spawn_exit();
  278. return 0; /* windows wants this function to return an int */
  279. }
  280. /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
  281. */
  282. static int
  283. spawn_cpuworker(void)
  284. {
  285. int *fdarray;
  286. int fd;
  287. connection_t *conn;
  288. int err;
  289. fdarray = tor_malloc(sizeof(int)*2);
  290. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  291. warn(LD_NET, "Couldn't construct socketpair: %s",
  292. tor_socket_strerror(-err));
  293. tor_free(fdarray);
  294. return -1;
  295. }
  296. fd = fdarray[0];
  297. spawn_func(cpuworker_main, (void*)fdarray);
  298. debug(LD_OR,"just spawned a cpu worker.");
  299. #ifndef TOR_IS_MULTITHREADED
  300. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  301. tor_free(fdarray);
  302. #endif
  303. conn = connection_new(CONN_TYPE_CPUWORKER);
  304. set_socket_nonblocking(fd);
  305. /* set up conn so it's got all the data we need to remember */
  306. conn->s = fd;
  307. conn->address = tor_strdup("localhost");
  308. if (connection_add(conn) < 0) { /* no space, forget it */
  309. warn(LD_NET,"connection_add failed. Giving up.");
  310. connection_free(conn); /* this closes fd */
  311. return -1;
  312. }
  313. conn->state = CPUWORKER_STATE_IDLE;
  314. connection_start_reading(conn);
  315. return 0; /* success */
  316. }
  317. /** If we have too few or too many active cpuworkers, try to spawn new ones
  318. * or kill idle ones.
  319. */
  320. static void
  321. spawn_enough_cpuworkers(void)
  322. {
  323. int num_cpuworkers_needed = get_options()->NumCpus;
  324. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  325. num_cpuworkers_needed = MIN_CPUWORKERS;
  326. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  327. num_cpuworkers_needed = MAX_CPUWORKERS;
  328. while (num_cpuworkers < num_cpuworkers_needed) {
  329. if (spawn_cpuworker() < 0) {
  330. warn(LD_GENERAL,"Spawn failed. Will try again later.");
  331. return;
  332. }
  333. num_cpuworkers++;
  334. }
  335. }
  336. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  337. static void
  338. process_pending_task(connection_t *cpuworker)
  339. {
  340. circuit_t *circ;
  341. tor_assert(cpuworker);
  342. /* for now only process onion tasks */
  343. circ = onion_next_task();
  344. if (!circ)
  345. return;
  346. if (assign_to_cpuworker(cpuworker, CPUWORKER_TASK_ONION, circ) < 0)
  347. warn(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  348. }
  349. #define CPUWORKER_BUSY_TIMEOUT 3600 /* seconds */
  350. /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers
  351. * get stuck in the 'busy' state, even though the cpuworker process
  352. * thinks of itself as idle. I don't know why. But here's a workaround
  353. * to kill any cpuworker that's been busy for more than 3600 seconds. */
  354. static void
  355. cull_wedged_cpuworkers(void)
  356. {
  357. connection_t **carray;
  358. connection_t *conn;
  359. int n_conns, i;
  360. time_t now = time(NULL);
  361. get_connection_array(&carray, &n_conns);
  362. for (i = 0; i < n_conns; ++i) {
  363. conn = carray[i];
  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. notice(LD_BUG,
  369. "Bug: 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. /** If cpuworker 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
  378. * the pending onion list and return.
  379. * If question_type is CPUWORKER_TASK_ONION then task is a circ.
  380. * No other question_types are allowed.
  381. */
  382. int
  383. assign_to_cpuworker(connection_t *cpuworker, uint8_t question_type,
  384. void *task)
  385. {
  386. circuit_t *circ;
  387. char tag[TAG_LEN];
  388. tor_assert(question_type == CPUWORKER_TASK_ONION);
  389. cull_wedged_cpuworkers();
  390. spawn_enough_cpuworkers();
  391. if (question_type == CPUWORKER_TASK_ONION) {
  392. circ = task;
  393. tor_assert(circ->onionskin);
  394. if (num_cpuworkers_busy == num_cpuworkers) {
  395. debug(LD_OR,"No idle cpuworkers. Queuing.");
  396. if (onion_pending_add(circ) < 0)
  397. return -1;
  398. return 0;
  399. }
  400. if (!cpuworker)
  401. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  402. CPUWORKER_STATE_IDLE);
  403. tor_assert(cpuworker);
  404. if (!circ->p_conn) {
  405. info(LD_OR,"circ->p_conn gone. Failing circ.");
  406. return -1;
  407. }
  408. tag_pack(tag, circ->p_conn->addr, circ->p_conn->port, circ->p_circ_id);
  409. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  410. num_cpuworkers_busy++;
  411. connection_write_to_buf((char*)&question_type, 1, cpuworker);
  412. connection_write_to_buf(tag, sizeof(tag), cpuworker);
  413. connection_write_to_buf(circ->onionskin, ONIONSKIN_CHALLENGE_LEN,
  414. cpuworker);
  415. tor_free(circ->onionskin);
  416. }
  417. return 0;
  418. }