connection.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_c_id[] = "$Id$";
  7. /**
  8. * \file connection.c
  9. * \brief General high-level functions to handle reading and writing
  10. * on connections.
  11. **/
  12. #include "or.h"
  13. static int connection_create_listener(const char *bindaddress,
  14. uint16_t bindport, int type);
  15. static int connection_init_accepted_conn(connection_t *conn);
  16. static int connection_handle_listener_read(connection_t *conn, int new_type);
  17. static int connection_receiver_bucket_should_increase(connection_t *conn);
  18. static int connection_finished_flushing(connection_t *conn);
  19. static int connection_finished_connecting(connection_t *conn);
  20. static int connection_reached_eof(connection_t *conn);
  21. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  22. static int connection_process_inbuf(connection_t *conn, int package_partial);
  23. static int connection_bucket_read_limit(connection_t *conn);
  24. /**************************************************************/
  25. const char *
  26. conn_type_to_string(int type)
  27. {
  28. static char buf[64];
  29. switch (type) {
  30. case CONN_TYPE_OR_LISTENER: return "OR listener";
  31. case CONN_TYPE_OR: return "OR";
  32. case CONN_TYPE_EXIT: return "Exit";
  33. case CONN_TYPE_AP_LISTENER: return "App listener";
  34. case CONN_TYPE_AP: return "App";
  35. case CONN_TYPE_DIR_LISTENER: return "Dir listener";
  36. case CONN_TYPE_DIR: return "Dir";
  37. case CONN_TYPE_DNSWORKER: return "DNS worker";
  38. case CONN_TYPE_CPUWORKER: return "CPU worker";
  39. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  40. case CONN_TYPE_CONTROL: return "Control";
  41. default:
  42. log_fn(LOG_WARN, "Bug: unknown connection type %d", type);
  43. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  44. return buf;
  45. }
  46. }
  47. const char *
  48. conn_state_to_string(int type, int state) {
  49. static char buf[96];
  50. switch (type) {
  51. case CONN_TYPE_OR_LISTENER:
  52. case CONN_TYPE_AP_LISTENER:
  53. case CONN_TYPE_DIR_LISTENER:
  54. case CONN_TYPE_CONTROL_LISTENER:
  55. if (state == LISTENER_STATE_READY)
  56. return "ready";
  57. break;
  58. case CONN_TYPE_OR:
  59. switch (state) {
  60. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  61. case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
  62. case OR_CONN_STATE_PROXY_READING: return "proxy reading";
  63. case OR_CONN_STATE_HANDSHAKING: return "proxy reading";
  64. case OR_CONN_STATE_OPEN: return "open";
  65. }
  66. break;
  67. case CONN_TYPE_EXIT:
  68. switch (state) {
  69. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  70. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  71. case EXIT_CONN_STATE_OPEN: return "open";
  72. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  73. }
  74. break;
  75. case CONN_TYPE_AP:
  76. switch (state) {
  77. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for dest info";
  78. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  79. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  80. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for safe circuit";
  81. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect";
  82. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve";
  83. case AP_CONN_STATE_OPEN: return "open";
  84. }
  85. break;
  86. case CONN_TYPE_DIR:
  87. switch (state) {
  88. case DIR_CONN_STATE_CONNECTING: return "connecting";
  89. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  90. case DIR_CONN_STATE_CLIENT_READING: return "cleint reading";
  91. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  92. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  93. }
  94. break;
  95. case CONN_TYPE_DNSWORKER:
  96. switch (state) {
  97. case DNSWORKER_STATE_IDLE: return "idle";
  98. case DNSWORKER_STATE_BUSY: return "busy";
  99. }
  100. break;
  101. case CONN_TYPE_CPUWORKER:
  102. switch (state) {
  103. case CPUWORKER_STATE_IDLE: return "idle";
  104. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  105. }
  106. break;
  107. case CONN_TYPE_CONTROL:
  108. switch (state) {
  109. case CONTROL_CONN_STATE_OPEN: return "open";
  110. case CONTROL_CONN_STATE_NEEDAUTH: return "waiting for authentication";
  111. }
  112. break;
  113. }
  114. log_fn(LOG_WARN, "Bug: unknown connection state %d (type %d)", state, type);
  115. tor_snprintf(buf, sizeof(buf),
  116. "unknown state [%d] on unknown [%s] connection",
  117. state, conn_type_to_string(type));
  118. return buf;
  119. }
  120. /** Allocate space for a new connection_t. This function just initializes
  121. * conn; you must call connection_add() to link it into the main array.
  122. *
  123. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  124. * -1 to signify they are not yet assigned.
  125. *
  126. * If conn is not a listener type, allocate buffers for it. If it's
  127. * an AP type, allocate space to store the socks_request.
  128. *
  129. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  130. *
  131. * Initialize conn's timestamps to now.
  132. */
  133. connection_t *connection_new(int type) {
  134. static uint32_t n_connections_allocated = 0;
  135. connection_t *conn;
  136. time_t now = time(NULL);
  137. conn = tor_malloc_zero(sizeof(connection_t));
  138. conn->magic = CONNECTION_MAGIC;
  139. conn->s = -1; /* give it a default of 'not used' */
  140. conn->poll_index = -1; /* also default to 'not used' */
  141. conn->global_identifier = n_connections_allocated++;
  142. conn->type = type;
  143. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  144. conn->inbuf = buf_new();
  145. conn->outbuf = buf_new();
  146. }
  147. if (type == CONN_TYPE_AP) {
  148. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  149. }
  150. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  151. conn->timestamp_created = now;
  152. conn->timestamp_lastread = now;
  153. conn->timestamp_lastwritten = now;
  154. return conn;
  155. }
  156. /** Tell libevent that we don't care about <b>conn</b> any more. */
  157. void
  158. connection_unregister(connection_t *conn)
  159. {
  160. if (conn->read_event) {
  161. if (event_del(conn->read_event))
  162. log_fn(LOG_WARN, "Error removing read event for %d", conn->s);
  163. tor_free(conn->read_event);
  164. }
  165. if (conn->write_event) {
  166. if (event_del(conn->write_event))
  167. log_fn(LOG_WARN, "Error removing write event for %d", conn->s);
  168. tor_free(conn->write_event);
  169. }
  170. }
  171. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
  172. * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
  173. * is an OR or OP connection.
  174. */
  175. static void
  176. _connection_free(connection_t *conn) {
  177. tor_assert(conn->magic == CONNECTION_MAGIC);
  178. if (!connection_is_listener(conn)) {
  179. buf_free(conn->inbuf);
  180. buf_free(conn->outbuf);
  181. }
  182. tor_free(conn->address);
  183. tor_free(conn->chosen_exit_name);
  184. if (connection_speaks_cells(conn)) {
  185. if (conn->tls) {
  186. tor_tls_free(conn->tls);
  187. conn->tls = NULL;
  188. }
  189. }
  190. if (conn->identity_pkey)
  191. crypto_free_pk_env(conn->identity_pkey);
  192. tor_free(conn->nickname);
  193. tor_free(conn->socks_request);
  194. tor_free(conn->incoming_cmd);
  195. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  196. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  197. if (conn->s >= 0) {
  198. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  199. tor_close_socket(conn->s);
  200. }
  201. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  202. tor_free(conn);
  203. }
  204. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  205. */
  206. void connection_free(connection_t *conn) {
  207. tor_assert(conn);
  208. tor_assert(!connection_is_on_closeable_list(conn));
  209. tor_assert(!connection_in_array(conn));
  210. if (connection_speaks_cells(conn)) {
  211. if (conn->state == OR_CONN_STATE_OPEN)
  212. directory_set_dirty();
  213. }
  214. connection_unregister(conn);
  215. _connection_free(conn);
  216. }
  217. /** Call _connection_free() on every connection in our array.
  218. * This is used by cpuworkers and dnsworkers when they fork,
  219. * so they don't keep resources held open (especially sockets).
  220. *
  221. * Don't do the checks in connection_free(), because they will
  222. * fail.
  223. */
  224. void connection_free_all(void) {
  225. int i, n;
  226. connection_t **carray;
  227. get_connection_array(&carray,&n);
  228. for (i=0;i<n;i++)
  229. _connection_free(carray[i]);
  230. }
  231. /** Do any cleanup needed:
  232. * - Directory conns that failed to fetch a rendezvous descriptor
  233. * need to inform pending rendezvous streams.
  234. * - OR conns need to call rep_hist_note_*() to record status.
  235. * - AP conns need to send a socks reject if necessary.
  236. * - Exit conns need to call connection_dns_remove() if necessary.
  237. * - AP and Exit conns need to send an end cell if they can.
  238. * - DNS conns need to fail any resolves that are pending on them.
  239. */
  240. void connection_about_to_close_connection(connection_t *conn)
  241. {
  242. circuit_t *circ;
  243. assert(conn->marked_for_close);
  244. if (CONN_IS_EDGE(conn)) {
  245. if (!conn->has_sent_end) {
  246. log_fn(LOG_WARN,"Harmless bug: Edge connection (marked at %s:%d) hasn't sent end yet?", conn->marked_for_close_file, conn->marked_for_close);
  247. tor_fragile_assert();
  248. }
  249. }
  250. switch (conn->type) {
  251. case CONN_TYPE_DIR:
  252. if (conn->state == DIR_CONN_STATE_CONNECTING) {
  253. /* it's a directory server and connecting failed: forget about
  254. this router */
  255. connection_dir_connect_failed(conn);
  256. }
  257. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  258. rend_client_desc_here(conn->rend_query); /* give it a try */
  259. break;
  260. case CONN_TYPE_OR:
  261. /* Remember why we're closing this connection. */
  262. if (conn->state != OR_CONN_STATE_OPEN) {
  263. if (connection_or_nonopen_was_started_here(conn)) {
  264. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  265. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  266. }
  267. } else if (conn->hold_open_until_flushed) {
  268. /* XXXX009 We used to have an arg that told us whether we closed the
  269. * connection on purpose or not. Can we use hold_open_until_flushed
  270. * instead? We only set it when we are intentionally closing a
  271. * connection. -NM
  272. *
  273. * (Of course, now things we set to close which expire rather than
  274. * flushing still get noted as dead, not disconnected. But this is an
  275. * improvement. -NM
  276. */
  277. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  278. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  279. } else if (conn->identity_digest) {
  280. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  281. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  282. }
  283. break;
  284. case CONN_TYPE_AP:
  285. if (conn->socks_request->has_finished == 0) {
  286. /* since conn gets removed right after this function finishes,
  287. * there's no point trying to send back a reply at this point. */
  288. log_fn(LOG_WARN,"Bug: Closing stream (marked at %s:%d) without sending back a socks reply.",
  289. conn->marked_for_close_file, conn->marked_for_close);
  290. } else {
  291. control_event_stream_status(conn, STREAM_EVENT_CLOSED);
  292. }
  293. break;
  294. case CONN_TYPE_EXIT:
  295. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  296. circ = circuit_get_by_edge_conn(conn);
  297. if (circ)
  298. circuit_detach_stream(circ, conn);
  299. connection_dns_remove(conn);
  300. }
  301. break;
  302. case CONN_TYPE_DNSWORKER:
  303. if (conn->state == DNSWORKER_STATE_BUSY) {
  304. dns_cancel_pending_resolve(conn->address);
  305. }
  306. break;
  307. }
  308. }
  309. /** Close the underlying socket for <b>conn</b>, so we don't try to
  310. * flush it. Must be used in conjunction with (right before)
  311. * connection_mark_for_close().
  312. */
  313. void connection_close_immediate(connection_t *conn)
  314. {
  315. assert_connection_ok(conn,0);
  316. if (conn->s < 0) {
  317. log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
  318. tor_fragile_assert();
  319. return;
  320. }
  321. if (conn->outbuf_flushlen) {
  322. log_fn(LOG_INFO,"fd %d, type %s, state %s, %d bytes on outbuf.",
  323. conn->s, conn_type_to_string(conn->type),
  324. conn_state_to_string(conn->type, conn->state),
  325. (int)conn->outbuf_flushlen);
  326. }
  327. connection_unregister(conn);
  328. tor_close_socket(conn->s);
  329. conn->s = -1;
  330. if (!connection_is_listener(conn)) {
  331. buf_clear(conn->outbuf);
  332. conn->outbuf_flushlen = 0;
  333. }
  334. }
  335. /** Mark <b>conn</b> to be closed next time we loop through
  336. * conn_close_if_marked() in main.c. */
  337. void
  338. _connection_mark_for_close(connection_t *conn, int line, const char *file)
  339. {
  340. assert_connection_ok(conn,0);
  341. tor_assert(line);
  342. tor_assert(file);
  343. if (conn->marked_for_close) {
  344. log(LOG_WARN, "Duplicate call to connection_mark_for_close at %s:%d"
  345. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  346. conn->marked_for_close);
  347. tor_fragile_assert();
  348. return;
  349. }
  350. conn->marked_for_close = line;
  351. conn->marked_for_close_file = file;
  352. add_connection_to_closeable_list(conn);
  353. /* in case we're going to be held-open-til-flushed, reset
  354. * the number of seconds since last successful write, so
  355. * we get our whole 15 seconds */
  356. conn->timestamp_lastwritten = time(NULL);
  357. }
  358. /** Find each connection that has hold_open_until_flushed set to
  359. * 1 but hasn't written in the past 15 seconds, and set
  360. * hold_open_until_flushed to 0. This means it will get cleaned
  361. * up in the next loop through close_if_marked() in main.c.
  362. */
  363. void connection_expire_held_open(void)
  364. {
  365. connection_t **carray, *conn;
  366. int n, i;
  367. time_t now;
  368. now = time(NULL);
  369. get_connection_array(&carray, &n);
  370. for (i = 0; i < n; ++i) {
  371. conn = carray[i];
  372. /* If we've been holding the connection open, but we haven't written
  373. * for 15 seconds...
  374. */
  375. if (conn->hold_open_until_flushed) {
  376. tor_assert(conn->marked_for_close);
  377. if (now - conn->timestamp_lastwritten >= 15) {
  378. log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %s).",
  379. conn->s, conn_type_to_string(conn->type),
  380. conn_state_to_string(conn->type, conn->state));
  381. conn->hold_open_until_flushed = 0;
  382. }
  383. }
  384. }
  385. }
  386. /** Bind a new non-blocking socket listening to
  387. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  388. * (of type <b>type</b>) to the connection array.
  389. *
  390. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  391. * use bindport.
  392. */
  393. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  394. struct sockaddr_in bindaddr; /* where to bind */
  395. connection_t *conn;
  396. uint16_t usePort;
  397. uint32_t addr;
  398. int s; /* the socket we're going to make */
  399. #ifndef MS_WINDOWS
  400. int one=1;
  401. #endif
  402. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  403. if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
  404. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  405. return -1;
  406. }
  407. if (usePort==0)
  408. usePort = bindport;
  409. bindaddr.sin_addr.s_addr = htonl(addr);
  410. bindaddr.sin_family = AF_INET;
  411. bindaddr.sin_port = htons((uint16_t) usePort);
  412. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  413. if (s < 0) {
  414. log_fn(LOG_WARN,"Socket creation failed.");
  415. return -1;
  416. } else if (!SOCKET_IS_POLLABLE(s)) {
  417. log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
  418. tor_close_socket(s);
  419. return -1;
  420. }
  421. #ifndef MS_WINDOWS
  422. /* REUSEADDR on normal places means you can rebind to the port
  423. * right after somebody else has let it go. But REUSEADDR on win32
  424. * means you can bind to the port _even when somebody else
  425. * already has it bound_. So, don't do that on Win32. */
  426. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  427. #endif
  428. if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  429. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  430. tor_socket_strerror(tor_socket_errno(s)));
  431. return -1;
  432. }
  433. if (listen(s,SOMAXCONN) < 0) {
  434. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  435. tor_socket_strerror(tor_socket_errno(s)));
  436. return -1;
  437. }
  438. set_socket_nonblocking(s);
  439. conn = connection_new(type);
  440. conn->s = s;
  441. if (connection_add(conn) < 0) { /* no space, forget it */
  442. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  443. connection_free(conn);
  444. return -1;
  445. }
  446. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string(type), usePort);
  447. conn->state = LISTENER_STATE_READY;
  448. connection_start_reading(conn);
  449. return 0;
  450. }
  451. /** Do basic sanity checking on a newly received socket. Return 0
  452. * if it looks ok, else return -1. */
  453. static int
  454. check_sockaddr_in(struct sockaddr *sa, int len, int level)
  455. {
  456. int ok = 1;
  457. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  458. if (len != sizeof(struct sockaddr_in)) {
  459. log_fn(level, "Length of address not as expected: %d vs %d",
  460. len,(int)sizeof(struct sockaddr_in));
  461. ok = 0;
  462. }
  463. if (sa->sa_family != AF_INET) {
  464. log_fn(level, "Family of address not as expected: %d vs %d",
  465. sa->sa_family, AF_INET);
  466. ok = 0;
  467. }
  468. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  469. log_fn(level, "Address for new connection has address/port equal to zero.");
  470. ok = 0;
  471. }
  472. return ok ? 0 : -1;
  473. }
  474. /** The listener connection <b>conn</b> told poll() it wanted to read.
  475. * Call accept() on conn-\>s, and add the new connection if necessary.
  476. */
  477. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  478. int news; /* the new socket */
  479. connection_t *newconn;
  480. /* information about the remote peer when connecting to other routers */
  481. struct sockaddr_in remote;
  482. char addrbuf[256];
  483. /* length of the remote address. Must be whatever accept() needs. */
  484. socklen_t remotelen = 256;
  485. char tmpbuf[INET_NTOA_BUF_LEN];
  486. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  487. memset(addrbuf, 0, sizeof(addrbuf));
  488. news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
  489. if (!SOCKET_IS_POLLABLE(news)) {
  490. /* accept() error, or too many conns to poll */
  491. int e;
  492. if (news>=0) {
  493. /* Too many conns to poll. */
  494. log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
  495. tor_close_socket(news);
  496. return 0;
  497. }
  498. e = tor_socket_errno(conn->s);
  499. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  500. return 0; /* he hung up before we could accept(). that's fine. */
  501. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  502. log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
  503. tor_socket_strerror(e));
  504. return 0;
  505. }
  506. /* else there was a real error. */
  507. log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
  508. tor_socket_strerror(e));
  509. connection_mark_for_close(conn);
  510. return -1;
  511. }
  512. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  513. set_socket_nonblocking(news);
  514. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
  515. log_fn(LOG_INFO, "accept() returned a strange address; trying getsockname().");
  516. remotelen=256;
  517. memset(addrbuf, 0, sizeof(addrbuf));
  518. if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
  519. log_fn(LOG_WARN, "getsockname() failed.");
  520. } else {
  521. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_WARN)<0) {
  522. log_fn(LOG_WARN,"Something's wrong with this conn. Closing it.");
  523. tor_close_socket(news);
  524. return 0;
  525. }
  526. }
  527. }
  528. memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
  529. /* process entrance policies here, before we even create the connection */
  530. if (new_type == CONN_TYPE_AP) {
  531. /* check sockspolicy to see if we should accept it */
  532. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  533. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  534. log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
  535. tmpbuf);
  536. tor_close_socket(news);
  537. return 0;
  538. }
  539. }
  540. if (new_type == CONN_TYPE_DIR) {
  541. /* check dirpolicy to see if we should accept it */
  542. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  543. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  544. log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
  545. tmpbuf);
  546. tor_close_socket(news);
  547. return 0;
  548. }
  549. }
  550. newconn = connection_new(new_type);
  551. newconn->s = news;
  552. /* remember the remote address */
  553. newconn->address = tor_malloc(INET_NTOA_BUF_LEN);
  554. tor_inet_ntoa(&remote.sin_addr, newconn->address, INET_NTOA_BUF_LEN);
  555. newconn->addr = ntohl(remote.sin_addr.s_addr);
  556. newconn->port = ntohs(remote.sin_port);
  557. if (connection_add(newconn) < 0) { /* no space, forget it */
  558. connection_free(newconn);
  559. return 0; /* no need to tear down the parent */
  560. }
  561. if (connection_init_accepted_conn(newconn) < 0) {
  562. connection_mark_for_close(newconn);
  563. return 0;
  564. }
  565. return 0;
  566. }
  567. /** Initialize states for newly accepted connection <b>conn</b>.
  568. * If conn is an OR, start the tls handshake.
  569. */
  570. static int connection_init_accepted_conn(connection_t *conn) {
  571. connection_start_reading(conn);
  572. switch (conn->type) {
  573. case CONN_TYPE_OR:
  574. return connection_tls_start_handshake(conn, 1);
  575. case CONN_TYPE_AP:
  576. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  577. break;
  578. case CONN_TYPE_DIR:
  579. conn->purpose = DIR_PURPOSE_SERVER;
  580. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  581. break;
  582. case CONN_TYPE_CONTROL:
  583. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  584. break;
  585. }
  586. return 0;
  587. }
  588. /** Take conn, make a nonblocking socket; try to connect to
  589. * addr:port (they arrive in *host order*). If fail, return -1. Else
  590. * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  591. *
  592. * address is used to make the logs useful.
  593. *
  594. * On success, add conn to the list of polled connections.
  595. */
  596. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  597. int s;
  598. struct sockaddr_in dest_addr;
  599. or_options_t *options = get_options();
  600. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  601. if (s < 0) {
  602. log_fn(LOG_WARN,"Error creating network socket: %s",
  603. tor_socket_strerror(tor_socket_errno(-1)));
  604. return -1;
  605. } else if (!SOCKET_IS_POLLABLE(s)) {
  606. log_fn(LOG_WARN,
  607. "Too many connections; can't create pollable connection to %s",
  608. safe_str(address));
  609. tor_close_socket(s);
  610. return -1;
  611. }
  612. if (options->OutboundBindAddress) {
  613. struct sockaddr_in ext_addr;
  614. memset(&ext_addr, 0, sizeof(ext_addr));
  615. ext_addr.sin_family = AF_INET;
  616. ext_addr.sin_port = 0;
  617. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  618. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  619. options->OutboundBindAddress);
  620. } else {
  621. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  622. log_fn(LOG_WARN,"Error binding network socket: %s",
  623. tor_socket_strerror(tor_socket_errno(s)));
  624. return -1;
  625. }
  626. }
  627. }
  628. set_socket_nonblocking(s);
  629. memset(&dest_addr,0,sizeof(dest_addr));
  630. dest_addr.sin_family = AF_INET;
  631. dest_addr.sin_port = htons(port);
  632. dest_addr.sin_addr.s_addr = htonl(addr);
  633. log_fn(LOG_DEBUG,"Connecting to %s:%u.",safe_str(address),port);
  634. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  635. int e = tor_socket_errno(s);
  636. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  637. /* yuck. kill it. */
  638. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",safe_str(address),port,
  639. tor_socket_strerror(e));
  640. tor_close_socket(s);
  641. return -1;
  642. } else {
  643. /* it's in progress. set state appropriately and return. */
  644. conn->s = s;
  645. if (connection_add(conn) < 0) /* no space, forget it */
  646. return -1;
  647. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  648. return 0;
  649. }
  650. }
  651. /* it succeeded. we're connected. */
  652. log_fn(LOG_INFO,"Connection to %s:%u established.",safe_str(address),port);
  653. conn->s = s;
  654. if (connection_add(conn) < 0) /* no space, forget it */
  655. return -1;
  656. return 1;
  657. }
  658. /** If there exist any listeners of type <b>type</b> in the connection
  659. * array, mark them for close.
  660. */
  661. static void listener_close_if_present(int type) {
  662. connection_t *conn;
  663. connection_t **carray;
  664. int i,n;
  665. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  666. type == CONN_TYPE_AP_LISTENER ||
  667. type == CONN_TYPE_DIR_LISTENER ||
  668. type == CONN_TYPE_CONTROL_LISTENER);
  669. get_connection_array(&carray,&n);
  670. for (i=0;i<n;i++) {
  671. conn = carray[i];
  672. if (conn->type == type && !conn->marked_for_close) {
  673. connection_close_immediate(conn);
  674. connection_mark_for_close(conn);
  675. }
  676. }
  677. }
  678. /**
  679. * Launch any configured listener connections of type <b>type</b>. (A
  680. * listener is configured if <b>port_option</b> is non-zero. If any
  681. * BindAddress configuration options are given in <b>cfg</b>, create a
  682. * connection binding to each one. Otherwise, create a single
  683. * connection binding to the address <b>default_addr</b>.)
  684. *
  685. * If <b>force</b> is true, close and re-open all listener connections.
  686. * Otherwise, only relaunch the listeners of this type if the number of
  687. * existing connections is not as configured (e.g., because one died).
  688. */
  689. static int retry_listeners(int type, struct config_line_t *cfg,
  690. int port_option, const char *default_addr,
  691. int force)
  692. {
  693. if (!force) {
  694. int want, have, n_conn, i;
  695. struct config_line_t *c;
  696. connection_t *conn;
  697. connection_t **carray;
  698. /* How many should there be? */
  699. if (cfg && port_option) {
  700. want = 0;
  701. for (c = cfg; c; c = c->next)
  702. ++want;
  703. } else if (port_option) {
  704. want = 1;
  705. } else {
  706. want = 0;
  707. }
  708. /* How many are there actually? */
  709. have = 0;
  710. get_connection_array(&carray,&n_conn);
  711. for (i=0;i<n_conn;i++) {
  712. conn = carray[i];
  713. if (conn->type == type && !conn->marked_for_close)
  714. ++have;
  715. }
  716. /* If we have the right number of listeners, do nothing. */
  717. if (have == want)
  718. return 0;
  719. /* Otherwise, warn the user and relaunch. */
  720. log_fn(LOG_NOTICE,"We have %d %s(s) open, but we want %d; relaunching.",
  721. have, conn_type_to_string(type), want);
  722. }
  723. listener_close_if_present(type);
  724. if (port_option) {
  725. if (!cfg) {
  726. if (connection_create_listener(default_addr, (uint16_t) port_option,
  727. type)<0)
  728. return -1;
  729. } else {
  730. for ( ; cfg; cfg = cfg->next) {
  731. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  732. type)<0)
  733. return -1;
  734. }
  735. }
  736. }
  737. return 0;
  738. }
  739. /** (Re)launch listeners for each port you should have open. If
  740. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  741. * is false, then only relaunch listeners when we have the wrong number of
  742. * connections for a given type.
  743. */
  744. int retry_all_listeners(int force) {
  745. or_options_t *options = get_options();
  746. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
  747. options->ORPort, "0.0.0.0", force)<0)
  748. return -1;
  749. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
  750. options->DirPort, "0.0.0.0", force)<0)
  751. return -1;
  752. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
  753. options->SocksPort, "127.0.0.1", force)<0)
  754. return -1;
  755. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  756. options->ControlPort, "127.0.0.1", force)<0)
  757. return -1;
  758. return 0;
  759. }
  760. extern int global_read_bucket, global_write_bucket;
  761. /** How many bytes at most can we read onto this connection? */
  762. static int connection_bucket_read_limit(connection_t *conn) {
  763. int at_most;
  764. /* do a rudimentary round-robin so one circuit can't hog a connection */
  765. if (connection_speaks_cells(conn)) {
  766. at_most = 32*(CELL_NETWORK_SIZE);
  767. } else {
  768. at_most = 32*(RELAY_PAYLOAD_SIZE);
  769. }
  770. if (at_most > global_read_bucket)
  771. at_most = global_read_bucket;
  772. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  773. if (at_most > conn->receiver_bucket)
  774. at_most = conn->receiver_bucket;
  775. if (at_most < 0)
  776. return 0;
  777. return at_most;
  778. }
  779. /** We just read num_read onto conn. Decrement buckets appropriately. */
  780. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  781. global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
  782. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  783. conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
  784. }
  785. }
  786. static void connection_consider_empty_buckets(connection_t *conn) {
  787. if (global_read_bucket <= 0) {
  788. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  789. conn->wants_to_read = 1;
  790. connection_stop_reading(conn);
  791. return;
  792. }
  793. if (connection_speaks_cells(conn) &&
  794. conn->state == OR_CONN_STATE_OPEN &&
  795. conn->receiver_bucket <= 0) {
  796. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  797. conn->wants_to_read = 1;
  798. connection_stop_reading(conn);
  799. }
  800. }
  801. /** Initialize the global read bucket to options->BandwidthBurst,
  802. * and current_time to the current time. */
  803. void connection_bucket_init(void) {
  804. or_options_t *options = get_options();
  805. global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  806. global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  807. }
  808. /** A second has rolled over; increment buckets appropriately. */
  809. void connection_bucket_refill(struct timeval *now) {
  810. int i, n;
  811. connection_t *conn;
  812. connection_t **carray;
  813. or_options_t *options = get_options();
  814. /* refill the global buckets */
  815. if (global_read_bucket < (int)options->BandwidthBurst) {
  816. global_read_bucket += (int)options->BandwidthRate;
  817. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  818. }
  819. if (global_write_bucket < (int)options->BandwidthBurst) {
  820. global_write_bucket += (int)options->BandwidthRate;
  821. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  822. }
  823. /* refill the per-connection buckets */
  824. get_connection_array(&carray,&n);
  825. for (i=0;i<n;i++) {
  826. conn = carray[i];
  827. if (connection_receiver_bucket_should_increase(conn)) {
  828. conn->receiver_bucket = conn->bandwidth;
  829. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  830. }
  831. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  832. && global_read_bucket > 0 /* and we're allowed to read */
  833. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  834. * not the best place to check this.) */
  835. && (!connection_speaks_cells(conn) ||
  836. conn->state != OR_CONN_STATE_OPEN ||
  837. conn->receiver_bucket > 0)) {
  838. /* and either a non-cell conn or a cell conn with non-empty bucket */
  839. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  840. conn->wants_to_read = 0;
  841. connection_start_reading(conn);
  842. if (conn->wants_to_write == 1) {
  843. conn->wants_to_write = 0;
  844. connection_start_writing(conn);
  845. }
  846. }
  847. }
  848. }
  849. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  850. * should add another pile of tokens to it?
  851. */
  852. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  853. tor_assert(conn);
  854. if (!connection_speaks_cells(conn))
  855. return 0; /* edge connections don't use receiver_buckets */
  856. if (conn->state != OR_CONN_STATE_OPEN)
  857. return 0; /* only open connections play the rate limiting game */
  858. if (conn->receiver_bucket >= conn->bandwidth)
  859. return 0;
  860. return 1;
  861. }
  862. /** Read bytes from conn-\>s and process them.
  863. *
  864. * This function gets called from conn_read() in main.c, either
  865. * when poll() has declared that conn wants to read, or (for OR conns)
  866. * when there are pending TLS bytes.
  867. *
  868. * It calls connection_read_to_buf() to bring in any new bytes,
  869. * and then calls connection_process_inbuf() to process them.
  870. *
  871. * Mark the connection and return -1 if you want to close it, else
  872. * return 0.
  873. */
  874. int connection_handle_read(connection_t *conn) {
  875. int max_to_read=-1, try_to_read;
  876. conn->timestamp_lastread = time(NULL);
  877. switch (conn->type) {
  878. case CONN_TYPE_OR_LISTENER:
  879. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  880. case CONN_TYPE_AP_LISTENER:
  881. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  882. case CONN_TYPE_DIR_LISTENER:
  883. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  884. case CONN_TYPE_CONTROL_LISTENER:
  885. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  886. }
  887. loop_again:
  888. try_to_read = max_to_read;
  889. tor_assert(!conn->marked_for_close);
  890. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  891. /* There's a read error; kill the connection.*/
  892. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  893. if (CONN_IS_EDGE(conn)) {
  894. connection_edge_end_errno(conn, conn->cpath_layer);
  895. }
  896. connection_mark_for_close(conn);
  897. return -1;
  898. }
  899. if (CONN_IS_EDGE(conn) &&
  900. try_to_read != max_to_read) {
  901. /* instruct it not to try to package partial cells. */
  902. if (connection_process_inbuf(conn, 0) < 0) {
  903. return -1;
  904. }
  905. if (!conn->marked_for_close &&
  906. connection_is_reading(conn) &&
  907. !conn->inbuf_reached_eof &&
  908. max_to_read > 0)
  909. goto loop_again; /* try reading again, in case more is here now */
  910. }
  911. /* one last try, packaging partial cells and all. */
  912. if (!conn->marked_for_close &&
  913. connection_process_inbuf(conn, 1) < 0) {
  914. return -1;
  915. }
  916. if (!conn->marked_for_close &&
  917. conn->inbuf_reached_eof &&
  918. connection_reached_eof(conn) < 0) {
  919. return -1;
  920. }
  921. return 0;
  922. }
  923. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  924. * directly or via TLS. Reduce the token buckets by the number of
  925. * bytes read.
  926. *
  927. * If *max_to_read is -1, then decide it ourselves, else go with the
  928. * value passed to us. When returning, if it's changed, subtract the
  929. * number of bytes we read from *max_to_read.
  930. *
  931. * Return -1 if we want to break conn, else return 0.
  932. */
  933. static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
  934. int result, at_most = *max_to_read;
  935. size_t bytes_in_buf, more_to_read;
  936. if (at_most == -1) { /* we need to initialize it */
  937. /* how many bytes are we allowed to read? */
  938. at_most = connection_bucket_read_limit(conn);
  939. }
  940. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  941. again:
  942. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  943. more_to_read = at_most - bytes_in_buf;
  944. at_most = bytes_in_buf;
  945. } else {
  946. more_to_read = 0;
  947. }
  948. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  949. int pending;
  950. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  951. /* continue handshaking even if global token bucket is empty */
  952. return connection_tls_continue_handshake(conn);
  953. }
  954. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  955. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  956. /* else open, or closing */
  957. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  958. switch (result) {
  959. case TOR_TLS_CLOSE:
  960. log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
  961. conn->nickname ? conn->nickname : "not set", conn->address);
  962. return -1;
  963. case TOR_TLS_ERROR:
  964. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  965. conn->nickname ? conn->nickname : "not set", conn->address);
  966. return -1;
  967. case TOR_TLS_WANTWRITE:
  968. connection_start_writing(conn);
  969. return 0;
  970. case TOR_TLS_WANTREAD: /* we're already reading */
  971. case TOR_TLS_DONE: /* no data read, so nothing to process */
  972. result = 0;
  973. break; /* so we call bucket_decrement below */
  974. default:
  975. break;
  976. }
  977. pending = tor_tls_get_pending_bytes(conn->tls);
  978. if (pending) {
  979. /* XXXX If we have any pending bytes, read them now. This *can*
  980. * take us over our read alotment, but really we shouldn't be
  981. * believing that SSL bytes are the same as TCP bytes anyway. */
  982. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  983. if (r2<0) {
  984. log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
  985. return -1;
  986. } else {
  987. result += r2;
  988. }
  989. }
  990. } else {
  991. result = read_to_buf(conn->s, at_most, conn->inbuf,
  992. &conn->inbuf_reached_eof);
  993. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  994. if (result < 0)
  995. return -1;
  996. }
  997. if (result > 0) { /* change *max_to_read */
  998. *max_to_read = at_most - result;
  999. }
  1000. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1001. rep_hist_note_bytes_read(result, time(NULL));
  1002. connection_read_bucket_decrement(conn, result);
  1003. }
  1004. if (more_to_read && result == at_most) {
  1005. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1006. tor_assert(bytes_in_buf < 1024);
  1007. at_most = more_to_read;
  1008. goto again;
  1009. }
  1010. /* Call even if result is 0, since the global read bucket may
  1011. * have reached 0 on a different conn, and this guy needs to
  1012. * know to stop reading. */
  1013. connection_consider_empty_buckets(conn);
  1014. return 0;
  1015. }
  1016. /** A pass-through to fetch_from_buf. */
  1017. int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
  1018. return fetch_from_buf(string, len, conn->inbuf);
  1019. }
  1020. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1021. * from its outbuf. */
  1022. int connection_wants_to_flush(connection_t *conn) {
  1023. return conn->outbuf_flushlen;
  1024. }
  1025. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1026. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1027. * connection_edge_consider_sending_sendme().
  1028. */
  1029. int connection_outbuf_too_full(connection_t *conn) {
  1030. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1031. }
  1032. /** Try to flush more bytes onto conn-\>s.
  1033. *
  1034. * This function gets called either from conn_write() in main.c
  1035. * when poll() has declared that conn wants to write, or below
  1036. * from connection_write_to_buf() when an entire TLS record is ready.
  1037. *
  1038. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1039. * or flush_buf_tls appropriately. If it succeeds and there no more
  1040. * more bytes on conn->outbuf, then call connection_finished_flushing
  1041. * on it too.
  1042. *
  1043. * Mark the connection and return -1 if you want to close it, else
  1044. * return 0.
  1045. */
  1046. int connection_handle_write(connection_t *conn) {
  1047. int e;
  1048. socklen_t len=sizeof(e);
  1049. int result;
  1050. time_t now = time(NULL);
  1051. tor_assert(!connection_is_listener(conn));
  1052. conn->timestamp_lastwritten = now;
  1053. /* Sometimes, "writable" means "connected". */
  1054. if (connection_state_is_connecting(conn)) {
  1055. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1056. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  1057. if (CONN_IS_EDGE(conn))
  1058. connection_edge_end_errno(conn, conn->cpath_layer);
  1059. connection_mark_for_close(conn);
  1060. return -1;
  1061. }
  1062. if (e) {
  1063. /* some sort of error, but maybe just inprogress still */
  1064. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1065. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  1066. if (CONN_IS_EDGE(conn))
  1067. connection_edge_end_errno(conn, conn->cpath_layer);
  1068. connection_close_immediate(conn);
  1069. connection_mark_for_close(conn);
  1070. /* it's safe to pass OPs to router_mark_as_down(), since it just
  1071. * ignores unrecognized routers
  1072. */
  1073. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1074. router_mark_as_down(conn->identity_digest);
  1075. return -1;
  1076. } else {
  1077. return 0; /* no change, see if next time is better */
  1078. }
  1079. }
  1080. /* The connection is successful. */
  1081. if (connection_finished_connecting(conn)<0)
  1082. return -1;
  1083. }
  1084. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  1085. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1086. connection_stop_writing(conn);
  1087. if (connection_tls_continue_handshake(conn) < 0) {
  1088. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1089. connection_mark_for_close(conn);
  1090. return -1;
  1091. }
  1092. return 0;
  1093. }
  1094. /* else open, or closing */
  1095. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  1096. switch (result) {
  1097. case TOR_TLS_ERROR:
  1098. case TOR_TLS_CLOSE:
  1099. log_fn(LOG_INFO,result==TOR_TLS_ERROR?
  1100. "tls error. breaking.":"TLS connection closed on flush");
  1101. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1102. connection_mark_for_close(conn);
  1103. return -1;
  1104. case TOR_TLS_WANTWRITE:
  1105. log_fn(LOG_DEBUG,"wanted write.");
  1106. /* we're already writing */
  1107. return 0;
  1108. case TOR_TLS_WANTREAD:
  1109. /* Make sure to avoid a loop if the receive buckets are empty. */
  1110. log_fn(LOG_DEBUG,"wanted read.");
  1111. if (!connection_is_reading(conn)) {
  1112. connection_stop_writing(conn);
  1113. conn->wants_to_write = 1;
  1114. /* we'll start reading again when the next second arrives,
  1115. * and then also start writing again.
  1116. */
  1117. }
  1118. /* else no problem, we're already reading */
  1119. return 0;
  1120. /* case TOR_TLS_DONE:
  1121. * for TOR_TLS_DONE, fall through to check if the flushlen
  1122. * is empty, so we can stop writing.
  1123. */
  1124. }
  1125. } else {
  1126. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  1127. if (result < 0) {
  1128. if (CONN_IS_EDGE(conn))
  1129. connection_edge_end_errno(conn, conn->cpath_layer);
  1130. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1131. connection_mark_for_close(conn);
  1132. return -1;
  1133. }
  1134. }
  1135. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1136. rep_hist_note_bytes_written(result, now);
  1137. global_write_bucket -= result;
  1138. }
  1139. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1140. if (connection_finished_flushing(conn) < 0) {
  1141. /* already marked */
  1142. return -1;
  1143. }
  1144. }
  1145. return 0;
  1146. }
  1147. /* DOCDOC */
  1148. void _connection_controller_force_write(connection_t *conn)
  1149. {
  1150. /* XXX This is hideous code duplication, but raising it seems a little
  1151. * tricky for now. Think more about this one. We only call it for
  1152. * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
  1153. */
  1154. int result;
  1155. tor_assert(conn);
  1156. tor_assert(!conn->tls);
  1157. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1158. if (conn->marked_for_close || conn->s < 0)
  1159. return;
  1160. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  1161. if (result < 0) {
  1162. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1163. connection_mark_for_close(conn);
  1164. return;
  1165. }
  1166. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1167. rep_hist_note_bytes_written(result, time(NULL));
  1168. global_write_bucket -= result;
  1169. }
  1170. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1171. if (connection_finished_flushing(conn) < 0) {
  1172. /* already marked */
  1173. return;
  1174. }
  1175. }
  1176. }
  1177. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1178. * outbuf, and ask it to start writing.
  1179. */
  1180. void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
  1181. if (!len)
  1182. return;
  1183. /* if it's marked for close, only allow write if we mean to flush it */
  1184. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1185. return;
  1186. if (write_to_buf(string, len, conn->outbuf) < 0) {
  1187. if (CONN_IS_EDGE(conn)) {
  1188. /* if it failed, it means we have our package/delivery windows set
  1189. wrong compared to our max outbuf size. close the whole circuit. */
  1190. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1191. circuit_mark_for_close(circuit_get_by_edge_conn(conn));
  1192. } else {
  1193. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  1194. connection_mark_for_close(conn);
  1195. }
  1196. return;
  1197. }
  1198. connection_start_writing(conn);
  1199. conn->outbuf_flushlen += len;
  1200. }
  1201. /** Return the conn to addr/port that has the most recent
  1202. * timestamp_created, or NULL if no such conn exists. */
  1203. connection_t *connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  1204. int i, n;
  1205. connection_t *conn, *best=NULL;
  1206. connection_t **carray;
  1207. get_connection_array(&carray,&n);
  1208. for (i=0;i<n;i++) {
  1209. conn = carray[i];
  1210. if (conn->type == CONN_TYPE_OR &&
  1211. conn->addr == addr &&
  1212. conn->port == port &&
  1213. !conn->marked_for_close &&
  1214. (!best || best->timestamp_created < conn->timestamp_created))
  1215. best = conn;
  1216. }
  1217. return best;
  1218. }
  1219. connection_t *connection_get_by_identity_digest(const char *digest, int type)
  1220. {
  1221. int i, n;
  1222. connection_t *conn, *best=NULL;
  1223. connection_t **carray;
  1224. get_connection_array(&carray,&n);
  1225. for (i=0;i<n;i++) {
  1226. conn = carray[i];
  1227. if (conn->type != type)
  1228. continue;
  1229. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
  1230. !conn->marked_for_close &&
  1231. (!best || best->timestamp_created < conn->timestamp_created))
  1232. best = conn;
  1233. }
  1234. return best;
  1235. }
  1236. /** Return the connection with id <b>id</b> if it is not already
  1237. * marked for close.
  1238. */
  1239. connection_t *
  1240. connection_get_by_global_id(uint32_t id) {
  1241. int i, n;
  1242. connection_t *conn;
  1243. connection_t **carray;
  1244. get_connection_array(&carray,&n);
  1245. for (i=0;i<n;i++) {
  1246. conn = carray[i];
  1247. if (conn->global_identifier == id) {
  1248. if (!conn->marked_for_close)
  1249. return conn;
  1250. else
  1251. return NULL;
  1252. }
  1253. }
  1254. return NULL;
  1255. }
  1256. /** Return a connection of type <b>type</b> that is not marked for
  1257. * close.
  1258. */
  1259. connection_t *connection_get_by_type(int type) {
  1260. int i, n;
  1261. connection_t *conn;
  1262. connection_t **carray;
  1263. get_connection_array(&carray,&n);
  1264. for (i=0;i<n;i++) {
  1265. conn = carray[i];
  1266. if (conn->type == type && !conn->marked_for_close)
  1267. return conn;
  1268. }
  1269. return NULL;
  1270. }
  1271. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1272. * and that is not marked for close.
  1273. */
  1274. connection_t *connection_get_by_type_state(int type, int state) {
  1275. int i, n;
  1276. connection_t *conn;
  1277. connection_t **carray;
  1278. get_connection_array(&carray,&n);
  1279. for (i=0;i<n;i++) {
  1280. conn = carray[i];
  1281. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1282. return conn;
  1283. }
  1284. return NULL;
  1285. }
  1286. /** Return a connection of type <b>type</b> that has purpose <b>purpose</b>,
  1287. * and that is not marked for close.
  1288. */
  1289. connection_t *connection_get_by_type_purpose(int type, int purpose) {
  1290. int i, n;
  1291. connection_t *conn;
  1292. connection_t **carray;
  1293. get_connection_array(&carray,&n);
  1294. for (i=0;i<n;i++) {
  1295. conn = carray[i];
  1296. if (conn->type == type && conn->purpose == purpose && !conn->marked_for_close)
  1297. return conn;
  1298. }
  1299. return NULL;
  1300. }
  1301. /** Return the connection of type <b>type</b> that is in state
  1302. * <b>state</b>, that was written to least recently, and that is not
  1303. * marked for close.
  1304. */
  1305. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  1306. int i, n;
  1307. connection_t *conn, *best=NULL;
  1308. connection_t **carray;
  1309. get_connection_array(&carray,&n);
  1310. for (i=0;i<n;i++) {
  1311. conn = carray[i];
  1312. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1313. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1314. best = conn;
  1315. }
  1316. return best;
  1317. }
  1318. /** Return a connection of type <b>type</b> that has rendquery equal
  1319. * to <b>rendquery</b>, and that is not marked for close. If state
  1320. * is non-zero, conn must be of that state too.
  1321. */
  1322. connection_t *
  1323. connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
  1324. int i, n;
  1325. connection_t *conn;
  1326. connection_t **carray;
  1327. get_connection_array(&carray,&n);
  1328. for (i=0;i<n;i++) {
  1329. conn = carray[i];
  1330. if (conn->type == type &&
  1331. !conn->marked_for_close &&
  1332. (!state || state == conn->state) &&
  1333. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1334. return conn;
  1335. }
  1336. return NULL;
  1337. }
  1338. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1339. int connection_is_listener(connection_t *conn) {
  1340. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1341. conn->type == CONN_TYPE_AP_LISTENER ||
  1342. conn->type == CONN_TYPE_DIR_LISTENER ||
  1343. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1344. return 1;
  1345. return 0;
  1346. }
  1347. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1348. * for close, else return 0.
  1349. */
  1350. int connection_state_is_open(connection_t *conn) {
  1351. tor_assert(conn);
  1352. if (conn->marked_for_close)
  1353. return 0;
  1354. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1355. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1356. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1357. (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
  1358. return 1;
  1359. return 0;
  1360. }
  1361. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1362. int connection_state_is_connecting(connection_t *conn) {
  1363. tor_assert(conn);
  1364. if (conn->marked_for_close)
  1365. return 0;
  1366. switch (conn->type)
  1367. {
  1368. case CONN_TYPE_OR:
  1369. return conn->state == OR_CONN_STATE_CONNECTING;
  1370. case CONN_TYPE_EXIT:
  1371. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1372. case CONN_TYPE_DIR:
  1373. return conn->state == DIR_CONN_STATE_CONNECTING;
  1374. }
  1375. return 0;
  1376. }
  1377. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1378. * <b>conn</b>.
  1379. *
  1380. * Return 0.
  1381. */
  1382. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  1383. cell_t cell;
  1384. tor_assert(conn);
  1385. tor_assert(connection_speaks_cells(conn));
  1386. memset(&cell, 0, sizeof(cell_t));
  1387. cell.circ_id = circ_id;
  1388. cell.command = CELL_DESTROY;
  1389. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  1390. connection_or_write_cell_to_buf(&cell, conn);
  1391. return 0;
  1392. }
  1393. /** Process new bytes that have arrived on conn-\>inbuf.
  1394. *
  1395. * This function just passes conn to the connection-specific
  1396. * connection_*_process_inbuf() function. It also passes in
  1397. * package_partial if wanted.
  1398. */
  1399. static int connection_process_inbuf(connection_t *conn, int package_partial) {
  1400. tor_assert(conn);
  1401. switch (conn->type) {
  1402. case CONN_TYPE_OR:
  1403. return connection_or_process_inbuf(conn);
  1404. case CONN_TYPE_EXIT:
  1405. case CONN_TYPE_AP:
  1406. return connection_edge_process_inbuf(conn, package_partial);
  1407. case CONN_TYPE_DIR:
  1408. return connection_dir_process_inbuf(conn);
  1409. case CONN_TYPE_DNSWORKER:
  1410. return connection_dns_process_inbuf(conn);
  1411. case CONN_TYPE_CPUWORKER:
  1412. return connection_cpu_process_inbuf(conn);
  1413. case CONN_TYPE_CONTROL:
  1414. return connection_control_process_inbuf(conn);
  1415. default:
  1416. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1417. tor_fragile_assert();
  1418. return -1;
  1419. }
  1420. }
  1421. /** We just finished flushing bytes from conn-\>outbuf, and there
  1422. * are no more bytes remaining.
  1423. *
  1424. * This function just passes conn to the connection-specific
  1425. * connection_*_finished_flushing() function.
  1426. */
  1427. static int connection_finished_flushing(connection_t *conn) {
  1428. tor_assert(conn);
  1429. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1430. switch (conn->type) {
  1431. case CONN_TYPE_OR:
  1432. return connection_or_finished_flushing(conn);
  1433. case CONN_TYPE_AP:
  1434. case CONN_TYPE_EXIT:
  1435. return connection_edge_finished_flushing(conn);
  1436. case CONN_TYPE_DIR:
  1437. return connection_dir_finished_flushing(conn);
  1438. case CONN_TYPE_DNSWORKER:
  1439. return connection_dns_finished_flushing(conn);
  1440. case CONN_TYPE_CPUWORKER:
  1441. return connection_cpu_finished_flushing(conn);
  1442. case CONN_TYPE_CONTROL:
  1443. return connection_control_finished_flushing(conn);
  1444. default:
  1445. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1446. tor_fragile_assert();
  1447. return -1;
  1448. }
  1449. }
  1450. /** Called when our attempt to connect() to another server has just
  1451. * succeeded.
  1452. *
  1453. * This function just passes conn to the connection-specific
  1454. * connection_*_finished_connecting() function.
  1455. */
  1456. static int connection_finished_connecting(connection_t *conn)
  1457. {
  1458. tor_assert(conn);
  1459. switch (conn->type)
  1460. {
  1461. case CONN_TYPE_OR:
  1462. return connection_or_finished_connecting(conn);
  1463. case CONN_TYPE_EXIT:
  1464. return connection_edge_finished_connecting(conn);
  1465. case CONN_TYPE_DIR:
  1466. return connection_dir_finished_connecting(conn);
  1467. default:
  1468. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1469. tor_fragile_assert();
  1470. return -1;
  1471. }
  1472. }
  1473. static int connection_reached_eof(connection_t *conn)
  1474. {
  1475. switch (conn->type) {
  1476. case CONN_TYPE_OR:
  1477. return connection_or_reached_eof(conn);
  1478. case CONN_TYPE_AP:
  1479. case CONN_TYPE_EXIT:
  1480. return connection_edge_reached_eof(conn);
  1481. case CONN_TYPE_DIR:
  1482. return connection_dir_reached_eof(conn);
  1483. case CONN_TYPE_DNSWORKER:
  1484. return connection_dns_reached_eof(conn);
  1485. case CONN_TYPE_CPUWORKER:
  1486. return connection_cpu_reached_eof(conn);
  1487. case CONN_TYPE_CONTROL:
  1488. return connection_control_reached_eof(conn);
  1489. default:
  1490. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1491. tor_fragile_assert();
  1492. return -1;
  1493. }
  1494. }
  1495. /** Verify that connection <b>conn</b> has all of its invariants
  1496. * correct. Trigger an assert if anything is invalid.
  1497. */
  1498. void assert_connection_ok(connection_t *conn, time_t now)
  1499. {
  1500. tor_assert(conn);
  1501. tor_assert(conn->magic == CONNECTION_MAGIC);
  1502. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1503. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1504. if (conn->outbuf_flushlen > 0) {
  1505. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1506. }
  1507. if (conn->hold_open_until_flushed)
  1508. tor_assert(conn->marked_for_close);
  1509. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1510. * marked_for_close. */
  1511. /* buffers */
  1512. if (!connection_is_listener(conn)) {
  1513. assert_buf_ok(conn->inbuf);
  1514. assert_buf_ok(conn->outbuf);
  1515. }
  1516. #if 0 /* computers often go back in time; no way to know */
  1517. tor_assert(!now || conn->timestamp_lastread <= now);
  1518. tor_assert(!now || conn->timestamp_lastwritten <= now);
  1519. tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
  1520. tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  1521. #endif
  1522. /* XXX Fix this; no longer so.*/
  1523. #if 0
  1524. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1525. tor_assert(!conn->pkey);
  1526. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1527. * connected to another OR.
  1528. */
  1529. #endif
  1530. if (conn->type != CONN_TYPE_OR) {
  1531. tor_assert(!conn->tls);
  1532. } else {
  1533. if (conn->state == OR_CONN_STATE_OPEN) {
  1534. /* tor_assert(conn->bandwidth > 0); */
  1535. /* the above isn't necessarily true: if we just did a TLS
  1536. * handshake but we didn't recognize the other peer, or it
  1537. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1538. * yet it will be open. -RD
  1539. */
  1540. // tor_assert(conn->receiver_bucket >= 0);
  1541. }
  1542. // tor_assert(conn->addr && conn->port);
  1543. tor_assert(conn->address);
  1544. if (conn->state > OR_CONN_STATE_PROXY_READING)
  1545. tor_assert(conn->tls);
  1546. }
  1547. if (! CONN_IS_EDGE(conn)) {
  1548. tor_assert(!conn->stream_id);
  1549. tor_assert(!conn->next_stream);
  1550. tor_assert(!conn->cpath_layer);
  1551. tor_assert(!conn->package_window);
  1552. tor_assert(!conn->deliver_window);
  1553. tor_assert(!conn->done_sending);
  1554. tor_assert(!conn->done_receiving);
  1555. } else {
  1556. /* XXX unchecked: package window, deliver window. */
  1557. }
  1558. if (conn->type == CONN_TYPE_AP) {
  1559. tor_assert(conn->socks_request);
  1560. if (conn->state == AP_CONN_STATE_OPEN) {
  1561. tor_assert(conn->socks_request->has_finished);
  1562. if (!conn->marked_for_close) {
  1563. tor_assert(conn->cpath_layer);
  1564. assert_cpath_layer_ok(conn->cpath_layer);
  1565. }
  1566. }
  1567. } else {
  1568. tor_assert(!conn->socks_request);
  1569. }
  1570. if (conn->type == CONN_TYPE_EXIT) {
  1571. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1572. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1573. } else if (conn->type != CONN_TYPE_DIR) {
  1574. tor_assert(!conn->purpose); /* only used for dir types currently */
  1575. }
  1576. switch (conn->type)
  1577. {
  1578. case CONN_TYPE_OR_LISTENER:
  1579. case CONN_TYPE_AP_LISTENER:
  1580. case CONN_TYPE_DIR_LISTENER:
  1581. case CONN_TYPE_CONTROL_LISTENER:
  1582. tor_assert(conn->state == LISTENER_STATE_READY);
  1583. break;
  1584. case CONN_TYPE_OR:
  1585. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1586. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1587. break;
  1588. case CONN_TYPE_EXIT:
  1589. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1590. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1591. break;
  1592. case CONN_TYPE_AP:
  1593. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1594. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1595. tor_assert(conn->socks_request);
  1596. break;
  1597. case CONN_TYPE_DIR:
  1598. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1599. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1600. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1601. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1602. break;
  1603. case CONN_TYPE_DNSWORKER:
  1604. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1605. conn->state == DNSWORKER_STATE_BUSY);
  1606. break;
  1607. case CONN_TYPE_CPUWORKER:
  1608. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1609. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1610. break;
  1611. case CONN_TYPE_CONTROL:
  1612. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1613. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1614. break;
  1615. default:
  1616. tor_assert(0);
  1617. }
  1618. }