Report HTTP reasons to directory clients. (Also, fix format on new TODO items)
[tor.git] / src / or / connection_or.c
blob675e9e89e8c0bea45f7767f2ac81650d9a4bbc79
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_or_c_id[] = "$Id$";
8 /**
9 * \file connection_or.c
10 * \brief Functions to handle OR connections, TLS handshaking, and
11 * cells on the network.
12 **/
14 #include "or.h"
16 /** How much clock skew do we tolerate when checking certificates for
17 * known routers? (sec) */
18 #define TIGHT_CERT_ALLOW_SKEW (90*60)
20 static int connection_tls_finish_handshake(connection_t *conn);
21 static int connection_or_process_cells_from_inbuf(connection_t *conn);
23 /**************************************************************/
25 /** Pack the cell_t host-order structure <b>src</b> into network-order
26 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
27 * wire format.
29 static void cell_pack(char *dest, const cell_t *src) {
30 *(uint16_t*)dest = htons(src->circ_id);
31 *(uint8_t*)(dest+2) = src->command;
32 memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
35 /** Unpack the network-order buffer <b>src</b> into a host-order
36 * cell_t structure <b>dest</b>.
38 static void cell_unpack(cell_t *dest, const char *src) {
39 dest->circ_id = ntohs(*(uint16_t*)(src));
40 dest->command = *(uint8_t*)(src+2);
41 memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
44 int connection_or_reached_eof(connection_t *conn) {
45 log_fn(LOG_INFO,"OR connection reached EOF. Closing.");
46 connection_mark_for_close(conn);
47 return 0;
50 /** Read conn's inbuf. If the http response from the proxy is all
51 * here, make sure it's good news, and begin the tls handshake. If
52 * it's bad news, close the connection and return -1. Else return 0
53 * and hope for better luck next time.
55 static int
56 connection_or_read_proxy_response(connection_t *conn) {
58 char *headers;
59 char *reason=NULL;
60 int status_code;
61 time_t date_header;
62 int compression;
64 switch (fetch_from_buf_http(conn->inbuf,
65 &headers, MAX_HEADERS_SIZE,
66 NULL, NULL, 10000)) {
67 case -1: /* overflow */
68 log_fn(LOG_WARN,"Your https proxy sent back an oversized response. Closing.");
69 return -1;
70 case 0:
71 log_fn(LOG_INFO,"https proxy response not all here yet. Waiting.");
72 return 0;
73 /* case 1, fall through */
76 if (parse_http_response(headers, &status_code, &date_header,
77 &compression, &reason) < 0) {
78 log_fn(LOG_WARN,"Unparseable headers (connecting to '%s'). Closing.",
79 conn->address);
80 tor_free(headers);
81 return -1;
83 if (!reason) reason = tor_strdup("[no reason given]");
85 if (status_code == 200) {
86 log_fn(LOG_INFO,
87 "HTTPS connect to '%s' successful! (200 \"%s\") Starting TLS.",
88 conn->address, reason);
89 tor_free(reason);
90 if (connection_tls_start_handshake(conn, 0) < 0) {
91 /* TLS handshaking error of some kind. */
92 connection_mark_for_close(conn);
94 return -1;
96 return 0;
98 /* else, bad news on the status code */
99 log_fn(LOG_WARN,"The https proxy sent back an unexpected status code %d (\"%s\"). Closing.",
100 status_code, reason);
101 tor_free(reason);
102 connection_mark_for_close(conn);
103 return -1;
106 /** Handle any new bytes that have come in on connection <b>conn</b>.
107 * If conn is in 'open' state, hand it to
108 * connection_or_process_cells_from_inbuf()
109 * (else do nothing).
111 int connection_or_process_inbuf(connection_t *conn) {
113 tor_assert(conn);
114 tor_assert(conn->type == CONN_TYPE_OR);
116 switch (conn->state) {
117 case OR_CONN_STATE_PROXY_READING:
118 return connection_or_read_proxy_response(conn);
119 case OR_CONN_STATE_OPEN:
120 return connection_or_process_cells_from_inbuf(conn);
121 default:
122 return 0; /* don't do anything */
126 /** Connection <b>conn</b> has finished writing and has no bytes left on
127 * its outbuf.
129 * Otherwise it's in state "open": stop writing and return.
131 * If <b>conn</b> is broken, mark it for close and return -1, else
132 * return 0.
134 int connection_or_finished_flushing(connection_t *conn) {
135 tor_assert(conn);
136 tor_assert(conn->type == CONN_TYPE_OR);
138 assert_connection_ok(conn,0);
140 switch (conn->state) {
141 case OR_CONN_STATE_PROXY_FLUSHING:
142 log_fn(LOG_DEBUG,"finished sending CONNECT to proxy.");
143 conn->state = OR_CONN_STATE_PROXY_READING;
144 connection_stop_writing(conn);
145 break;
146 case OR_CONN_STATE_OPEN:
147 connection_stop_writing(conn);
148 break;
149 default:
150 log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
151 #ifdef TOR_FRAGILE
152 tor_assert(0);
153 #endif
154 return -1;
156 return 0;
159 /** Connected handler for OR connections: begin the TLS handshake.
161 int connection_or_finished_connecting(connection_t *conn)
163 tor_assert(conn);
164 tor_assert(conn->type == CONN_TYPE_OR);
165 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
167 log_fn(LOG_INFO,"OR connect() to router at %s:%u finished.",
168 conn->address,conn->port);
170 if (get_options()->HttpsProxy) {
171 char buf[1024];
172 char addrbuf[INET_NTOA_BUF_LEN];
173 struct in_addr in;
175 in.s_addr = htonl(conn->addr);
176 tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
177 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
178 addrbuf, conn->port);
179 connection_write_to_buf(buf, strlen(buf), conn);
180 conn->state = OR_CONN_STATE_PROXY_FLUSHING;
181 return 0;
184 if (connection_tls_start_handshake(conn, 0) < 0) {
185 /* TLS handshaking error of some kind. */
186 connection_mark_for_close(conn);
187 return -1;
189 return 0;
192 /** Initialize <b>conn</b> to include all the relevant data from <b>router</b>.
193 * This function is called either from connection_or_connect(), if
194 * we initiated the connect, or from connection_tls_finish_handshake()
195 * if the other side initiated it.
197 static void
198 connection_or_init_conn_from_router(connection_t *conn, routerinfo_t *router) {
199 or_options_t *options = get_options();
201 conn->addr = router->addr;
202 conn->port = router->or_port;
203 conn->receiver_bucket = conn->bandwidth = (int)options->BandwidthBurst;
204 conn->identity_pkey = crypto_pk_dup_key(router->identity_pkey);
205 crypto_pk_get_digest(conn->identity_pkey, conn->identity_digest);
206 conn->nickname = tor_strdup(router->nickname);
207 tor_free(conn->address);
208 conn->address = tor_strdup(router->address);
211 static void
212 connection_or_init_conn_from_address(connection_t *conn,
213 uint32_t addr, uint16_t port,
214 const char *id_digest)
216 struct in_addr in;
217 const char *n;
218 or_options_t *options = get_options();
219 routerinfo_t *r = router_get_by_digest(id_digest);
220 if (r) {
221 connection_or_init_conn_from_router(conn,r);
222 return;
224 conn->addr = addr;
225 conn->port = port;
226 /* This next part isn't really right, but it's good enough for now. */
227 conn->receiver_bucket = conn->bandwidth = (int)options->BandwidthBurst;
228 memcpy(conn->identity_digest, id_digest, DIGEST_LEN);
229 /* If we're an authoritative directory server, we may know a
230 * nickname for this router. */
231 n = dirserv_get_nickname_by_digest(id_digest);
232 if (n) {
233 conn->nickname = tor_strdup(n);
234 } else {
235 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
236 conn->nickname[0] = '$';
237 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
238 conn->identity_digest, DIGEST_LEN);
240 tor_free(conn->address);
241 in.s_addr = htonl(addr);
243 conn->address = tor_malloc(INET_NTOA_BUF_LEN);
244 tor_inet_ntoa(&in,conn->address,INET_NTOA_BUF_LEN);
247 void
248 connection_or_update_nickname(connection_t *conn)
250 routerinfo_t *r;
251 const char *n;
253 tor_assert(conn);
254 tor_assert(conn->type == CONN_TYPE_OR);
255 n = dirserv_get_nickname_by_digest(conn->identity_digest);
256 if (n) {
257 if (!conn->nickname || strcmp(conn->nickname, n)) {
258 tor_free(conn->nickname);
259 conn->nickname = tor_strdup(n);
261 return;
263 r = router_get_by_digest(conn->identity_digest);
264 if (r && r->is_verified) {
265 if (!conn->nickname || strcmp(conn->nickname, r->nickname)) {
266 tor_free(conn->nickname);
267 conn->nickname = tor_strdup(r->nickname);
269 return;
271 if (conn->nickname[0] != '$') {
272 tor_free(conn->nickname);
273 conn->nickname = tor_malloc(HEX_DIGEST_LEN+1);
274 base16_encode(conn->nickname, HEX_DIGEST_LEN+1,
275 conn->identity_digest, DIGEST_LEN);
279 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
280 * handshake with an OR with identity digest <b>id_digest</b>.
282 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
283 * return that connection. If the connect() is in progress, set the
284 * new conn's state to 'connecting' and return it. If connect() succeeds,
285 * call * connection_tls_start_handshake() on it.
287 * This function is called from router_retry_connections(), for
288 * ORs connecting to ORs, and circuit_establish_circuit(), for
289 * OPs connecting to ORs.
291 * Return the launched conn, or NULL if it failed.
293 connection_t *connection_or_connect(uint32_t addr, uint16_t port,
294 const char *id_digest) {
295 connection_t *conn;
296 routerinfo_t *me;
297 or_options_t *options = get_options();
299 tor_assert(id_digest);
301 if (server_mode(options) && (me=router_get_my_routerinfo()) &&
302 !memcmp(me->identity_digest, id_digest,DIGEST_LEN)) {
303 log_fn(LOG_WARN,"Bug: Client asked me to connect to myself! Refusing.");
304 return NULL;
307 /* this function should never be called if we're already connected to
308 * id_digest, but check first to be sure */
309 /*XXX this is getting called, at least by dirservers. */
310 conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
311 if (conn) {
312 tor_assert(conn->nickname);
313 log_fn(LOG_WARN,"Asked me to connect to router '%s', but there's already a connection.", conn->nickname);
314 return conn;
317 conn = connection_new(CONN_TYPE_OR);
319 /* set up conn so it's got all the data we need to remember */
320 connection_or_init_conn_from_address(conn, addr, port, id_digest);
321 conn->state = OR_CONN_STATE_CONNECTING;
322 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED);
324 if (options->HttpsProxy) {
325 /* we shouldn't connect directly. use the https proxy instead. */
326 addr = options->HttpsProxyAddr;
327 port = options->HttpsProxyPort;
330 switch (connection_connect(conn, conn->address, addr, port)) {
331 case -1:
332 if (!options->HttpsProxy)
333 router_mark_as_down(conn->identity_digest);
334 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
335 connection_free(conn);
336 return NULL;
337 case 0:
338 connection_watch_events(conn, EV_READ | EV_WRITE);
339 /* writable indicates finish, readable indicates broken link,
340 error indicates broken link on windows */
341 return conn;
342 /* case 1: fall through */
345 if (connection_or_finished_connecting(conn) < 0) {
346 /* already marked for close */
347 return NULL;
349 return conn;
352 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
353 * we initiated the connection, else it's 1.
355 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and pass
356 * <b>conn</b> to connection_tls_continue_handshake().
358 * Return -1 if <b>conn</b> is broken, else return 0.
360 int connection_tls_start_handshake(connection_t *conn, int receiving) {
361 conn->state = OR_CONN_STATE_HANDSHAKING;
362 conn->tls = tor_tls_new(conn->s, receiving, 0);
363 if (!conn->tls) {
364 log_fn(LOG_WARN,"tor_tls_new failed. Closing.");
365 return -1;
367 connection_start_reading(conn);
368 log_fn(LOG_DEBUG,"starting the handshake");
369 if (connection_tls_continue_handshake(conn) < 0) {
370 return -1;
372 return 0;
375 /** Move forward with the tls handshake. If it finishes, hand
376 * <b>conn</b> to connection_tls_finish_handshake().
378 * Return -1 if <b>conn</b> is broken, else return 0.
380 int connection_tls_continue_handshake(connection_t *conn) {
381 switch (tor_tls_handshake(conn->tls)) {
382 case TOR_TLS_ERROR:
383 case TOR_TLS_CLOSE:
384 log_fn(LOG_INFO,"tls error. breaking.");
385 return -1;
386 case TOR_TLS_DONE:
387 return connection_tls_finish_handshake(conn);
388 case TOR_TLS_WANTWRITE:
389 connection_start_writing(conn);
390 log_fn(LOG_DEBUG,"wanted write");
391 return 0;
392 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
393 log_fn(LOG_DEBUG,"wanted read");
394 return 0;
396 return 0;
399 static char ZERO_DIGEST[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
401 int connection_or_nonopen_was_started_here(connection_t *conn)
403 tor_assert(sizeof(ZERO_DIGEST) == DIGEST_LEN);
404 tor_assert(conn->type == CONN_TYPE_OR);
406 if (!memcmp(ZERO_DIGEST, conn->identity_digest, DIGEST_LEN))
407 return 0;
408 else
409 return 1;
412 /** The tls handshake is finished.
414 * Make sure we are happy with the person we just handshaked with:
415 * If it's an OP (that is, it has no certificate), make sure I'm an OR.
416 * If it's an OR (it has a certificate), make sure it has a recognized
417 * nickname, and its cert is signed by the identity key of that nickname.
418 * If I initiated the connection, make sure it's the right guy; and if
419 * he initiated the connection, make sure he's not already connected.
421 * If he initiated the conn, also initialize conn from the information
422 * in router.
424 * If either of us is an OP, set bandwidth to the default OP bandwidth.
426 * If all is successful and he's an OR, then call circuit_n_conn_done()
427 * to handle events that have been pending on the tls handshake
428 * completion, and set the directory to be dirty (only matters if I'm
429 * an authdirserver).
431 static int
432 connection_tls_finish_handshake(connection_t *conn) {
433 routerinfo_t *router;
434 char nickname[MAX_NICKNAME_LEN+1];
435 connection_t *c;
436 crypto_pk_env_t *identity_rcvd=NULL;
437 char digest_rcvd[DIGEST_LEN];
438 or_options_t *options = get_options();
440 conn->state = OR_CONN_STATE_OPEN;
441 connection_watch_events(conn, EV_READ);
442 log_fn(LOG_DEBUG,"tls handshake done. verifying.");
443 if (! tor_tls_peer_has_cert(conn->tls)) {
444 log_fn(LOG_INFO,"Peer didn't send a cert! Closing.");
445 /* XXX we should handle this case rather than just closing. */
446 return -1;
448 if (tor_tls_get_peer_cert_nickname(conn->tls, nickname, sizeof(nickname))) {
449 log_fn(LOG_WARN,"Other side (%s:%d) has a cert without a valid nickname. Closing.",
450 conn->address, conn->port);
451 return -1;
453 log_fn(LOG_DEBUG, "Other side (%s:%d) claims to be router '%s'",
454 conn->address, conn->port, nickname);
456 if (tor_tls_verify(conn->tls, &identity_rcvd) < 0) {
457 log_fn(LOG_WARN,"Other side, which claims to be router '%s' (%s:%d), has a cert but it's invalid. Closing.",
458 nickname, conn->address, conn->port);
459 return -1;
461 #if 0
462 if (tor_tls_check_lifetime(conn->tls, LOOSE_CERT_ALLOW_SKEW)<0) {
463 log_fn(LOG_WARN,"Other side '%s' (%s:%d) has a very highly skewed clock, or an expired certificate. Closing.",
464 nickname, conn->address, conn->port);
465 return -1;
467 #endif
468 log_fn(LOG_DEBUG,"The router's cert is valid.");
469 crypto_pk_get_digest(identity_rcvd, digest_rcvd);
471 if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
472 conn->circ_id_type = CIRC_ID_TYPE_LOWER;
473 } else {
474 conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
476 crypto_free_pk_env(identity_rcvd);
478 router = router_get_by_nickname(nickname);
479 if (router && /* we know this nickname */
480 router->is_verified && /* make sure it's the right guy */
481 memcmp(digest_rcvd, router->identity_digest, DIGEST_LEN) != 0) {
482 log_fn(LOG_WARN, "Identity key not as expected for router claiming to be '%s' (%s:%d) ", nickname, conn->address, conn->port);
483 return -1;
485 #if 0
486 if (router_get_by_digest(digest_rcvd)) {
487 /* This is a known router; don't cut it slack with its clock skew. */
488 if (tor_tls_check_lifetime(conn->tls, TIGHT_CERT_ALLOW_SKEW)<0) {
489 log_fn(LOG_WARN,"Router '%s' (%s:%d) has a skewed clock, or an expired certificate; or else our clock is skewed. Closing.",
490 nickname, conn->address, conn->port);
491 return -1;
494 #endif
496 if (connection_or_nonopen_was_started_here(conn)) {
497 /* I initiated this connection. */
498 if (strcasecmp(conn->nickname, nickname)) {
499 log_fn(authdir_mode(options) ? LOG_WARN : LOG_INFO,
500 "Other side (%s:%d) is '%s', but we tried to connect to '%s'",
501 conn->address, conn->port, nickname, conn->nickname);
502 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
503 return -1;
505 } else {
506 if ((c=connection_get_by_identity_digest(digest_rcvd, CONN_TYPE_OR))) {
507 log_fn(LOG_INFO,"Router '%s' is already connected on fd %d. Dropping fd %d.", nickname, c->s, conn->s);
508 return -1;
510 connection_or_init_conn_from_address(conn,conn->addr,conn->port,digest_rcvd);
513 if (!server_mode(options)) { /* If I'm an OP... */
514 conn->receiver_bucket = conn->bandwidth = DEFAULT_BANDWIDTH_OP;
517 directory_set_dirty();
518 circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
519 /* Note the success */
520 rep_hist_note_connect_succeeded(conn->identity_digest, time(NULL));
521 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED);
522 return 0;
525 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s
526 * outbuf.
528 * (Commented out) If it's an OR conn, and an entire TLS record is
529 * ready, then try to flush the record now.
531 void connection_or_write_cell_to_buf(const cell_t *cell, connection_t *conn) {
532 char networkcell[CELL_NETWORK_SIZE];
533 char *n = networkcell;
535 tor_assert(cell);
536 tor_assert(conn);
537 tor_assert(connection_speaks_cells(conn));
539 cell_pack(n, cell);
541 connection_write_to_buf(n, CELL_NETWORK_SIZE, conn);
543 #if 0 /* commented out -- can we get away with not doing this,
544 * because we're already round-robining in handle_read?
546 #define MIN_TLS_FLUSHLEN 15872
547 /* openssl tls record size is 16383, this is close. The goal here is to
548 * push data out as soon as we know there's enough for a tls record, so
549 * during periods of high load we won't read the entire megabyte from
550 * input before pushing any data out. */
551 if (conn->outbuf_flushlen-CELL_NETWORK_SIZE < MIN_TLS_FLUSHLEN &&
552 conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
553 int extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
554 conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
555 if (connection_handle_write(conn) < 0) {
556 log_fn(LOG_WARN,"flushing failed.");
557 return;
559 if (extra) {
560 conn->outbuf_flushlen += extra;
561 connection_start_writing(conn);
564 #endif
568 /** Process cells from <b>conn</b>'s inbuf.
570 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
571 * and hand it to command_process_cell().
573 * Always return 0.
575 static int connection_or_process_cells_from_inbuf(connection_t *conn) {
576 char buf[CELL_NETWORK_SIZE];
577 cell_t cell;
579 loop:
580 log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object).",
581 conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls));
582 if (buf_datalen(conn->inbuf) < CELL_NETWORK_SIZE) /* entire response available? */
583 return 0; /* not yet */
585 connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, conn);
587 /* retrieve cell info from buf (create the host-order struct from the
588 * network-order string) */
589 cell_unpack(&cell, buf);
591 command_process_cell(&cell, conn);
593 goto loop; /* process the remainder of the buffer */