Fix last patch
[tor.git] / src / or / connection_edge.c
blob31bc9ba35108abc5a6256b1cbf37581d7022a765
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char connection_edge_c_id[] = "$Id$";
8 /**
9 * \file connection_edge.c
10 * \brief Handle edge streams.
11 **/
13 #include "or.h"
14 #include "tree.h"
16 static struct addr_policy_t *socks_policy = NULL;
17 /* List of exit_redirect_t */
18 static smartlist_t *redirect_exit_list = NULL;
20 static int connection_ap_handshake_process_socks(connection_t *conn);
22 /** There was an EOF. Send an end and mark the connection for close.
24 int connection_edge_reached_eof(connection_t *conn) {
25 #ifdef HALF_OPEN
26 /* eof reached; we're done reading, but we might want to write more. */
27 conn->done_receiving = 1;
28 shutdown(conn->s, 0); /* XXX check return, refactor NM */
29 if (conn->done_sending) {
30 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
31 connection_mark_for_close(conn);
32 } else {
33 connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_END,
34 NULL, 0, conn->cpath_layer);
36 return 0;
37 #else
38 if (buf_datalen(conn->inbuf)) {
39 /* it still has stuff to process. don't let it die yet. */
40 return 0;
42 log_fn(LOG_INFO,"conn (fd %d) reached eof (stream size %d). Closing.", conn->s, (int)conn->stream_size);
43 connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
44 if (!conn->marked_for_close) {
45 /* only mark it if not already marked. it's possible to
46 * get the 'end' right around when the client hangs up on us. */
47 connection_mark_for_close(conn);
49 conn->hold_open_until_flushed = 1; /* just because we shouldn't read
50 doesn't mean we shouldn't write */
51 return 0;
52 #endif
55 /** Handle new bytes on conn->inbuf based on state:
56 * - If it's waiting for socks info, try to read another step of the
57 * socks handshake out of conn->inbuf.
58 * - If it's open, then package more relay cells from the stream.
59 * - Else, leave the bytes on inbuf alone for now.
61 * Mark and return -1 if there was an unexpected error with the conn,
62 * else return 0.
64 int connection_edge_process_inbuf(connection_t *conn, int package_partial) {
66 tor_assert(conn);
67 tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
69 switch (conn->state) {
70 case AP_CONN_STATE_SOCKS_WAIT:
71 if (connection_ap_handshake_process_socks(conn) < 0) {
72 conn->has_sent_end = 1; /* no circ yet */
73 connection_mark_for_close(conn);
74 conn->hold_open_until_flushed = 1;
75 return -1;
77 return 0;
78 case AP_CONN_STATE_OPEN:
79 case EXIT_CONN_STATE_OPEN:
80 if (conn->package_window <= 0) {
81 /* XXX this is still getting called rarely :( */
82 log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
83 return 0;
85 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
86 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
87 connection_mark_for_close(conn);
88 return -1;
90 return 0;
91 case EXIT_CONN_STATE_CONNECTING:
92 case AP_CONN_STATE_RENDDESC_WAIT:
93 case AP_CONN_STATE_CIRCUIT_WAIT:
94 case AP_CONN_STATE_CONNECT_WAIT:
95 case AP_CONN_STATE_RESOLVE_WAIT:
96 log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
97 conn_state_to_string[conn->type][conn->state]);
98 return 0;
100 log_fn(LOG_WARN,"Got unexpected state %d. Closing.",conn->state);
101 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
102 connection_mark_for_close(conn);
103 return -1;
106 /** This edge needs to be closed, because its circuit has closed.
107 * Mark it for close and return 0.
109 int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
110 tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
112 if (conn->marked_for_close)
113 return 0; /* already marked; probably got an 'end' */
114 log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
115 circ_id);
116 conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
117 connection_mark_for_close(conn);
118 conn->hold_open_until_flushed = 1;
119 return 0;
122 /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
123 * with a destination of cpath_layer. (If cpath_layer is NULL, the
124 * destination is the circuit's origin.) Mark the relay end cell as
125 * closing because of <b>reason</b>.
127 * Return -1 if this function has already been called on this conn,
128 * else return 0.
131 connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
133 char payload[5];
134 size_t payload_len=1;
135 circuit_t *circ;
137 if (conn->has_sent_end) {
138 log_fn(LOG_WARN,"It appears I've already sent the end. Are you calling me twice?");
139 return -1;
142 payload[0] = reason;
143 if (reason == END_STREAM_REASON_EXITPOLICY) {
144 /* this is safe even for rend circs, because they never fail
145 * because of exitpolicy */
146 set_uint32(payload+1, htonl(conn->addr));
147 payload_len += 4;
150 circ = circuit_get_by_conn(conn);
151 if (circ && !circ->marked_for_close) {
152 log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
153 connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
154 payload, payload_len, cpath_layer);
155 } else {
156 log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
159 conn->has_sent_end = 1;
160 return 0;
163 /** Connection <b>conn</b> has finished writing and has no bytes left on
164 * its outbuf.
166 * If it's in state 'open', stop writing, consider responding with a
167 * sendme, and return.
168 * Otherwise, stop writing and return.
170 * If <b>conn</b> is broken, mark it for close and return -1, else
171 * return 0.
173 int connection_edge_finished_flushing(connection_t *conn) {
174 tor_assert(conn);
175 tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
177 switch (conn->state) {
178 case AP_CONN_STATE_OPEN:
179 case EXIT_CONN_STATE_OPEN:
180 connection_stop_writing(conn);
181 connection_edge_consider_sending_sendme(conn);
182 return 0;
183 case AP_CONN_STATE_SOCKS_WAIT:
184 case AP_CONN_STATE_RENDDESC_WAIT:
185 case AP_CONN_STATE_CIRCUIT_WAIT:
186 case AP_CONN_STATE_CONNECT_WAIT:
187 connection_stop_writing(conn);
188 return 0;
189 default:
190 log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
191 return -1;
193 return 0;
196 /** Connected handler for exit connections: start writing pending
197 * data, deliver 'CONNECTED' relay cells as appropriate, and check
198 * any pending data that may have been received. */
199 int connection_edge_finished_connecting(connection_t *conn)
201 unsigned char connected_payload[4];
203 tor_assert(conn);
204 tor_assert(conn->type == CONN_TYPE_EXIT);
205 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
207 log_fn(LOG_INFO,"Exit connection to %s:%u established.",
208 conn->address,conn->port);
210 conn->state = EXIT_CONN_STATE_OPEN;
211 connection_watch_events(conn, POLLIN); /* stop writing, continue reading */
212 if (connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
213 connection_start_writing(conn);
214 /* deliver a 'connected' relay cell back through the circuit. */
215 if (connection_edge_is_rendezvous_stream(conn)) {
216 if (connection_edge_send_command(conn, circuit_get_by_conn(conn),
217 RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
218 return 0; /* circuit is closed, don't continue */
219 } else {
220 *(uint32_t*)connected_payload = htonl(conn->addr);
221 if (connection_edge_send_command(conn, circuit_get_by_conn(conn),
222 RELAY_COMMAND_CONNECTED, connected_payload, 4, conn->cpath_layer) < 0)
223 return 0; /* circuit is closed, don't continue */
225 tor_assert(conn->package_window > 0);
226 /* in case the server has written anything */
227 return connection_edge_process_inbuf(conn, 1);
230 /** How many times do we retry a general-purpose stream (detach it from
231 * one circuit and try another, after we wait a while with no 'connected'
232 * cell) before giving up?
234 #define MAX_STREAM_RETRIES 4
236 /** Find all general-purpose AP streams in state connect_wait that sent
237 * their begin cell >=15 seconds ago. Detach from their current circuit,
238 * and mark their current circuit as unsuitable for new streams. Then call
239 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
240 * available) or launch a new one.
242 * For rendezvous streams, simply give up after 45 seconds (with no
243 * retry attempt).
245 void connection_ap_expire_beginning(void) {
246 connection_t **carray;
247 connection_t *conn;
248 circuit_t *circ;
249 int n, i;
250 time_t now = time(NULL);
251 or_options_t *options = get_options();
253 get_connection_array(&carray, &n);
255 for (i = 0; i < n; ++i) {
256 conn = carray[i];
257 if (conn->type != CONN_TYPE_AP ||
258 conn->state != AP_CONN_STATE_CONNECT_WAIT)
259 continue;
260 if (now - conn->timestamp_lastread < 15)
261 continue;
262 conn->num_retries++;
263 circ = circuit_get_by_conn(conn);
264 if (!circ) { /* it's vanished? */
265 log_fn(LOG_INFO,"Conn is in connect-wait, but lost its circ.");
266 connection_mark_for_close(conn);
267 continue;
269 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
270 if (now - conn->timestamp_lastread > 45) {
271 log_fn(LOG_WARN,"Rend stream is %d seconds late. Giving up.",
272 (int)(now - conn->timestamp_lastread));
273 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
274 connection_mark_for_close(conn);
276 continue;
278 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
279 if (conn->num_retries >= MAX_STREAM_RETRIES) {
280 log_fn(LOG_WARN,"Stream is %d seconds late. Giving up.",
281 15*conn->num_retries);
282 circuit_log_path(LOG_WARN, circ);
283 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
284 connection_mark_for_close(conn);
285 } else {
286 log_fn(LOG_WARN,"Stream is %d seconds late. Retrying.",
287 (int)(now - conn->timestamp_lastread));
288 circuit_log_path(LOG_WARN, circ);
289 /* send an end down the circuit */
290 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
291 /* un-mark it as ending, since we're going to reuse it */
292 conn->has_sent_end = 0;
293 /* move it back into 'pending' state. */
294 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
295 circuit_detach_stream(circ, conn);
296 /* kludge to make us not try this circuit again, yet to allow
297 * current streams on it to survive if they can: make it
298 * unattractive to use for new streams */
299 tor_assert(circ->timestamp_dirty);
300 circ->timestamp_dirty -= options->NewCircuitPeriod;
301 /* give our stream another 15 seconds to try */
302 conn->timestamp_lastread += 15;
303 /* attaching to a dirty circuit is fine */
304 if (connection_ap_handshake_attach_circuit(conn)<0) {
305 /* it will never work */
306 /* Don't need to send end -- we're not connected */
307 conn->has_sent_end = 1;
308 connection_mark_for_close(conn);
310 } /* end if max_retries */
311 } /* end for */
314 /** Tell any AP streams that are waiting for a new circuit that one is
315 * available.
317 void connection_ap_attach_pending(void)
319 connection_t **carray;
320 connection_t *conn;
321 int n, i;
323 get_connection_array(&carray, &n);
325 for (i = 0; i < n; ++i) {
326 conn = carray[i];
327 if (conn->marked_for_close ||
328 conn->type != CONN_TYPE_AP ||
329 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
330 continue;
331 if (connection_ap_handshake_attach_circuit(conn) < 0) {
332 /* -1 means it will never work */
333 /* Don't send end; there is no 'other side' yet */
334 conn->has_sent_end = 1;
335 connection_mark_for_close(conn);
340 /** connection_edge_process_inbuf() found a conn in state
341 * socks_wait. See if conn->inbuf has the right bytes to proceed with
342 * the socks handshake.
344 * If the handshake is complete, and it's for a general circuit, then
345 * try to attach it to a circuit (or launch one as needed). If it's for
346 * a rendezvous circuit, then fetch a rendezvous descriptor first (or
347 * attach/launch a circuit if the rendezvous descriptor is already here
348 * and fresh enough).
350 * Return -1 if an unexpected error with conn (and it should be marked
351 * for close), else return 0.
353 static int connection_ap_handshake_process_socks(connection_t *conn) {
354 socks_request_t *socks;
355 int sockshere;
356 hostname_type_t addresstype;
358 tor_assert(conn);
359 tor_assert(conn->type == CONN_TYPE_AP);
360 tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
361 tor_assert(conn->socks_request);
362 socks = conn->socks_request;
364 log_fn(LOG_DEBUG,"entered.");
366 sockshere = fetch_from_buf_socks(conn->inbuf, socks);
367 if (sockshere == -1 || sockshere == 0) {
368 if (socks->replylen) { /* we should send reply back */
369 log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
370 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
371 socks->replylen = 0; /* zero it out so we can do another round of negotiation */
372 } else if (sockshere == -1) { /* send normal reject */
373 log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
374 connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
375 } else {
376 log_fn(LOG_DEBUG,"socks handshake not all here yet.");
378 if (sockshere == -1)
379 socks->has_finished = 1;
380 return sockshere;
381 } /* else socks handshake is done, continue processing */
383 if (socks->command == SOCKS_COMMAND_RESOLVE) {
384 uint32_t answer;
385 /* Reply to resolves immediately if we can. */
386 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
387 log_fn(LOG_WARN,"Address to be resolved is too large. Failing.");
388 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
389 return -1;
391 answer = htonl(client_dns_lookup_entry(socks->address));
392 if (answer) {
393 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
394 (char*)&answer);
395 conn->has_sent_end = 1;
396 connection_mark_for_close(conn);
397 conn->hold_open_until_flushed = 1;
398 return 0;
402 /* Parse the address provided by SOCKS. Modify it in-place if it
403 * specifies a hidden-service (.onion) or particular exit node (.exit).
405 addresstype = parse_extended_hostname(socks->address);
407 if (addresstype == EXIT_HOSTNAME) {
408 /* .exit -- modify conn to specify the exit node. */
409 char *s = strrchr(socks->address,'.');
410 if (!s || s[1] == '\0') {
411 log_fn(LOG_WARN,"Malformed address '%s.exit'. Refusing.", socks->address);
412 return -1;
414 if (strlen(s+1) == HEX_DIGEST_LEN) {
415 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
416 *(conn->chosen_exit_name) = '$';
417 strlcpy(conn->chosen_exit_name+1, s+1, HEX_DIGEST_LEN+1);
418 } else {
419 conn->chosen_exit_name = tor_strdup(s+1);
421 *s = 0;
422 if (!is_legal_nickname_or_hexdigest(conn->chosen_exit_name)) {
423 log_fn(LOG_WARN, "%s is not a legal exit node nickname; rejecting.",
424 conn->chosen_exit_name);
425 return -1;
429 if (addresstype != ONION_HOSTNAME) {
430 /* not a hidden-service request (i.e. normal or .exit) */
431 if (socks->command == SOCKS_COMMAND_CONNECT && socks->port == 0) {
432 log_fn(LOG_WARN,"Application asked to connect to port 0. Refusing.");
433 return -1;
435 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
436 return connection_ap_handshake_attach_circuit(conn);
437 } else {
438 /* it's a hidden-service request */
439 rend_cache_entry_t *entry;
440 int r;
442 if (socks->command == SOCKS_COMMAND_RESOLVE) {
443 /* if it's a resolve request, fail it right now, rather than
444 * building all the circuits and then realizing it won't work. */
445 log_fn(LOG_WARN,"Resolve requests to hidden services not allowed. Failing.");
446 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
447 return -1;
450 strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
451 log_fn(LOG_INFO,"Got a hidden service request for ID '%s'", conn->rend_query);
452 /* see if we already have it cached */
453 r = rend_cache_lookup_entry(conn->rend_query, &entry);
454 if (r<0) {
455 log_fn(LOG_WARN,"Invalid service descriptor %s", conn->rend_query);
456 return -1;
458 if (r==0) {
459 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
460 log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.", conn->rend_query);
461 rend_client_refetch_renddesc(conn->rend_query);
462 return 0;
464 if (r>0) {
465 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
466 if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
467 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
468 log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
469 return connection_ap_handshake_attach_circuit(conn);
470 } else {
471 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
472 log_fn(LOG_INFO, "Stale descriptor %s. Refetching.", conn->rend_query);
473 rend_client_refetch_renddesc(conn->rend_query);
474 return 0;
478 return 0; /* unreached but keeps the compiler happy */
481 /** Iterate over the two bytes of stream_id until we get one that is not
482 * already in use; return it. Return 0 if can't get a unique stream_id.
484 static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
485 connection_t *tmpconn;
486 uint16_t test_stream_id;
487 uint32_t attempts=0;
489 again:
490 test_stream_id = circ->next_stream_id++;
491 if (++attempts > 1<<16) {
492 /* Make sure we don't loop forever if all stream_id's are used. */
493 log_fn(LOG_WARN,"No unused stream IDs. Failing.");
494 return 0;
496 if (test_stream_id == 0)
497 goto again;
498 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
499 if (tmpconn->stream_id == test_stream_id)
500 goto again;
501 return test_stream_id;
504 /** Write a relay begin cell, using destaddr and destport from ap_conn's
505 * socks_request field, and send it down circ.
507 * If ap_conn is broken, mark it for close and return -1. Else return 0.
509 int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
511 char payload[CELL_PAYLOAD_SIZE];
512 int payload_len;
513 struct in_addr in;
514 const char *string_addr;
516 tor_assert(ap_conn->type == CONN_TYPE_AP);
517 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
518 tor_assert(ap_conn->socks_request);
520 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
521 if (ap_conn->stream_id==0) {
522 /* Don't send end: there is no 'other side' yet */
523 ap_conn->has_sent_end = 1;
524 connection_mark_for_close(ap_conn);
525 circuit_mark_for_close(circ);
526 return -1;
529 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
530 in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
531 string_addr = in.s_addr ? inet_ntoa(in) : NULL;
533 tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
534 "%s:%d",
535 string_addr ? string_addr : ap_conn->socks_request->address,
536 ap_conn->socks_request->port);
537 } else {
538 tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
539 ":%d", ap_conn->socks_request->port);
541 payload_len = strlen(payload)+1;
543 log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
545 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
546 payload, payload_len, ap_conn->cpath_layer) < 0)
547 return -1; /* circuit is closed, don't continue */
549 ap_conn->package_window = STREAMWINDOW_START;
550 ap_conn->deliver_window = STREAMWINDOW_START;
551 ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
552 log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
553 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
554 return 0;
557 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
558 * socks_request field, and send it down circ.
560 * If ap_conn is broken, mark it for close and return -1. Else return 0.
562 int connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
564 int payload_len;
565 const char *string_addr;
567 tor_assert(ap_conn->type == CONN_TYPE_AP);
568 tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
569 tor_assert(ap_conn->socks_request);
570 tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
571 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
573 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
574 if (ap_conn->stream_id==0) {
575 /* Don't send end: there is no 'other side' yet */
576 ap_conn->has_sent_end = 1;
577 connection_mark_for_close(ap_conn);
578 circuit_mark_for_close(circ);
579 return -1;
582 string_addr = ap_conn->socks_request->address;
583 payload_len = strlen(string_addr);
584 tor_assert(strlen(string_addr) <= RELAY_PAYLOAD_SIZE);
586 log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
588 if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
589 string_addr, payload_len, ap_conn->cpath_layer) < 0)
590 return -1; /* circuit is closed, don't continue */
592 ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
593 log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
594 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
595 return 0;
598 /** Make an AP connection_t, do a socketpair and attach one side
599 * to the conn, connection_add it, initialize it to circuit_wait,
600 * and call connection_ap_handshake_attach_circuit(conn) on it.
602 * Return the other end of the socketpair, or -1 if error.
604 int connection_ap_make_bridge(char *address, uint16_t port) {
605 int fd[2];
606 connection_t *conn;
608 log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
610 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
611 log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
612 tor_socket_strerror(tor_socket_errno(-1)));
613 return -1;
616 set_socket_nonblocking(fd[0]);
617 set_socket_nonblocking(fd[1]);
619 conn = connection_new(CONN_TYPE_AP);
620 conn->s = fd[0];
622 /* populate conn->socks_request */
624 /* leave version at zero, so the socks_reply is empty */
625 conn->socks_request->socks_version = 0;
626 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
627 strlcpy(conn->socks_request->address, address,
628 sizeof(conn->socks_request->address));
629 conn->socks_request->port = port;
630 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
632 conn->address = tor_strdup("(local bridge)");
633 conn->addr = 0;
634 conn->port = 0;
636 if (connection_add(conn) < 0) { /* no space, forget it */
637 connection_free(conn); /* this closes fd[0] */
638 tor_close_socket(fd[1]);
639 return -1;
642 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
643 connection_start_reading(conn);
645 /* attaching to a dirty circuit is fine */
646 if (connection_ap_handshake_attach_circuit(conn) < 0) {
647 conn->has_sent_end = 1; /* no circ to send to */
648 connection_mark_for_close(conn);
649 tor_close_socket(fd[1]);
650 return -1;
653 log_fn(LOG_INFO,"... AP bridge created and connected.");
654 return fd[1];
657 /* DOCDOC */
658 void connection_ap_handshake_socks_resolved(connection_t *conn,
659 int answer_type,
660 size_t answer_len,
661 const char *answer)
663 char buf[256];
664 size_t replylen;
666 if (answer_type == RESOLVED_TYPE_IPV4) {
667 uint32_t a = get_uint32(answer);
668 if (a)
669 client_dns_set_entry(conn->socks_request->address, ntohl(a));
672 if (conn->socks_request->socks_version == 4) {
673 buf[0] = 0x00; /* version */
674 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
675 buf[1] = 90; /* "Granted" */
676 set_uint16(buf+2, 0);
677 memcpy(buf+4, answer, 4); /* address */
678 replylen = SOCKS4_NETWORK_LEN;
679 } else {
680 buf[1] = 91; /* "error" */
681 memset(buf+2, 0, 6);
682 replylen = SOCKS4_NETWORK_LEN;
684 } else {
685 /* SOCKS5 */
686 buf[0] = 0x05; /* version */
687 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
688 buf[1] = 0; /* succeeded */
689 buf[2] = 0; /* reserved */
690 buf[3] = 0x01; /* IPv4 address type */
691 memcpy(buf+4, answer, 4); /* address */
692 set_uint16(buf+8, 0); /* port == 0. */
693 replylen = 10;
694 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
695 buf[1] = 0; /* succeeded */
696 buf[2] = 0; /* reserved */
697 buf[3] = 0x04; /* IPv6 address type */
698 memcpy(buf+4, answer, 16); /* address */
699 set_uint16(buf+20, 0); /* port == 0. */
700 replylen = 22;
701 } else {
702 buf[1] = 0x04; /* host unreachable */
703 memset(buf+2, 0, 8);
704 replylen = 10;
707 connection_ap_handshake_socks_reply(conn, buf, replylen,
708 (answer_type == RESOLVED_TYPE_IPV4 ||
709 answer_type == RESOLVED_TYPE_IPV6) ? 1 : -1);
710 conn->socks_request->has_finished = 1;
713 /** Send a socks reply to stream <b>conn</b>, using the appropriate
714 * socks version, etc.
716 * Status can be 1 (succeeded), -1 (failed), or 0 (not sure yet).
718 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
719 * to conn and return, else reply based on <b>status</b>.
721 * If <b>reply</b> is undefined, <b>status</b> can't be 0.
723 void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
724 size_t replylen, int status) {
725 char buf[256];
727 if (status) /* it's either 1 or -1 */
728 control_event_stream_status(conn,
729 status==1 ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
731 if (replylen) { /* we already have a reply in mind */
732 connection_write_to_buf(reply, replylen, conn);
733 return;
735 tor_assert(conn->socks_request);
736 tor_assert(status == 1 || status == -1);
737 if (conn->socks_request->socks_version == 4) {
738 memset(buf,0,SOCKS4_NETWORK_LEN);
739 #define SOCKS4_GRANTED 90
740 #define SOCKS4_REJECT 91
741 buf[1] = (status==1 ? SOCKS4_GRANTED : SOCKS4_REJECT);
742 /* leave version, destport, destip zero */
743 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
745 if (conn->socks_request->socks_version == 5) {
746 buf[0] = 5; /* version 5 */
747 #define SOCKS5_SUCCESS 0
748 #define SOCKS5_GENERIC_ERROR 1
749 buf[1] = status==1 ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
750 buf[2] = 0;
751 buf[3] = 1; /* ipv4 addr */
752 memset(buf+4,0,6); /* Set external addr/port to 0.
753 The spec doesn't seem to say what to do here. -RD */
754 connection_write_to_buf(buf,10,conn);
756 /* If socks_version isn't 4 or 5, don't send anything.
757 * This can happen in the case of AP bridges. */
758 return;
761 /** A relay 'begin' cell has arrived, and either we are an exit hop
762 * for the circuit, or we are the origin and it is a rendezvous begin.
764 * Launch a new exit connection and initialize things appropriately.
766 * If it's a rendezvous stream, call connection_exit_connect() on
767 * it.
769 * For general streams, call dns_resolve() on it first, and only call
770 * connection_exit_connect() if the dns answer is already known.
772 * Note that we don't call connection_add() on the new stream! We wait
773 * for connection_exit_connect() to do that.
775 * Return -1 if we want to tear down <b>circ</b>. Else return 0.
777 int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
778 connection_t *n_stream;
779 relay_header_t rh;
780 char *address=NULL;
781 uint16_t port;
783 assert_circuit_ok(circ);
784 relay_header_unpack(&rh, cell->payload);
786 /* XXX currently we don't send an end cell back if we drop the
787 * begin because it's malformed.
790 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
791 log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
792 return 0;
794 if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
795 log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
796 return 0;
798 if (port==0) {
799 log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
800 tor_free(address);
801 return 0;
804 log_fn(LOG_DEBUG,"Creating new exit connection.");
805 n_stream = connection_new(CONN_TYPE_EXIT);
806 n_stream->purpose = EXIT_PURPOSE_CONNECT;
808 n_stream->stream_id = rh.stream_id;
809 n_stream->port = port;
810 /* leave n_stream->s at -1, because it's not yet valid */
811 n_stream->package_window = STREAMWINDOW_START;
812 n_stream->deliver_window = STREAMWINDOW_START;
814 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
815 log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
816 n_stream->address = tor_strdup("(rendezvous)");
817 n_stream->state = EXIT_CONN_STATE_CONNECTING;
818 strlcpy(n_stream->rend_query, circ->rend_query,
819 sizeof(n_stream->rend_query));
820 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
821 assert_circuit_ok(circ);
822 if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
823 log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
824 connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
825 connection_free(n_stream);
826 circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
827 tor_free(address);
828 return 0;
830 assert_circuit_ok(circ);
831 log_fn(LOG_DEBUG,"Finished assigning addr/port");
832 n_stream->cpath_layer = circ->cpath->prev; /* link it */
834 /* add it into the linked list of n_streams on this circuit */
835 n_stream->next_stream = circ->n_streams;
836 circ->n_streams = n_stream;
837 assert_circuit_ok(circ);
839 connection_exit_connect(n_stream);
840 tor_free(address);
841 return 0;
843 n_stream->address = address;
844 n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
845 /* default to failed, change in dns_resolve if it turns out not to fail */
847 if (we_are_hibernating()) {
848 connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
849 connection_free(n_stream);
852 /* send it off to the gethostbyname farm */
853 switch (dns_resolve(n_stream)) {
854 case 1: /* resolve worked */
856 /* add it into the linked list of n_streams on this circuit */
857 n_stream->next_stream = circ->n_streams;
858 circ->n_streams = n_stream;
859 assert_circuit_ok(circ);
861 connection_exit_connect(n_stream);
862 return 0;
863 case -1: /* resolve failed */
864 log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
865 connection_edge_end(n_stream, END_STREAM_REASON_RESOLVEFAILED, n_stream->cpath_layer);
866 connection_free(n_stream);
867 break;
868 case 0: /* resolve added to pending list */
869 /* add it into the linked list of resolving_streams on this circuit */
870 n_stream->next_stream = circ->resolving_streams;
871 circ->resolving_streams = n_stream;
872 assert_circuit_ok(circ);
875 return 0;
879 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
880 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
882 int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ) {
883 connection_t *dummy_conn;
884 relay_header_t rh;
886 assert_circuit_ok(circ);
887 relay_header_unpack(&rh, cell->payload);
889 /* This 'dummy_conn' only exists to remember the stream ID
890 * associated with the resolve request; and to make the
891 * implementation of dns.c more uniform. (We really only need to
892 * remember the circuit, the stream ID, and the hostname to be
893 * resolved; but if we didn't store them in a connection like this,
894 * the housekeeping in dns.c would get way more complicated.)
896 dummy_conn = connection_new(CONN_TYPE_EXIT);
897 dummy_conn->stream_id = rh.stream_id;
898 dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
899 rh.length);
900 dummy_conn->port = 0;
901 dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
902 dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
904 dummy_conn->next_stream = circ->resolving_streams;
905 circ->resolving_streams = dummy_conn;
907 /* send it off to the gethostbyname farm */
908 switch (dns_resolve(dummy_conn)) {
909 case 1: /* The result was cached; a resolved cell was sent. */
910 case -1:
911 circuit_detach_stream(circuit_get_by_conn(dummy_conn), dummy_conn);
912 connection_free(dummy_conn);
913 return 0;
914 case 0: /* resolve added to pending list */
915 assert_circuit_ok(circ);
918 return 0;
921 /** Connect to conn's specified addr and port. If it worked, conn
922 * has now been added to the connection_array.
924 * Send back a connected cell. Include the resolved IP of the destination
925 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
926 * streams must not reveal what IP they connected to.)
928 void
929 connection_exit_connect(connection_t *conn) {
930 unsigned char connected_payload[4];
931 uint32_t addr;
932 uint16_t port;
934 if (!connection_edge_is_rendezvous_stream(conn) &&
935 router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
936 log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
937 connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
938 circuit_detach_stream(circuit_get_by_conn(conn), conn);
939 connection_free(conn);
940 return;
943 addr = conn->addr;
944 port = conn->port;
945 if (redirect_exit_list) {
946 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
948 if ((addr&r->mask)==(r->addr&r->mask) &&
949 (r->port_min <= port) && (port <= r->port_max)) {
950 struct in_addr in;
951 if (r->is_redirect) {
952 addr = r->addr_dest;
953 port = r->port_dest;
954 in.s_addr = htonl(addr);
955 log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
956 conn->address, conn->port, inet_ntoa(in), port);
958 break;
963 log_fn(LOG_DEBUG,"about to try connecting");
964 switch (connection_connect(conn, conn->address, addr, port)) {
965 case -1:
966 connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, conn->cpath_layer);
967 circuit_detach_stream(circuit_get_by_conn(conn), conn);
968 connection_free(conn);
969 return;
970 case 0:
971 conn->state = EXIT_CONN_STATE_CONNECTING;
973 connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
974 /* writable indicates finish, readable indicates broken link,
975 error indicates broken link in windowsland. */
976 return;
977 /* case 1: fall through */
980 conn->state = EXIT_CONN_STATE_OPEN;
981 if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
982 log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
983 // connection_start_writing(conn);
985 connection_watch_events(conn, POLLIN);
987 /* also, deliver a 'connected' cell back through the circuit. */
988 if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
989 /* don't send an address back! */
990 connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
991 NULL, 0, conn->cpath_layer);
992 } else { /* normal stream */
993 /* This must be the original address, not the redirected address. */
994 *(uint32_t*)connected_payload = htonl(conn->addr);
995 connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
996 connected_payload, 4, conn->cpath_layer);
1000 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
1001 * it is a general stream.
1003 int connection_edge_is_rendezvous_stream(connection_t *conn) {
1004 tor_assert(conn);
1005 if (*conn->rend_query) /* XXX */
1006 return 1;
1007 return 0;
1010 /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
1011 * to exit from it, or 0 if it definitely will not allow it.
1012 * (We might be uncertain if conn's destination address has not yet been
1013 * resolved.)
1015 int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
1017 uint32_t addr;
1019 tor_assert(conn);
1020 tor_assert(conn->type == CONN_TYPE_AP);
1021 tor_assert(conn->socks_request);
1022 tor_assert(exit);
1024 log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
1025 exit->nickname, conn->socks_request->address,
1026 conn->socks_request->port);
1028 /* If a particular exit node has been requested for the new connection,
1029 * make sure the exit node of the existing circuit matches exactly.
1031 if (conn->chosen_exit_name) {
1032 if (router_get_by_nickname(conn->chosen_exit_name) != exit) {
1033 /* doesn't match */
1034 log_fn(LOG_DEBUG,"Requested node '%s', considering node '%s'. No.",
1035 conn->chosen_exit_name, exit->nickname);
1036 return 0;
1040 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE) {
1041 /* 0.0.8 servers have buggy resolve support. */
1042 if (!tor_version_as_new_as(exit->platform, "0.0.9pre1"))
1043 return 0;
1044 } else {
1045 addr = client_dns_lookup_entry(conn->socks_request->address);
1046 if (router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
1047 exit->exit_policy) < 0)
1048 return 0;
1050 return 1;
1053 /** A helper function for socks_policy_permits_address() below.
1055 * Parse options->SocksPolicy in the same way that the exit policy
1056 * is parsed, and put the processed version in &socks_policy.
1057 * Ignore port specifiers.
1059 void
1060 parse_socks_policy(void)
1062 struct addr_policy_t *n;
1063 if (socks_policy) {
1064 addr_policy_free(socks_policy);
1065 socks_policy = NULL;
1067 config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy);
1068 /* ports aren't used. */
1069 for (n=socks_policy; n; n = n->next) {
1070 n->prt_min = 1;
1071 n->prt_max = 65535;
1075 /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
1076 * based on <b>socks_policy</b>. Else return 0.
1078 int socks_policy_permits_address(uint32_t addr)
1080 int a;
1082 if (!socks_policy) /* 'no socks policy' means 'accept' */
1083 return 1;
1084 a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
1085 if (a==-1)
1086 return 0;
1087 else if (a==0)
1088 return 1;
1089 tor_assert(a==1);
1090 log_fn(LOG_WARN, "Got unexpected 'maybe' answer from socks policy");
1091 return 0;
1094 /* ***** Client DNS code ***** */
1096 /* XXX Perhaps this should get merged with the dns.c code somehow. */
1097 /* XXX But we can't just merge them, because then nodes that act as
1098 * both OR and OP could be attacked: people could rig the dns cache
1099 * by answering funny things to stream begin requests, and later
1100 * other clients would reuse those funny addr's. Hm.
1103 /** A client-side struct to remember the resolved IP (addr) for
1104 * a given address. These structs make up a tree, with client_dns_map
1105 * below as its root.
1107 struct client_dns_entry {
1108 uint32_t addr; /**< The resolved IP of this entry. */
1109 time_t expires; /**< At what second does addr expire? */
1110 int n_failures; /**< How many times has this entry failed to resolve so far? */
1113 /** How many elements are in the client dns cache currently? */
1114 static int client_dns_size = 0;
1115 /** The tree of client-side cached DNS resolves. */
1116 static strmap_t *client_dns_map = NULL;
1118 /** Initialize client_dns_map and client_dns_size. */
1119 void client_dns_init(void) {
1120 client_dns_map = strmap_new();
1121 client_dns_size = 0;
1124 /** Return the client_dns_entry that corresponds to <b>address</b>.
1125 * If it's not there, allocate and return a new entry for <b>address</b>.
1127 static struct client_dns_entry *
1128 _get_or_create_ent(const char *address)
1130 struct client_dns_entry *ent;
1131 ent = strmap_get_lc(client_dns_map,address);
1132 if (!ent) {
1133 ent = tor_malloc_zero(sizeof(struct client_dns_entry));
1134 ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
1135 strmap_set_lc(client_dns_map,address,ent);
1136 ++client_dns_size;
1138 return ent;
1141 /** Return the IP associated with <b>address</b>, if we know it
1142 * and it's still fresh enough. Otherwise return 0.
1144 uint32_t client_dns_lookup_entry(const char *address)
1146 struct client_dns_entry *ent;
1147 struct in_addr in;
1148 time_t now;
1150 tor_assert(address);
1152 if (tor_inet_aton(address, &in)) {
1153 log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
1154 (unsigned long)ntohl(in.s_addr));
1155 return ntohl(in.s_addr);
1157 ent = strmap_get_lc(client_dns_map,address);
1158 if (!ent || !ent->addr) {
1159 log_fn(LOG_DEBUG, "No entry found for address %s", address);
1160 return 0;
1161 } else {
1162 now = time(NULL);
1163 if (ent->expires < now) {
1164 log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
1165 strmap_remove_lc(client_dns_map,address);
1166 tor_free(ent);
1167 --client_dns_size;
1168 return 0;
1170 in.s_addr = htonl(ent->addr);
1171 log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
1172 inet_ntoa(in));
1173 return ent->addr;
1177 /** An attempt to resolve <b>address</b> failed at some OR.
1178 * Increment the number of resolve failures we have on record
1179 * for it, and then return that number.
1181 int client_dns_incr_failures(const char *address)
1183 struct client_dns_entry *ent;
1184 ent = _get_or_create_ent(address);
1185 ++ent->n_failures;
1186 log_fn(LOG_DEBUG,"Address %s now has %d resolve failures.",
1187 address, ent->n_failures);
1188 return ent->n_failures;
1191 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1192 * We can now use this in subsequent streams in client_dns_lookup_entry(),
1193 * so we can more correctly choose a router that will allow <b>address</b>
1194 * to exit from him.
1196 void client_dns_set_entry(const char *address, uint32_t val)
1198 struct client_dns_entry *ent;
1199 struct in_addr in;
1200 time_t now;
1202 tor_assert(address);
1203 tor_assert(val);
1205 if (tor_inet_aton(address, &in))
1206 return;
1207 now = time(NULL);
1208 ent = _get_or_create_ent(address);
1209 in.s_addr = htonl(val);
1210 log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
1211 inet_ntoa(in));
1212 ent->addr = val;
1213 ent->expires = now+MAX_DNS_ENTRY_AGE;
1214 ent->n_failures = 0;
1217 /** A helper function for client_dns_clean() below. If ent is too old,
1218 * then remove it from the tree and return NULL, else return ent.
1220 static void* _remove_if_expired(const char *addr,
1221 struct client_dns_entry *ent,
1222 time_t *nowp)
1224 if (ent->expires < *nowp) {
1225 --client_dns_size;
1226 tor_free(ent);
1227 return NULL;
1228 } else {
1229 return ent;
1233 /** Clean out entries from the client-side DNS cache that were
1234 * resolved long enough ago that they are no longer valid.
1236 void client_dns_clean(void)
1238 time_t now;
1240 if (!client_dns_size)
1241 return;
1242 now = time(NULL);
1243 strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
1246 /** Make connection redirection follow the provided list of
1247 * exit_redirect_t */
1248 void
1249 set_exit_redirects(smartlist_t *lst)
1251 if (redirect_exit_list) {
1252 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
1253 smartlist_free(redirect_exit_list);
1255 redirect_exit_list = lst;
1258 /** If address is of the form "y.onion" with a well-formed handle y:
1259 * Put a '\0' after y, lower-case it, and return ONION_HOSTNAME.
1261 * If address is of the form "y.exit":
1262 * Put a '\0' after y and return EXIT_HOSTNAME.
1264 * Otherwise:
1265 * Return NORMAL_HOSTNAME and change nothing.
1267 hostname_type_t
1268 parse_extended_hostname(char *address) {
1269 char *s;
1270 char query[REND_SERVICE_ID_LEN+1];
1272 s = strrchr(address,'.');
1273 if (!s) return 0; /* no dot, thus normal */
1274 if (!strcasecmp(s+1,"exit")) {
1275 *s = 0; /* null-terminate it */
1276 return EXIT_HOSTNAME; /* .exit */
1278 if (strcasecmp(s+1,"onion"))
1279 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1281 /* so it is .onion */
1282 *s = 0; /* null-terminate it */
1283 if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
1284 goto failed;
1285 tor_strlower(query);
1286 if (rend_valid_service_id(query)) {
1287 tor_strlower(address);
1288 return ONION_HOSTNAME; /* success */
1290 failed:
1291 /* otherwise, return to previous state and return 0 */
1292 *s = '.';
1293 return NORMAL_HOSTNAME;