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 */
6 const char cpuworker_c_id
[] =
11 * \brief Implements a farm of 'CPU worker' processes to perform
12 * CPU-intensive tasks in another thread or process, to not
13 * interrupt the main thread.
15 * Right now, we only use this for processing onionskins.
20 /** The maximum number of cpuworker processes we will keep around. */
21 #define MAX_CPUWORKERS 16
22 /** The minimum number of cpuworker processes we will keep around. */
23 #define MIN_CPUWORKERS 1
25 /** The tag specifies which circuit this onionskin was from. */
27 /** How many bytes are sent from the cpuworker back to tor? */
28 #define LEN_ONION_RESPONSE \
29 (1+TAG_LEN+ONIONSKIN_REPLY_LEN+CPATH_KEY_MATERIAL_LEN)
31 /** How many cpuworkers we have running right now. */
32 static int num_cpuworkers
=0;
33 /** How many of the running cpuworkers have an assigned task right now. */
34 static int num_cpuworkers_busy
=0;
35 /** We need to spawn new cpuworkers whenever we rotate the onion keys
36 * on platforms where execution contexts==processes. This variable stores
37 * the last time we got a key rotation event. */
38 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
);
45 /** Initialize the cpuworker subsystem.
53 /** Called when we're done sending a request to a cpuworker. */
55 connection_cpu_finished_flushing(connection_t
*conn
)
58 tor_assert(conn
->type
== CONN_TYPE_CPUWORKER
);
59 connection_stop_writing(conn
);
63 /** Pack global_id and circ_id; set *tag to the result. (See note on
64 * cpuworker_main for wire format.) */
66 tag_pack(char *tag
, uint64_t conn_id
, circid_t circ_id
)
68 /*XXXX RETHINK THIS WHOLE MESS !!!! !NM NM NM NM*/
69 *(uint64_t *)tag
= conn_id
;
70 *(uint16_t *)(tag
+8) = circ_id
;
73 /** Unpack <b>tag</b> into addr, port, and circ_id.
76 tag_unpack(const char *tag
, uint64_t *conn_id
, circid_t
*circ_id
)
78 *conn_id
= *(const uint64_t *)tag
;
79 *circ_id
= *(const uint16_t *)(tag
+8);
82 /** Called when the onion key has changed and we need to spawn new
83 * cpuworkers. Close all currently idle cpuworkers, and mark the last
84 * rotation time as now.
87 cpuworkers_rotate(void)
89 connection_t
*cpuworker
;
90 while ((cpuworker
= connection_get_by_type_state(CONN_TYPE_CPUWORKER
,
91 CPUWORKER_STATE_IDLE
))) {
92 connection_mark_for_close(cpuworker
);
95 last_rotation_time
= time(NULL
);
96 if (server_mode(get_options()))
97 spawn_enough_cpuworkers();
100 /** If the cpuworker closes the connection,
101 * mark it as closed and spawn a new one as needed. */
103 connection_cpu_reached_eof(connection_t
*conn
)
105 log_warn(LD_GENERAL
,"Read eof. CPU worker died unexpectedly.");
106 if (conn
->state
!= CPUWORKER_STATE_IDLE
) {
107 /* the circ associated with this cpuworker will have to wait until
108 * it gets culled in run_connection_housekeeping(), since we have
109 * no way to find out which circ it was. */
110 log_warn(LD_GENERAL
,"...and it left a circuit queued; abandoning circ.");
111 num_cpuworkers_busy
--;
114 spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up
116 connection_mark_for_close(conn
);
120 /** Called when we get data from a cpuworker. If the answer is not complete,
121 * wait for a complete answer. If the answer is complete,
122 * process it as appropriate.
125 connection_cpu_process_inbuf(connection_t
*conn
)
128 char buf
[LEN_ONION_RESPONSE
];
131 connection_t
*tmp_conn
;
132 or_connection_t
*p_conn
= NULL
;
136 tor_assert(conn
->type
== CONN_TYPE_CPUWORKER
);
138 if (!buf_datalen(conn
->inbuf
))
141 if (conn
->state
== CPUWORKER_STATE_BUSY_ONION
) {
142 if (buf_datalen(conn
->inbuf
) < LEN_ONION_RESPONSE
) /* answer available? */
143 return 0; /* not yet */
144 tor_assert(buf_datalen(conn
->inbuf
) == LEN_ONION_RESPONSE
);
146 connection_fetch_from_buf(&success
,1,conn
);
147 connection_fetch_from_buf(buf
,LEN_ONION_RESPONSE
-1,conn
);
149 /* parse out the circ it was talking about */
150 tag_unpack(buf
, &conn_id
, &circ_id
);
152 tmp_conn
= connection_get_by_global_id(conn_id
);
153 if (tmp_conn
&& !tmp_conn
->marked_for_close
&&
154 tmp_conn
->type
== CONN_TYPE_OR
)
155 p_conn
= TO_OR_CONN(tmp_conn
);
158 circ
= circuit_get_by_circid_orconn(circ_id
, p_conn
);
162 "decoding onionskin failed. "
163 "(Old key or bad software.) Closing.");
165 circuit_mark_for_close(circ
, END_CIRC_REASON_TORPROTOCOL
);
166 goto done_processing
;
169 /* This happens because somebody sends us a destroy cell and the
170 * circuit goes away, while the cpuworker is working. This is also
171 * why our tag doesn't include a pointer to the circ, because we'd
172 * never know if it's still valid.
174 log_debug(LD_OR
,"processed onion for a circ that's gone. Dropping.");
175 goto done_processing
;
177 tor_assert(! CIRCUIT_IS_ORIGIN(circ
));
178 if (onionskin_answer(TO_OR_CIRCUIT(circ
), CELL_CREATED
, buf
+TAG_LEN
,
179 buf
+TAG_LEN
+ONIONSKIN_REPLY_LEN
) < 0) {
180 log_warn(LD_OR
,"onionskin_answer failed. Closing.");
181 circuit_mark_for_close(circ
, END_CIRC_REASON_INTERNAL
);
182 goto done_processing
;
184 log_debug(LD_OR
,"onionskin_answer succeeded. Yay.");
186 tor_assert(0); /* don't ask me to do handshakes yet */
190 conn
->state
= CPUWORKER_STATE_IDLE
;
191 num_cpuworkers_busy
--;
192 if (conn
->timestamp_created
< last_rotation_time
) {
193 connection_mark_for_close(conn
);
195 spawn_enough_cpuworkers();
197 process_pending_task(conn
);
202 /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
203 * Read and writes from fdarray[1]. Reads requests, writes answers.
206 * Task type [1 byte, always CPUWORKER_TASK_ONION]
208 * Onionskin challenge ONIONSKIN_CHALLENGE_LEN
210 * Success/failure [1 byte, boolean.]
212 * Onionskin challenge ONIONSKIN_REPLY_LEN
213 * Negotiated keys KEY_LEN*2+DIGEST_LEN*2
215 * (Note: this _should_ be by addr/port, since we're concerned with specific
216 * connections, not with routers (where we'd use identity).)
219 cpuworker_main(void *data
)
221 char question
[ONIONSKIN_CHALLENGE_LEN
];
222 uint8_t question_type
;
226 /* variables for onion processing */
227 char keys
[CPATH_KEY_MATERIAL_LEN
];
228 char reply_to_proxy
[ONIONSKIN_REPLY_LEN
];
229 char buf
[LEN_ONION_RESPONSE
];
231 crypto_pk_env_t
*onion_key
= NULL
, *last_onion_key
= NULL
;
233 fd
= fdarray
[1]; /* this side is ours */
234 #ifndef TOR_IS_MULTITHREADED
235 tor_close_socket(fdarray
[0]); /* this is the side of the socketpair the
237 tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
238 handle_signals(0); /* ignore interrupts from the keyboard, etc */
242 dup_onion_keys(&onion_key
, &last_onion_key
);
247 if ((r
= recv(fd
, &question_type
, 1, 0)) != 1) {
248 // log_fn(LOG_ERR,"read type failed. Exiting.");
251 "CPU worker exiting because Tor process closed connection "
252 "(either rotated keys or died).");
255 "CPU worker exiting because of error on connection to Tor "
257 log_info(LD_OR
,"(Error on %d was %s)",
258 fd
, tor_socket_strerror(tor_socket_errno(fd
)));
262 tor_assert(question_type
== CPUWORKER_TASK_ONION
);
264 if (read_all(fd
, tag
, TAG_LEN
, 1) != TAG_LEN
) {
265 log_err(LD_BUG
,"read tag failed. Exiting.");
269 if (read_all(fd
, question
, ONIONSKIN_CHALLENGE_LEN
, 1) !=
270 ONIONSKIN_CHALLENGE_LEN
) {
271 log_err(LD_BUG
,"read question failed. Exiting.");
275 if (question_type
== CPUWORKER_TASK_ONION
) {
276 if (onion_skin_server_handshake(question
, onion_key
, last_onion_key
,
277 reply_to_proxy
, keys
, CPATH_KEY_MATERIAL_LEN
) < 0) {
279 log_debug(LD_OR
,"onion_skin_server_handshake failed.");
280 memset(buf
,0,LEN_ONION_RESPONSE
); /* send all zeros for failure */
283 log_debug(LD_OR
,"onion_skin_server_handshake succeeded.");
284 buf
[0] = 1; /* 1 means success */
285 memcpy(buf
+1,tag
,TAG_LEN
);
286 memcpy(buf
+1+TAG_LEN
,reply_to_proxy
,ONIONSKIN_REPLY_LEN
);
287 memcpy(buf
+1+TAG_LEN
+ONIONSKIN_REPLY_LEN
,keys
,CPATH_KEY_MATERIAL_LEN
);
289 if (write_all(fd
, buf
, LEN_ONION_RESPONSE
, 1) != LEN_ONION_RESPONSE
) {
290 log_err(LD_BUG
,"writing response buf failed. Exiting.");
293 log_debug(LD_OR
,"finished writing response.");
298 crypto_free_pk_env(onion_key
);
300 crypto_free_pk_env(last_onion_key
);
301 tor_close_socket(fd
);
302 crypto_thread_cleanup();
306 /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
309 spawn_cpuworker(void)
316 fdarray
= tor_malloc(sizeof(int)*2);
317 if ((err
= tor_socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdarray
)) < 0) {
318 log_warn(LD_NET
, "Couldn't construct socketpair for cpuworker: %s",
319 tor_socket_strerror(-err
));
324 tor_assert(fdarray
[0] >= 0);
325 tor_assert(fdarray
[1] >= 0);
328 spawn_func(cpuworker_main
, (void*)fdarray
);
329 log_debug(LD_OR
,"just spawned a cpu worker.");
330 #ifndef TOR_IS_MULTITHREADED
331 tor_close_socket(fdarray
[1]); /* don't need the worker's side of the pipe */
335 conn
= connection_new(CONN_TYPE_CPUWORKER
, AF_UNIX
);
337 set_socket_nonblocking(fd
);
339 /* set up conn so it's got all the data we need to remember */
341 conn
->address
= tor_strdup("localhost");
343 if (connection_add(conn
) < 0) { /* no space, forget it */
344 log_warn(LD_NET
,"connection_add for cpuworker failed. Giving up.");
345 connection_free(conn
); /* this closes fd */
349 conn
->state
= CPUWORKER_STATE_IDLE
;
350 connection_start_reading(conn
);
352 return 0; /* success */
355 /** If we have too few or too many active cpuworkers, try to spawn new ones
359 spawn_enough_cpuworkers(void)
361 int num_cpuworkers_needed
= get_options()->NumCpus
;
363 if (num_cpuworkers_needed
< MIN_CPUWORKERS
)
364 num_cpuworkers_needed
= MIN_CPUWORKERS
;
365 if (num_cpuworkers_needed
> MAX_CPUWORKERS
)
366 num_cpuworkers_needed
= MAX_CPUWORKERS
;
368 while (num_cpuworkers
< num_cpuworkers_needed
) {
369 if (spawn_cpuworker() < 0) {
370 log_warn(LD_GENERAL
,"Cpuworker spawn failed. Will try again later.");
377 /** Take a pending task from the queue and assign it to 'cpuworker'. */
379 process_pending_task(connection_t
*cpuworker
)
382 char *onionskin
= NULL
;
384 tor_assert(cpuworker
);
386 /* for now only process onion tasks */
388 circ
= onion_next_task(&onionskin
);
391 if (assign_onionskin_to_cpuworker(cpuworker
, circ
, onionskin
))
392 log_warn(LD_OR
,"assign_to_cpuworker failed. Ignoring.");
395 /** How long should we let a cpuworker stay busy before we give
396 * up on it and decide that we have a bug or infinite loop?
397 * This value is high because some servers with low memory/cpu
398 * sometimes spend an hour or more swapping, and Tor starves. */
399 #define CPUWORKER_BUSY_TIMEOUT (60*60*12)
401 /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers get
402 * stuck in the 'busy' state, even though the cpuworker process thinks of
403 * itself as idle. I don't know why. But here's a workaround to kill any
404 * cpuworker that's been busy for more than CPUWORKER_BUSY_TIMEOUT.
407 cull_wedged_cpuworkers(void)
409 time_t now
= time(NULL
);
410 smartlist_t
*conns
= get_connection_array();
411 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
413 if (!conn
->marked_for_close
&&
414 conn
->type
== CONN_TYPE_CPUWORKER
&&
415 conn
->state
== CPUWORKER_STATE_BUSY_ONION
&&
416 conn
->timestamp_lastwritten
+ CPUWORKER_BUSY_TIMEOUT
< now
) {
418 "closing wedged cpuworker. Can somebody find the bug?");
419 num_cpuworkers_busy
--;
421 connection_mark_for_close(conn
);
426 /** Try to tell a cpuworker to perform the public key operations necessary to
427 * respond to <b>onionskin</b> for the circuit <b>circ</b>.
429 * If <b>cpuworker</b> is defined, assert that he's idle, and use him. Else,
430 * look for an idle cpuworker and use him. If none idle, queue task onto the
431 * pending onion list and return. Return 0 if we successfully assign the
432 * task, or -1 on failure.
435 assign_onionskin_to_cpuworker(connection_t
*cpuworker
,
436 or_circuit_t
*circ
, char *onionskin
)
441 cull_wedged_cpuworkers();
442 spawn_enough_cpuworkers();
445 if (num_cpuworkers_busy
== num_cpuworkers
) {
446 log_debug(LD_OR
,"No idle cpuworkers. Queuing.");
447 if (onion_pending_add(circ
, onionskin
) < 0)
453 cpuworker
= connection_get_by_type_state(CONN_TYPE_CPUWORKER
,
454 CPUWORKER_STATE_IDLE
);
456 tor_assert(cpuworker
);
459 log_info(LD_OR
,"circ->p_conn gone. Failing circ.");
463 tag_pack(tag
, circ
->p_conn
->_base
.global_identifier
,
466 cpuworker
->state
= CPUWORKER_STATE_BUSY_ONION
;
467 /* touch the lastwritten timestamp, since that's how we check to
468 * see how long it's been since we asked the question, and sometimes
469 * we check before the first call to connection_handle_write(). */
470 cpuworker
->timestamp_lastwritten
= time(NULL
);
471 num_cpuworkers_busy
++;
473 qbuf
[0] = CPUWORKER_TASK_ONION
;
474 connection_write_to_buf(qbuf
, 1, cpuworker
);
475 connection_write_to_buf(tag
, sizeof(tag
), cpuworker
);
476 connection_write_to_buf(onionskin
, ONIONSKIN_CHALLENGE_LEN
, cpuworker
);