circuitbuild.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char circuitbuild_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file circuitbuild.c
  10. * \brief The actual details of building circuits.
  11. **/
  12. #include "or.h"
  13. /********* START VARIABLES **********/
  14. /** A global list of all circuits at this hop. */
  15. extern circuit_t *global_circuitlist;
  16. /** An entry_guard_t represents our information about a chosen long-term
  17. * first hop, known as a "helper" node in the literature. We can't just
  18. * use a routerinfo_t, since we want to remember these even when we
  19. * don't have a directory. */
  20. typedef struct {
  21. char nickname[MAX_NICKNAME_LEN+1];
  22. char identity[DIGEST_LEN];
  23. uint8_t made_contact; /**< 0 if we have never connected to this router,
  24. * 1 if we have. */
  25. time_t down_since; /**< 0 if this router is currently up, or the time at
  26. * which it was observed to go down. */
  27. time_t unlisted_since; /**< 0 if this router is currently listed, or the
  28. * time at which it became unlisted */
  29. } entry_guard_t;
  30. /** A list of our chosen entry guards. */
  31. static smartlist_t *entry_guards = NULL;
  32. /** A value of 1 means that the entry_guards list has changed
  33. * and those changes need to be flushed to disk. */
  34. static int entry_guards_dirty = 0;
  35. /********* END VARIABLES ************/
  36. static int circuit_deliver_create_cell(circuit_t *circ,
  37. uint8_t cell_type, char *payload);
  38. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  39. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  40. static int onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  41. cpath_build_state_t *state);
  42. static int count_acceptable_routers(smartlist_t *routers);
  43. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  44. static routerinfo_t *choose_random_entry(cpath_build_state_t *state);
  45. static void entry_guards_changed(void);
  46. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  47. * and with the high bit specified by conn-\>circ_id_type, until we get
  48. * a circ_id that is not in use by any other circuit on that conn.
  49. *
  50. * Return it, or 0 if can't get a unique circ_id.
  51. */
  52. static uint16_t
  53. get_unique_circ_id_by_conn(connection_t *conn)
  54. {
  55. uint16_t test_circ_id;
  56. uint16_t attempts=0;
  57. uint16_t high_bit;
  58. tor_assert(conn);
  59. tor_assert(conn->type == CONN_TYPE_OR);
  60. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  61. do {
  62. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  63. * circID such that (high_bit|test_circ_id) is not already used. */
  64. test_circ_id = conn->next_circ_id++;
  65. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  66. test_circ_id = 1;
  67. conn->next_circ_id = 2;
  68. }
  69. if (++attempts > 1<<15) {
  70. /* Make sure we don't loop forever if all circ_id's are used. This
  71. * matters because it's an external DoS opportunity.
  72. */
  73. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  74. return 0;
  75. }
  76. test_circ_id |= high_bit;
  77. } while (circuit_id_used_on_conn(test_circ_id, conn));
  78. return test_circ_id;
  79. }
  80. /** If <b>verbose</b> is false, allocate and return a comma-separated
  81. * list of the currently built elements of circuit_t. If
  82. * <b>verbose</b> is true, also list information about link status in
  83. * a more verbose format using spaces.
  84. */
  85. char *
  86. circuit_list_path(origin_circuit_t *circ, int verbose)
  87. {
  88. crypt_path_t *hop;
  89. smartlist_t *elements;
  90. const char *states[] = {"closed", "waiting for keys", "open"};
  91. char buf[128];
  92. char *s;
  93. elements = smartlist_create();
  94. if (verbose) {
  95. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  96. tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
  97. circ->build_state->is_internal ? "internal" : "exit",
  98. circ->build_state->need_uptime ? " (high-uptime)" : "",
  99. circ->build_state->desired_path_len,
  100. circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
  101. circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
  102. (nickname?nickname:"*unnamed*"));
  103. smartlist_add(elements, tor_strdup(buf));
  104. }
  105. hop = circ->cpath;
  106. do {
  107. const char *elt;
  108. if (!hop)
  109. break;
  110. if (!verbose && hop->state != CPATH_STATE_OPEN)
  111. break;
  112. if (!hop->extend_info)
  113. break;
  114. elt = hop->extend_info->nickname;
  115. tor_assert(elt);
  116. if (verbose) {
  117. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  118. char *v = tor_malloc(len);
  119. tor_assert(hop->state <= 2);
  120. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  121. smartlist_add(elements, v);
  122. } else {
  123. smartlist_add(elements, tor_strdup(elt));
  124. }
  125. hop = hop->next;
  126. } while (hop != circ->cpath);
  127. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  128. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  129. smartlist_free(elements);
  130. return s;
  131. }
  132. /** Log, at severity <b>severity</b>, the nicknames of each router in
  133. * circ's cpath. Also log the length of the cpath, and the intended
  134. * exit point.
  135. */
  136. void
  137. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  138. {
  139. char *s = circuit_list_path(circ,1);
  140. log(severity,domain,"%s",s);
  141. tor_free(s);
  142. }
  143. /** Tell the rep(utation)hist(ory) module about the status of the links
  144. * in circ. Hops that have become OPEN are marked as successfully
  145. * extended; the _first_ hop that isn't open (if any) is marked as
  146. * unable to extend.
  147. */
  148. void
  149. circuit_rep_hist_note_result(origin_circuit_t *circ)
  150. {
  151. crypt_path_t *hop;
  152. char *prev_digest = NULL;
  153. routerinfo_t *router;
  154. hop = circ->cpath;
  155. if (!hop) {
  156. /* XXX
  157. * if !hop, then we're not the beginning of this circuit.
  158. * for now, just forget about it. later, we should remember when
  159. * extends-through-us failed, too.
  160. */
  161. return;
  162. }
  163. if (server_mode(get_options())) {
  164. routerinfo_t *me = router_get_my_routerinfo();
  165. if (!me)
  166. return;
  167. prev_digest = me->cache_info.identity_digest;
  168. }
  169. do {
  170. router = router_get_by_digest(hop->extend_info->identity_digest);
  171. if (router) {
  172. if (prev_digest) {
  173. if (hop->state == CPATH_STATE_OPEN)
  174. rep_hist_note_extend_succeeded(prev_digest,
  175. router->cache_info.identity_digest);
  176. else {
  177. rep_hist_note_extend_failed(prev_digest,
  178. router->cache_info.identity_digest);
  179. break;
  180. }
  181. }
  182. prev_digest = router->cache_info.identity_digest;
  183. } else {
  184. prev_digest = NULL;
  185. }
  186. hop=hop->next;
  187. } while (hop!=circ->cpath);
  188. }
  189. /** Pick all the entries in our cpath. Stop and return 0 when we're
  190. * happy, or return -1 if an error occurs. */
  191. static int
  192. onion_populate_cpath(origin_circuit_t *circ)
  193. {
  194. int r;
  195. again:
  196. r = onion_extend_cpath(circ->_base.purpose, &circ->cpath, circ->build_state);
  197. if (r < 0) {
  198. log_info(LD_CIRC,"Generating cpath hop failed.");
  199. return -1;
  200. }
  201. if (r == 0)
  202. goto again;
  203. return 0; /* if r == 1 */
  204. }
  205. /** Create and return a new origin circuit. Initialize its purpose and
  206. * build-state based on our arguments. */
  207. origin_circuit_t *
  208. origin_circuit_init(uint8_t purpose, int need_uptime, int need_capacity,
  209. int internal)
  210. {
  211. /* sets circ->p_circ_id and circ->p_conn */
  212. origin_circuit_t *circ = origin_circuit_new();
  213. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  214. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  215. circ->build_state->need_uptime = need_uptime;
  216. circ->build_state->need_capacity = need_capacity;
  217. circ->build_state->is_internal = internal;
  218. circ->_base.purpose = purpose;
  219. return circ;
  220. }
  221. /** Build a new circuit for <b>purpose</b>. If <b>info/b>
  222. * is defined, then use that as your exit router, else choose a suitable
  223. * exit node.
  224. *
  225. * Also launch a connection to the first OR in the chosen path, if
  226. * it's not open already.
  227. */
  228. origin_circuit_t *
  229. circuit_establish_circuit(uint8_t purpose, extend_info_t *info,
  230. int need_uptime, int need_capacity, int internal)
  231. {
  232. origin_circuit_t *circ;
  233. circ = origin_circuit_init(purpose, need_uptime, need_capacity, internal);
  234. if (onion_pick_cpath_exit(circ, info) < 0 ||
  235. onion_populate_cpath(circ) < 0) {
  236. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  237. return NULL;
  238. }
  239. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED);
  240. if (circuit_handle_first_hop(circ) < 0) {
  241. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  242. return NULL;
  243. }
  244. return circ;
  245. }
  246. /** Start establishing the first hop of our circuit. Figure out what
  247. * OR we should connect to, and if necessary start the connection to
  248. * it. If we're already connected, then send the 'create' cell.
  249. * Return 0 for ok, -1 if circ should be marked-for-close. */
  250. int
  251. circuit_handle_first_hop(origin_circuit_t *circ)
  252. {
  253. crypt_path_t *firsthop;
  254. connection_t *n_conn;
  255. char tmpbuf[INET_NTOA_BUF_LEN];
  256. struct in_addr in;
  257. firsthop = onion_next_hop_in_cpath(circ->cpath);
  258. tor_assert(firsthop);
  259. tor_assert(firsthop->extend_info);
  260. /* now see if we're already connected to the first OR in 'route' */
  261. in.s_addr = htonl(firsthop->extend_info->addr);
  262. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  263. log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
  264. firsthop->extend_info->port);
  265. /* imprint the circuit with its future n_conn->id */
  266. memcpy(circ->_base.n_conn_id_digest, firsthop->extend_info->identity_digest,
  267. DIGEST_LEN);
  268. n_conn = connection_or_get_by_identity_digest(
  269. firsthop->extend_info->identity_digest);
  270. /* If we don't have an open conn, or the conn we have is obsolete
  271. * (i.e. old or broken) and the other side will let us make a second
  272. * connection without dropping it immediately... */
  273. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN ||
  274. (n_conn->is_obsolete &&
  275. router_digest_version_as_new_as(firsthop->extend_info->identity_digest,
  276. "0.1.1.9-alpha-cvs"))) {
  277. /* not currently connected */
  278. circ->_base.n_addr = firsthop->extend_info->addr;
  279. circ->_base.n_port = firsthop->extend_info->port;
  280. if (!n_conn || n_conn->is_obsolete) { /* launch the connection */
  281. n_conn = connection_or_connect(firsthop->extend_info->addr,
  282. firsthop->extend_info->port,
  283. firsthop->extend_info->identity_digest);
  284. if (!n_conn) { /* connect failed, forget the whole thing */
  285. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  286. return -1;
  287. }
  288. }
  289. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  290. /* return success. The onion/circuit/etc will be taken care of
  291. * automatically (may already have been) whenever n_conn reaches
  292. * OR_CONN_STATE_OPEN.
  293. */
  294. return 0;
  295. } else { /* it's already open. use it. */
  296. circ->_base.n_addr = n_conn->addr;
  297. circ->_base.n_port = n_conn->port;
  298. circ->_base.n_conn = n_conn;
  299. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  300. if (circuit_send_next_onion_skin(circ) < 0) {
  301. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  302. return -1;
  303. }
  304. }
  305. return 0;
  306. }
  307. /** Find any circuits that are waiting on <b>or_conn</b> to become
  308. * open and get them to send their create cells forward.
  309. *
  310. * Status is 1 if connect succeeded, or 0 if connect failed.
  311. */
  312. void
  313. circuit_n_conn_done(connection_t *or_conn, int status)
  314. {
  315. extern smartlist_t *circuits_pending_or_conns;
  316. smartlist_t *changed_circs;
  317. log_debug(LD_CIRC,"or_conn to %s, status=%d",
  318. or_conn->nickname ? or_conn->nickname : "NULL", status);
  319. if (!circuits_pending_or_conns)
  320. return;
  321. changed_circs = smartlist_create();
  322. SMARTLIST_FOREACH(circuits_pending_or_conns, circuit_t *, circ,
  323. {
  324. if (circ->marked_for_close)
  325. continue;
  326. tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  327. if (!circ->n_conn &&
  328. !memcmp(or_conn->identity_digest, circ->n_conn_id_digest,
  329. DIGEST_LEN)) {
  330. if (!status) { /* or_conn failed; close circ */
  331. log_info(LD_CIRC,"or_conn failed. Closing circ.");
  332. circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
  333. continue;
  334. }
  335. log_debug(LD_CIRC, "Found circ, sending create cell.");
  336. /* circuit_deliver_create_cell will set n_circ_id and add us to
  337. * orconn_circuid_circuit_map, so we don't need to call
  338. * set_circid_orconn here. */
  339. circ->n_conn = or_conn;
  340. if (CIRCUIT_IS_ORIGIN(circ)) {
  341. if (circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)) < 0) {
  342. log_info(LD_CIRC,
  343. "send_next_onion_skin failed; circuit marked for closing.");
  344. circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
  345. continue;
  346. /* XXX could this be bad, eg if next_onion_skin failed because conn
  347. * died? */
  348. }
  349. } else {
  350. /* pull the create cell out of circ->onionskin, and send it */
  351. tor_assert(circ->onionskin);
  352. if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin)<0) {
  353. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  354. continue;
  355. }
  356. tor_free(circ->onionskin);
  357. /* We don't want to change circ's state here, since the act
  358. * of doing that modifies the circuits_pending_or_conns list
  359. * that we're looping through right now. So collect a list of
  360. * circs to change their state when we're done. */
  361. smartlist_add(changed_circs, circ);
  362. }
  363. }
  364. });
  365. SMARTLIST_FOREACH(changed_circs, circuit_t *, circ,
  366. circuit_set_state(circ, CIRCUIT_STATE_OPEN));
  367. smartlist_free(changed_circs);
  368. }
  369. /** Find a new circid that isn't currently in use on the circ->n_conn
  370. * for the outgoing
  371. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  372. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  373. * to this circuit.
  374. * Return -1 if we failed to find a suitable circid, else return 0.
  375. */
  376. static int
  377. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  378. char *payload)
  379. {
  380. cell_t cell;
  381. uint16_t id;
  382. tor_assert(circ);
  383. tor_assert(circ->n_conn);
  384. tor_assert(circ->n_conn->type == CONN_TYPE_OR);
  385. tor_assert(payload);
  386. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  387. id = get_unique_circ_id_by_conn(circ->n_conn);
  388. if (!id) {
  389. log_warn(LD_CIRC,"failed to get unique circID.");
  390. return -1;
  391. }
  392. log_debug(LD_CIRC,"Chosen circID %u.", id);
  393. circuit_set_n_circid_orconn(circ, id, circ->n_conn);
  394. memset(&cell, 0, sizeof(cell_t));
  395. cell.command = cell_type;
  396. cell.circ_id = circ->n_circ_id;
  397. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  398. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  399. return 0;
  400. }
  401. /** We've decided to start our reachability testing. If all
  402. * is set, log this to the user. Return 1 if we did, or 0 if
  403. * we chose not to log anything. */
  404. int
  405. inform_testing_reachability(void)
  406. {
  407. char dirbuf[128];
  408. routerinfo_t *me = router_get_my_routerinfo();
  409. if (!me)
  410. return 0;
  411. if (me->dir_port)
  412. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  413. me->address, me->dir_port);
  414. log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  415. "(this may take up to %d minutes -- look for log "
  416. "messages indicating success)",
  417. me->address, me->or_port,
  418. me->dir_port ? dirbuf : "",
  419. me->dir_port ? "are" : "is",
  420. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  421. return 1;
  422. }
  423. /** Return true iff we should send a create_fast cell to build a circuit
  424. * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
  425. * information on the router, so return false.) */
  426. static INLINE int
  427. should_use_create_fast_for_router(routerinfo_t *router)
  428. {
  429. or_options_t *options = get_options();
  430. if (!options->FastFirstHopPK || server_mode(options))
  431. return 0;
  432. else if (!router || !router->platform ||
  433. !tor_version_as_new_as(router->platform, "0.1.0.6-rc"))
  434. return 0;
  435. else
  436. return 1;
  437. }
  438. extern int has_completed_circuit;
  439. /** This is the backbone function for building circuits.
  440. *
  441. * If circ's first hop is closed, then we need to build a create
  442. * cell and send it forward.
  443. *
  444. * Otherwise, we need to build a relay extend cell and send it
  445. * forward.
  446. *
  447. * Return -reason if we want to tear down circ, else return 0.
  448. */
  449. int
  450. circuit_send_next_onion_skin(origin_circuit_t *circ)
  451. {
  452. crypt_path_t *hop;
  453. routerinfo_t *router;
  454. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  455. char *onionskin;
  456. size_t payload_len;
  457. tor_assert(circ);
  458. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  459. int fast;
  460. uint8_t cell_type;
  461. log_debug(LD_CIRC,"First skin; sending create cell.");
  462. router = router_get_by_digest(circ->_base.n_conn->identity_digest);
  463. fast = should_use_create_fast_for_router(router);
  464. if (! fast) {
  465. /* We are an OR, or we are connecting to an old Tor: we should
  466. * send an old slow create cell.
  467. */
  468. cell_type = CELL_CREATE;
  469. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  470. &(circ->cpath->dh_handshake_state),
  471. payload) < 0) {
  472. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  473. return - END_CIRC_REASON_INTERNAL;
  474. }
  475. } else {
  476. /* We are not an OR, and we're building the first hop of a circuit to a
  477. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  478. * and a DH operation. */
  479. cell_type = CELL_CREATE_FAST;
  480. memset(payload, 0, sizeof(payload));
  481. crypto_rand(circ->cpath->fast_handshake_state,
  482. sizeof(circ->cpath->fast_handshake_state));
  483. memcpy(payload, circ->cpath->fast_handshake_state,
  484. sizeof(circ->cpath->fast_handshake_state));
  485. }
  486. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  487. return - END_CIRC_REASON_RESOURCELIMIT;
  488. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  489. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  490. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  491. fast ? "CREATE_FAST" : "CREATE",
  492. router ? router->nickname : "<unnamed>");
  493. } else {
  494. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  495. tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
  496. log_debug(LD_CIRC,"starting to send subsequent skin.");
  497. hop = onion_next_hop_in_cpath(circ->cpath);
  498. if (!hop) {
  499. /* done building the circuit. whew. */
  500. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  501. log_info(LD_CIRC,"circuit built!");
  502. circuit_reset_failure_count(0);
  503. if (!has_completed_circuit) {
  504. or_options_t *options = get_options();
  505. has_completed_circuit=1;
  506. /* FFFF Log a count of known routers here */
  507. log(LOG_NOTICE, LD_GENERAL,
  508. "Tor has successfully opened a circuit. "
  509. "Looks like client functionality is working.");
  510. if (server_mode(options) && !check_whether_orport_reachable()) {
  511. inform_testing_reachability();
  512. consider_testing_reachability();
  513. }
  514. }
  515. circuit_rep_hist_note_result(circ);
  516. circuit_has_opened(circ); /* do other actions as necessary */
  517. return 0;
  518. }
  519. *(uint32_t*)payload = htonl(hop->extend_info->addr);
  520. *(uint16_t*)(payload+4) = htons(hop->extend_info->port);
  521. onionskin = payload+2+4;
  522. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  523. hop->extend_info->identity_digest, DIGEST_LEN);
  524. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  525. if (onion_skin_create(hop->extend_info->onion_key,
  526. &(hop->dh_handshake_state), onionskin) < 0) {
  527. log_warn(LD_CIRC,"onion_skin_create failed.");
  528. return - END_CIRC_REASON_INTERNAL;
  529. }
  530. log_debug(LD_CIRC,"Sending extend relay cell.");
  531. /* send it to hop->prev, because it will transfer
  532. * it to a create cell and then send to hop */
  533. if (connection_edge_send_command(NULL, TO_CIRCUIT(circ),
  534. RELAY_COMMAND_EXTEND,
  535. payload, payload_len, hop->prev) < 0)
  536. return 0; /* circuit is closed */
  537. hop->state = CPATH_STATE_AWAITING_KEYS;
  538. }
  539. return 0;
  540. }
  541. /** Our clock just jumped forward by <b>seconds_elapsed</b>. Assume
  542. * something has also gone wrong with our network: notify the user,
  543. * and abandon all not-yet-used circuits. */
  544. void
  545. circuit_note_clock_jumped(int seconds_elapsed)
  546. {
  547. if (server_mode(get_options()))
  548. log(LOG_WARN, LD_GENERAL,
  549. "Please report: your clock just jumped %d seconds forward; "
  550. "assuming established circuits no longer work.", seconds_elapsed);
  551. else
  552. log(LOG_NOTICE, LD_GENERAL, "Your clock just jumped %d seconds forward; "
  553. "assuming established circuits no longer work.", seconds_elapsed);
  554. has_completed_circuit=0; /* so it'll log when it works again */
  555. circuit_mark_all_unused_circs();
  556. circuit_expire_all_dirty_circs();
  557. }
  558. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  559. * sure we're connected to the next hop, and pass it the onion skin using
  560. * a create cell. Return -1 if we want to warn and tear down the circuit,
  561. * else return 0.
  562. */
  563. int
  564. circuit_extend(cell_t *cell, circuit_t *circ)
  565. {
  566. connection_t *n_conn;
  567. relay_header_t rh;
  568. char *onionskin;
  569. char *id_digest=NULL;
  570. if (circ->n_conn) {
  571. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  572. "n_conn already set. Bug/attack. Closing.");
  573. return -1;
  574. }
  575. relay_header_unpack(&rh, cell->payload);
  576. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  577. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  578. "Wrong length %d on extend cell. Closing circuit.",
  579. rh.length);
  580. return -1;
  581. }
  582. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  583. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  584. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  585. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  586. n_conn = connection_or_get_by_identity_digest(id_digest);
  587. /* If we don't have an open conn, or the conn we have is obsolete
  588. * (i.e. old or broken) and the other side will let us make a second
  589. * connection without dropping it immediately... */
  590. if (!n_conn || n_conn->state != OR_CONN_STATE_OPEN ||
  591. (n_conn->is_obsolete &&
  592. router_digest_version_as_new_as(id_digest,"0.1.1.9-alpha-cvs"))) {
  593. struct in_addr in;
  594. char tmpbuf[INET_NTOA_BUF_LEN];
  595. in.s_addr = htonl(circ->n_addr);
  596. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  597. log_info(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
  598. tmpbuf, circ->n_port);
  599. circ->onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  600. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  601. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  602. /* imprint the circuit with its future n_conn->id */
  603. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  604. if (n_conn && !n_conn->is_obsolete) {
  605. circ->n_addr = n_conn->addr;
  606. circ->n_port = n_conn->port;
  607. } else {
  608. /* we should try to open a connection */
  609. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  610. if (!n_conn) {
  611. log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  612. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  613. return 0;
  614. }
  615. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  616. }
  617. /* return success. The onion/circuit/etc will be taken care of
  618. * automatically (may already have been) whenever n_conn reaches
  619. * OR_CONN_STATE_OPEN.
  620. */
  621. return 0;
  622. }
  623. /* these may be different if the router connected to us from elsewhere */
  624. circ->n_addr = n_conn->addr;
  625. circ->n_port = n_conn->port;
  626. circ->n_conn = n_conn;
  627. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  628. log_debug(LD_CIRC,"n_conn is %s:%u",n_conn->address,n_conn->port);
  629. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  630. return -1;
  631. return 0;
  632. }
  633. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  634. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  635. * used as follows:
  636. * - 20 to initialize f_digest
  637. * - 20 to initialize b_digest
  638. * - 16 to key f_crypto
  639. * - 16 to key b_crypto
  640. *
  641. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  642. */
  643. int
  644. circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  645. {
  646. crypto_digest_env_t *tmp_digest;
  647. crypto_cipher_env_t *tmp_crypto;
  648. tor_assert(cpath);
  649. tor_assert(key_data);
  650. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  651. cpath->f_digest || cpath->b_digest));
  652. cpath->f_digest = crypto_new_digest_env();
  653. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  654. cpath->b_digest = crypto_new_digest_env();
  655. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  656. if (!(cpath->f_crypto =
  657. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  658. log_warn(LD_BUG,"Bug: forward cipher initialization failed.");
  659. return -1;
  660. }
  661. if (!(cpath->b_crypto =
  662. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  663. log_warn(LD_BUG,"Bug: backward cipher initialization failed.");
  664. return -1;
  665. }
  666. if (reverse) {
  667. tmp_digest = cpath->f_digest;
  668. cpath->f_digest = cpath->b_digest;
  669. cpath->b_digest = tmp_digest;
  670. tmp_crypto = cpath->f_crypto;
  671. cpath->f_crypto = cpath->b_crypto;
  672. cpath->b_crypto = tmp_crypto;
  673. }
  674. return 0;
  675. }
  676. /** A created or extended cell came back to us on the circuit, and it included
  677. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  678. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  679. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  680. *
  681. * Calculate the appropriate keys and digests, make sure KH is
  682. * correct, and initialize this hop of the cpath.
  683. *
  684. * Return - reason if we want to mark circ for close, else return 0.
  685. */
  686. int
  687. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  688. char *reply)
  689. {
  690. char keys[CPATH_KEY_MATERIAL_LEN];
  691. crypt_path_t *hop;
  692. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  693. hop = circ->cpath;
  694. else {
  695. hop = onion_next_hop_in_cpath(circ->cpath);
  696. if (!hop) { /* got an extended when we're all done? */
  697. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  698. return - END_CIRC_REASON_TORPROTOCOL;
  699. }
  700. }
  701. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  702. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  703. if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
  704. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  705. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  706. return -END_CIRC_REASON_TORPROTOCOL;
  707. }
  708. /* Remember hash of g^xy */
  709. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  710. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  711. if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
  712. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  713. log_warn(LD_CIRC,"fast_client_handshake failed.");
  714. return -END_CIRC_REASON_TORPROTOCOL;
  715. }
  716. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  717. } else {
  718. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  719. return -END_CIRC_REASON_TORPROTOCOL;
  720. }
  721. if (hop->dh_handshake_state) {
  722. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  723. hop->dh_handshake_state = NULL;
  724. }
  725. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  726. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  727. return -END_CIRC_REASON_TORPROTOCOL;
  728. }
  729. hop->state = CPATH_STATE_OPEN;
  730. log_info(LD_CIRC,"Finished building %scircuit hop:",
  731. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  732. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  733. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED);
  734. return 0;
  735. }
  736. /** We received a relay truncated cell on circ.
  737. *
  738. * Since we don't ask for truncates currently, getting a truncated
  739. * means that a connection broke or an extend failed. For now,
  740. * just give up: for circ to close, and return 0.
  741. */
  742. int
  743. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  744. {
  745. // crypt_path_t *victim;
  746. // connection_t *stream;
  747. tor_assert(circ);
  748. tor_assert(layer);
  749. /* XXX Since we don't ask for truncates currently, getting a truncated
  750. * means that a connection broke or an extend failed. For now,
  751. * just give up.
  752. */
  753. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  754. return 0;
  755. #if 0
  756. while (layer->next != circ->cpath) {
  757. /* we need to clear out layer->next */
  758. victim = layer->next;
  759. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  760. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  761. if (stream->cpath_layer == victim) {
  762. /* XXXX NM LD_CIRC? */
  763. log_info(LD_APP, "Marking stream %d for close.", stream->stream_id);
  764. /* no need to send 'end' relay cells,
  765. * because the other side's already dead
  766. */
  767. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  768. }
  769. }
  770. layer->next = victim->next;
  771. circuit_free_cpath_node(victim);
  772. }
  773. log_info(LD_CIRC, "finished");
  774. return 0;
  775. #endif
  776. }
  777. /** Given a response payload and keys, initialize, then send a created
  778. * cell back.
  779. */
  780. int
  781. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, char *payload,
  782. char *keys)
  783. {
  784. cell_t cell;
  785. crypt_path_t *tmp_cpath;
  786. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  787. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  788. memset(&cell, 0, sizeof(cell_t));
  789. cell.command = cell_type;
  790. cell.circ_id = circ->p_circ_id;
  791. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  792. memcpy(cell.payload, payload,
  793. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  794. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  795. (unsigned int)*(uint32_t*)(keys),
  796. (unsigned int)*(uint32_t*)(keys+20));
  797. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  798. log_warn(LD_BUG,"Circuit initialization failed");
  799. tor_free(tmp_cpath);
  800. return -1;
  801. }
  802. circ->n_digest = tmp_cpath->f_digest;
  803. circ->n_crypto = tmp_cpath->f_crypto;
  804. circ->p_digest = tmp_cpath->b_digest;
  805. circ->p_crypto = tmp_cpath->b_crypto;
  806. tmp_cpath->magic = 0;
  807. tor_free(tmp_cpath);
  808. if (cell_type == CELL_CREATED)
  809. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  810. else
  811. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  812. connection_or_write_cell_to_buf(&cell, circ->p_conn);
  813. log_debug(LD_CIRC,"Finished sending 'created' cell.");
  814. if (!is_local_IP(circ->p_conn->addr) &&
  815. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  816. /* record that we could process create cells from a non-local conn
  817. * that we didn't initiate; presumably this means that create cells
  818. * can reach us too. */
  819. router_orport_found_reachable();
  820. }
  821. return 0;
  822. }
  823. /** Choose a length for a circuit of purpose <b>purpose</b>.
  824. * Default length is 3 + the number of endpoints that would give something
  825. * away. If the routerlist <b>routers</b> doesn't have enough routers
  826. * to handle the desired path length, return as large a path length as
  827. * is feasible, except if it's less than 2, in which case return -1.
  828. */
  829. static int
  830. new_route_len(double cw, uint8_t purpose, extend_info_t *exit,
  831. smartlist_t *routers)
  832. {
  833. int num_acceptable_routers;
  834. int routelen;
  835. tor_assert(cw >= 0.);
  836. tor_assert(cw < 1.);
  837. tor_assert(routers);
  838. #ifdef TOR_PERF
  839. routelen = 2;
  840. #else
  841. routelen = 3;
  842. if (exit &&
  843. purpose != CIRCUIT_PURPOSE_TESTING &&
  844. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  845. routelen++;
  846. #endif
  847. log_debug(LD_CIRC,"Chosen route length %d (%d routers available).",
  848. routelen, smartlist_len(routers));
  849. num_acceptable_routers = count_acceptable_routers(routers);
  850. if (num_acceptable_routers < 2) {
  851. log_info(LD_CIRC,
  852. "Not enough acceptable routers (%d). Discarding this circuit.",
  853. num_acceptable_routers);
  854. return -1;
  855. }
  856. if (num_acceptable_routers < routelen) {
  857. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  858. routelen, num_acceptable_routers);
  859. routelen = num_acceptable_routers;
  860. }
  861. return routelen;
  862. }
  863. /** Fetch the list of predicted ports, dup it into a smartlist of
  864. * uint16_t's, remove the ones that are already handled by an
  865. * existing circuit, and return it.
  866. */
  867. static smartlist_t *
  868. circuit_get_unhandled_ports(time_t now)
  869. {
  870. smartlist_t *source = rep_hist_get_predicted_ports(now);
  871. smartlist_t *dest = smartlist_create();
  872. uint16_t *tmp;
  873. int i;
  874. for (i = 0; i < smartlist_len(source); ++i) {
  875. tmp = tor_malloc(sizeof(uint16_t));
  876. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  877. smartlist_add(dest, tmp);
  878. }
  879. circuit_remove_handled_ports(dest);
  880. return dest;
  881. }
  882. /** Return 1 if we already have circuits present or on the way for
  883. * all anticipated ports. Return 0 if we should make more.
  884. *
  885. * If we're returning 0, set need_uptime and need_capacity to
  886. * indicate any requirements that the unhandled ports have.
  887. */
  888. int
  889. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  890. int *need_capacity)
  891. {
  892. int i, enough;
  893. uint16_t *port;
  894. smartlist_t *sl = circuit_get_unhandled_ports(now);
  895. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  896. tor_assert(need_uptime);
  897. tor_assert(need_capacity);
  898. enough = (smartlist_len(sl) == 0);
  899. for (i = 0; i < smartlist_len(sl); ++i) {
  900. port = smartlist_get(sl, i);
  901. if (smartlist_string_num_isin(LongLivedServices, *port))
  902. *need_uptime = 1;
  903. tor_free(port);
  904. }
  905. smartlist_free(sl);
  906. return enough;
  907. }
  908. /** Return 1 if <b>router</b> can handle one or more of the ports in
  909. * <b>needed_ports</b>, else return 0.
  910. */
  911. static int
  912. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  913. {
  914. int i;
  915. uint16_t port;
  916. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  917. addr_policy_result_t r;
  918. port = *(uint16_t *)smartlist_get(needed_ports, i);
  919. tor_assert(port);
  920. r = compare_addr_to_addr_policy(0, port, router->exit_policy);
  921. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  922. return 1;
  923. }
  924. return 0;
  925. }
  926. /** How many circuits do we want simultaneously in-progress to handle
  927. * a given stream?
  928. */
  929. #define MIN_CIRCUITS_HANDLING_STREAM 2
  930. static int
  931. ap_stream_wants_exit_attention(connection_t *conn)
  932. {
  933. if (conn->type == CONN_TYPE_AP &&
  934. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  935. !conn->marked_for_close &&
  936. !connection_edge_is_rendezvous_stream(conn) &&
  937. !circuit_stream_is_being_handled(conn, 0, MIN_CIRCUITS_HANDLING_STREAM))
  938. return 1;
  939. return 0;
  940. }
  941. /** Return a pointer to a suitable router to be the exit node for the
  942. * general-purpose circuit we're about to build.
  943. *
  944. * Look through the connection array, and choose a router that maximizes
  945. * the number of pending streams that can exit from this router.
  946. *
  947. * Return NULL if we can't find any suitable routers.
  948. */
  949. static routerinfo_t *
  950. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  951. int need_capacity)
  952. {
  953. int *n_supported;
  954. int i, j;
  955. int n_pending_connections = 0;
  956. connection_t **carray;
  957. int n_connections;
  958. int best_support = -1;
  959. int n_best_support=0;
  960. smartlist_t *sl, *preferredexits, *excludedexits;
  961. routerinfo_t *router;
  962. or_options_t *options = get_options();
  963. get_connection_array(&carray, &n_connections);
  964. /* Count how many connections are waiting for a circuit to be built.
  965. * We use this for log messages now, but in the future we may depend on it.
  966. */
  967. for (i = 0; i < n_connections; ++i) {
  968. if (ap_stream_wants_exit_attention(carray[i]))
  969. ++n_pending_connections;
  970. }
  971. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  972. // n_pending_connections);
  973. /* Now we count, for each of the routers in the directory, how many
  974. * of the pending connections could possibly exit from that
  975. * router (n_supported[i]). (We can't be sure about cases where we
  976. * don't know the IP address of the pending connection.)
  977. */
  978. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  979. for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
  980. router = smartlist_get(dir->routers, i);
  981. if (router_is_me(router)) {
  982. n_supported[i] = -1;
  983. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  984. /* XXX there's probably a reverse predecessor attack here, but
  985. * it's slow. should we take this out? -RD
  986. */
  987. continue;
  988. }
  989. if (!router->is_running) {
  990. n_supported[i] = -1;
  991. // log_fn(LOG_DEBUG,
  992. // "Skipping node %s (index %d) -- directory says it's not running.",
  993. // router->nickname, i);
  994. continue; /* skip routers that are known to be down */
  995. }
  996. if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
  997. n_supported[i] = -1;
  998. continue; /* skip routers that are not suitable */
  999. }
  1000. if (!router->is_valid &&
  1001. (!(options->_AllowInvalid & ALLOW_INVALID_EXIT) ||
  1002. router_is_unreliable(router, 1, 1, 0))) {
  1003. /* if it's invalid, and either we don't want it or it's unsuitable */
  1004. n_supported[i] = -1;
  1005. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1006. // router->nickname, i);
  1007. continue; /* skip invalid routers */
  1008. }
  1009. if (router_exit_policy_rejects_all(router)) {
  1010. n_supported[i] = -1;
  1011. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1012. // router->nickname, i);
  1013. continue; /* skip routers that reject all */
  1014. }
  1015. n_supported[i] = 0;
  1016. for (j = 0; j < n_connections; ++j) { /* iterate over connections */
  1017. if (!ap_stream_wants_exit_attention(carray[j]))
  1018. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1019. if (connection_ap_can_use_exit(carray[j], router)) {
  1020. ++n_supported[i];
  1021. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1022. // router->nickname, i, n_supported[i]);
  1023. } else {
  1024. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1025. // router->nickname, i);
  1026. }
  1027. } /* End looping over connections. */
  1028. if (n_supported[i] > best_support) {
  1029. /* If this router is better than previous ones, remember its index
  1030. * and goodness, and start counting how many routers are this good. */
  1031. best_support = n_supported[i]; n_best_support=1;
  1032. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1033. // router->nickname);
  1034. } else if (n_supported[i] == best_support) {
  1035. /* If this router is _as good_ as the best one, just increment the
  1036. * count of equally good routers.*/
  1037. ++n_best_support;
  1038. }
  1039. }
  1040. log_info(LD_CIRC,
  1041. "Found %d servers that might support %d/%d pending connections.",
  1042. n_best_support, best_support >= 0 ? best_support : 0,
  1043. n_pending_connections);
  1044. preferredexits = smartlist_create();
  1045. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1,1,1);
  1046. excludedexits = smartlist_create();
  1047. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0,0,1);
  1048. sl = smartlist_create();
  1049. /* If any routers definitely support any pending connections, choose one
  1050. * at random. */
  1051. if (best_support > 0) {
  1052. for (i = 0; i < smartlist_len(dir->routers); i++)
  1053. if (n_supported[i] == best_support)
  1054. smartlist_add(sl, smartlist_get(dir->routers, i));
  1055. smartlist_subtract(sl,excludedexits);
  1056. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1057. smartlist_intersect(sl,preferredexits);
  1058. router = routerlist_sl_choose_by_bandwidth(sl);
  1059. } else {
  1060. /* Either there are no pending connections, or no routers even seem to
  1061. * possibly support any of them. Choose a router at random that satisfies
  1062. * at least one predicted exit port. */
  1063. int try;
  1064. smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
  1065. if (best_support == -1) {
  1066. if (need_uptime || need_capacity) {
  1067. log_info(LD_CIRC,
  1068. "We couldn't find any live%s%s routers; falling back "
  1069. "to list of all routers.",
  1070. need_capacity?", fast":"",
  1071. need_uptime?", stable":"");
  1072. return choose_good_exit_server_general(dir, 0, 0);
  1073. }
  1074. log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
  1075. "doomed exit at random.");
  1076. }
  1077. for (try = 0; try < 2; try++) {
  1078. /* try once to pick only from routers that satisfy a needed port,
  1079. * then if there are none, pick from any that support exiting. */
  1080. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1081. router = smartlist_get(dir->routers, i);
  1082. if (n_supported[i] != -1 &&
  1083. (try || router_handles_some_port(router, needed_ports))) {
  1084. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1085. // try, router->nickname);
  1086. smartlist_add(sl, router);
  1087. }
  1088. }
  1089. smartlist_subtract(sl,excludedexits);
  1090. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1091. smartlist_intersect(sl,preferredexits);
  1092. /* XXX sometimes the above results in null, when the requested
  1093. * exit node is down. we should pick it anyway. */
  1094. router = routerlist_sl_choose_by_bandwidth(sl);
  1095. if (router)
  1096. break;
  1097. }
  1098. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1099. smartlist_free(needed_ports);
  1100. }
  1101. smartlist_free(preferredexits);
  1102. smartlist_free(excludedexits);
  1103. smartlist_free(sl);
  1104. tor_free(n_supported);
  1105. if (router) {
  1106. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  1107. return router;
  1108. }
  1109. if (options->StrictExitNodes) {
  1110. log_warn(LD_CIRC,
  1111. "No specified exit routers seem to be running, and "
  1112. "StrictExitNodes is set: can't choose an exit.");
  1113. }
  1114. return NULL;
  1115. }
  1116. /** Return a pointer to a suitable router to be the exit node for the
  1117. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1118. * if no router is suitable).
  1119. *
  1120. * For general-purpose circuits, pass it off to
  1121. * choose_good_exit_server_general()
  1122. *
  1123. * For client-side rendezvous circuits, choose a random node, weighted
  1124. * toward the preferences in 'options'.
  1125. */
  1126. static routerinfo_t *
  1127. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1128. int need_uptime, int need_capacity, int is_internal)
  1129. {
  1130. or_options_t *options = get_options();
  1131. switch (purpose) {
  1132. case CIRCUIT_PURPOSE_C_GENERAL:
  1133. if (is_internal) /* pick it like a middle hop */
  1134. return router_choose_random_node(NULL, get_options()->ExcludeNodes,
  1135. NULL, need_uptime, need_capacity, 0,
  1136. get_options()->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0);
  1137. else
  1138. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  1139. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1140. return router_choose_random_node(
  1141. options->RendNodes, options->RendExcludeNodes,
  1142. NULL, need_uptime, need_capacity, 0,
  1143. options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS, 0);
  1144. }
  1145. log_warn(LD_BUG,"Bug: unhandled purpose %d", purpose);
  1146. tor_fragile_assert();
  1147. return NULL;
  1148. }
  1149. /** Decide a suitable length for circ's cpath, and pick an exit
  1150. * router (or use <b>exit</b> if provided). Store these in the
  1151. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1152. static int
  1153. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1154. {
  1155. cpath_build_state_t *state = circ->build_state;
  1156. routerlist_t *rl = router_get_routerlist();
  1157. int r;
  1158. r = new_route_len(get_options()->PathlenCoinWeight, circ->_base.purpose,
  1159. exit, rl->routers);
  1160. if (r < 1) /* must be at least 1 */
  1161. return -1;
  1162. state->desired_path_len = r;
  1163. if (exit) { /* the circuit-builder pre-requested one */
  1164. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  1165. exit = extend_info_dup(exit);
  1166. } else { /* we have to decide one */
  1167. routerinfo_t *router =
  1168. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  1169. state->need_capacity, state->is_internal);
  1170. if (!router) {
  1171. log_warn(LD_CIRC,"failed to choose an exit server");
  1172. return -1;
  1173. }
  1174. exit = extend_info_from_router(router);
  1175. }
  1176. state->chosen_exit = exit;
  1177. return 0;
  1178. }
  1179. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1180. * hop to the cpath reflecting this. Don't send the next extend cell --
  1181. * the caller will do this if it wants to.
  1182. */
  1183. int
  1184. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *info)
  1185. {
  1186. cpath_build_state_t *state;
  1187. tor_assert(info);
  1188. tor_assert(circ);
  1189. state = circ->build_state;
  1190. tor_assert(state);
  1191. if (state->chosen_exit)
  1192. extend_info_free(state->chosen_exit);
  1193. state->chosen_exit = extend_info_dup(info);
  1194. ++circ->build_state->desired_path_len;
  1195. onion_append_hop(&circ->cpath, info);
  1196. return 0;
  1197. }
  1198. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1199. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1200. * send the next extend cell to begin connecting to that hop.
  1201. */
  1202. int
  1203. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *info)
  1204. {
  1205. circuit_append_new_exit(circ, info);
  1206. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1207. if (circuit_send_next_onion_skin(circ)<0) {
  1208. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  1209. info->nickname);
  1210. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1211. return -1;
  1212. }
  1213. return 0;
  1214. }
  1215. /** Return the number of routers in <b>routers</b> that are currently up
  1216. * and available for building circuits through.
  1217. */
  1218. static int
  1219. count_acceptable_routers(smartlist_t *routers)
  1220. {
  1221. int i, n;
  1222. int num=0;
  1223. routerinfo_t *r;
  1224. n = smartlist_len(routers);
  1225. for (i=0;i<n;i++) {
  1226. r = smartlist_get(routers, i);
  1227. // log_debug(LD_CIRC,
  1228. // "Contemplating whether router %d (%s) is a new option.",
  1229. // i, r->nickname);
  1230. if (r->is_running == 0) {
  1231. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1232. goto next_i_loop;
  1233. }
  1234. if (r->is_valid == 0) {
  1235. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1236. goto next_i_loop;
  1237. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1238. * allows this node in some places, then we're getting an inaccurate
  1239. * count. For now, be conservative and don't count it. But later we
  1240. * should try to be smarter. */
  1241. }
  1242. num++;
  1243. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1244. next_i_loop:
  1245. ; /* C requires an explicit statement after the label */
  1246. }
  1247. return num;
  1248. }
  1249. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1250. * This function is used to extend cpath by another hop.
  1251. */
  1252. void
  1253. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1254. {
  1255. if (*head_ptr) {
  1256. new_hop->next = (*head_ptr);
  1257. new_hop->prev = (*head_ptr)->prev;
  1258. (*head_ptr)->prev->next = new_hop;
  1259. (*head_ptr)->prev = new_hop;
  1260. } else {
  1261. *head_ptr = new_hop;
  1262. new_hop->prev = new_hop->next = new_hop;
  1263. }
  1264. }
  1265. /** Pick a random server digest that's running a Tor version that
  1266. * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
  1267. * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
  1268. * probably already connected to them.
  1269. *
  1270. * We only return one, so this doesn't become stupid when the
  1271. * whole network has upgraded. */
  1272. static char *
  1273. compute_preferred_testing_list(const char *answer)
  1274. {
  1275. smartlist_t *choices;
  1276. routerlist_t *rl = router_get_routerlist();
  1277. routerinfo_t *router;
  1278. char *s;
  1279. if (answer) /* they have one in mind -- easy */
  1280. return tor_strdup(answer);
  1281. choices = smartlist_create();
  1282. /* now count up our choices */
  1283. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1284. if (r->is_running && r->is_valid &&
  1285. ((tor_version_as_new_as(r->platform,"0.1.1.21-cvs") &&
  1286. !tor_version_as_new_as(r->platform,"0.1.2.0-alpha-cvs")) ||
  1287. tor_version_as_new_as(r->platform,"0.1.2.1-alpha")) &&
  1288. !router_get_trusteddirserver_by_digest(r->cache_info.identity_digest))
  1289. smartlist_add(choices, r));
  1290. router = smartlist_choose(choices);
  1291. smartlist_free(choices);
  1292. if (!router) {
  1293. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1294. "reachability bug, but didn't find one. Oh well.");
  1295. return NULL;
  1296. }
  1297. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1298. "reachability bug, and chose '%s'. Great.", router->nickname);
  1299. s = tor_malloc(HEX_DIGEST_LEN+2);
  1300. s[0] = '$';
  1301. base16_encode(s+1, HEX_DIGEST_LEN+1,
  1302. router->cache_info.identity_digest, DIGEST_LEN);
  1303. return s;
  1304. }
  1305. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1306. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1307. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1308. * circuit. In particular, make sure we don't pick the exit node or its
  1309. * family, and make sure we don't duplicate any previous nodes or their
  1310. * families. */
  1311. static routerinfo_t *
  1312. choose_good_middle_server(uint8_t purpose,
  1313. cpath_build_state_t *state,
  1314. crypt_path_t *head,
  1315. int cur_len)
  1316. {
  1317. int i;
  1318. routerinfo_t *r, *choice;
  1319. crypt_path_t *cpath;
  1320. smartlist_t *excluded;
  1321. or_options_t *options = get_options();
  1322. char *preferred = NULL;
  1323. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  1324. purpose <= _CIRCUIT_PURPOSE_MAX);
  1325. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1326. excluded = smartlist_create();
  1327. if ((r = build_state_get_exit_router(state))) {
  1328. smartlist_add(excluded, r);
  1329. routerlist_add_family(excluded, r);
  1330. }
  1331. if ((r = routerlist_find_my_routerinfo())) {
  1332. smartlist_add(excluded, r);
  1333. routerlist_add_family(excluded, r);
  1334. }
  1335. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1336. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1337. smartlist_add(excluded, r);
  1338. routerlist_add_family(excluded, r);
  1339. }
  1340. }
  1341. if (purpose == CIRCUIT_PURPOSE_TESTING)
  1342. preferred = compute_preferred_testing_list(options->TestVia);
  1343. choice = router_choose_random_node(preferred,
  1344. options->ExcludeNodes, excluded,
  1345. state->need_uptime, state->need_capacity, 0,
  1346. options->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0);
  1347. if (preferred)
  1348. tor_free(preferred);
  1349. smartlist_free(excluded);
  1350. return choice;
  1351. }
  1352. /** Pick a good entry server for the circuit to be built according to
  1353. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1354. * router (if we're an OR), and respect firewall settings; if we're
  1355. * using entry_guards, return one.
  1356. *
  1357. * If <b>state</b> is NULL, we're choosing routers to serve as entry
  1358. * nodes, not for any particular circuit.
  1359. */
  1360. static routerinfo_t *
  1361. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1362. {
  1363. routerinfo_t *r, *choice;
  1364. smartlist_t *excluded;
  1365. or_options_t *options = get_options();
  1366. (void)purpose; /* not used yet. */
  1367. if (state && options->UseEntryGuards) {
  1368. return choose_random_entry(state);
  1369. }
  1370. excluded = smartlist_create();
  1371. if (state && (r = build_state_get_exit_router(state))) {
  1372. smartlist_add(excluded, r);
  1373. routerlist_add_family(excluded, r);
  1374. }
  1375. if ((r = routerlist_find_my_routerinfo())) {
  1376. smartlist_add(excluded, r);
  1377. routerlist_add_family(excluded, r);
  1378. }
  1379. if (firewall_is_fascist_or()) {
  1380. /* exclude all ORs that listen on the wrong port */
  1381. routerlist_t *rl = router_get_routerlist();
  1382. int i;
  1383. for (i=0; i < smartlist_len(rl->routers); i++) {
  1384. r = smartlist_get(rl->routers, i);
  1385. if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
  1386. smartlist_add(excluded, r);
  1387. }
  1388. }
  1389. /* and exclude current entry guards, if applicable */
  1390. if (options->UseEntryGuards && entry_guards) {
  1391. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1392. {
  1393. if ((r = router_get_by_digest(entry->identity)))
  1394. smartlist_add(excluded, r);
  1395. });
  1396. }
  1397. // XXX we should exclude busy exit nodes here, too,
  1398. // but only if there are enough other nodes available.
  1399. choice = router_choose_random_node(
  1400. NULL, options->ExcludeNodes,
  1401. excluded, state ? state->need_uptime : 0,
  1402. state ? state->need_capacity : 0,
  1403. state ? 0 : 1,
  1404. options->_AllowInvalid & ALLOW_INVALID_ENTRY, 0);
  1405. smartlist_free(excluded);
  1406. return choice;
  1407. }
  1408. /** Return the first non-open hop in cpath, or return NULL if all
  1409. * hops are open. */
  1410. static crypt_path_t *
  1411. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1412. {
  1413. crypt_path_t *hop = cpath;
  1414. do {
  1415. if (hop->state != CPATH_STATE_OPEN)
  1416. return hop;
  1417. hop = hop->next;
  1418. } while (hop != cpath);
  1419. return NULL;
  1420. }
  1421. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1422. * based on <b>state</b>. Append the hop info to head_ptr.
  1423. */
  1424. static int
  1425. onion_extend_cpath(uint8_t purpose, crypt_path_t **head_ptr,
  1426. cpath_build_state_t *state)
  1427. {
  1428. int cur_len;
  1429. crypt_path_t *cpath;
  1430. extend_info_t *info = NULL;
  1431. tor_assert(head_ptr);
  1432. if (!*head_ptr) {
  1433. cur_len = 0;
  1434. } else {
  1435. cur_len = 1;
  1436. for (cpath = *head_ptr; cpath->next != *head_ptr; cpath = cpath->next) {
  1437. ++cur_len;
  1438. }
  1439. }
  1440. if (cur_len >= state->desired_path_len) {
  1441. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1442. state->desired_path_len);
  1443. return 1;
  1444. }
  1445. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1446. state->desired_path_len);
  1447. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1448. info = extend_info_dup(state->chosen_exit);
  1449. } else if (cur_len == 0) { /* picking first node */
  1450. routerinfo_t *r = choose_good_entry_server(purpose, state);
  1451. if (r)
  1452. info = extend_info_from_router(r);
  1453. } else {
  1454. routerinfo_t *r =
  1455. choose_good_middle_server(purpose, state, *head_ptr, cur_len);
  1456. if (r)
  1457. info = extend_info_from_router(r);
  1458. }
  1459. if (!info) {
  1460. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1461. "this circuit.", cur_len);
  1462. return -1;
  1463. }
  1464. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1465. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  1466. onion_append_hop(head_ptr, info);
  1467. extend_info_free(info);
  1468. return 0;
  1469. }
  1470. /** Create a new hop, annotate it with information about its
  1471. * corresponding router <b>choice</b>, and append it to the
  1472. * end of the cpath <b>head_ptr</b>. */
  1473. static int
  1474. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1475. {
  1476. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1477. /* link hop into the cpath, at the end. */
  1478. onion_append_to_cpath(head_ptr, hop);
  1479. hop->magic = CRYPT_PATH_MAGIC;
  1480. hop->state = CPATH_STATE_CLOSED;
  1481. hop->extend_info = extend_info_dup(choice);
  1482. hop->package_window = CIRCWINDOW_START;
  1483. hop->deliver_window = CIRCWINDOW_START;
  1484. return 0;
  1485. }
  1486. /** Allocate and return a new extend_info_t that can be used to build a
  1487. * circuit to or through the router <b>r</b>. */
  1488. extend_info_t *
  1489. extend_info_from_router(routerinfo_t *r)
  1490. {
  1491. extend_info_t *info;
  1492. tor_assert(r);
  1493. info = tor_malloc_zero(sizeof(extend_info_t));
  1494. strlcpy(info->nickname, r->nickname, sizeof(info->nickname));
  1495. memcpy(info->identity_digest, r->cache_info.identity_digest, DIGEST_LEN);
  1496. info->onion_key = crypto_pk_dup_key(r->onion_pkey);
  1497. info->addr = r->addr;
  1498. info->port = r->or_port;
  1499. return info;
  1500. }
  1501. /** Release storage held by an extend_info_t struct. */
  1502. void
  1503. extend_info_free(extend_info_t *info)
  1504. {
  1505. tor_assert(info);
  1506. crypto_free_pk_env(info->onion_key);
  1507. tor_free(info);
  1508. }
  1509. /** Allocate and return a new extend_info_t with the same contents as
  1510. * <b>info</b>. */
  1511. extend_info_t *
  1512. extend_info_dup(extend_info_t *info)
  1513. {
  1514. extend_info_t *newinfo;
  1515. tor_assert(info);
  1516. newinfo = tor_malloc(sizeof(extend_info_t));
  1517. memcpy(newinfo, info, sizeof(extend_info_t));
  1518. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1519. return newinfo;
  1520. }
  1521. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1522. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1523. * the chosen exit, return NULL.
  1524. */
  1525. routerinfo_t *
  1526. build_state_get_exit_router(cpath_build_state_t *state)
  1527. {
  1528. if (!state || !state->chosen_exit)
  1529. return NULL;
  1530. return router_get_by_digest(state->chosen_exit->identity_digest);
  1531. }
  1532. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1533. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1534. * chosen exit, return NULL.
  1535. */
  1536. const char *
  1537. build_state_get_exit_nickname(cpath_build_state_t *state)
  1538. {
  1539. if (!state || !state->chosen_exit)
  1540. return NULL;
  1541. return state->chosen_exit->nickname;
  1542. }
  1543. /** Return the router corresponding to <b>e</b>, if <b>e</b> is
  1544. * working well enough that we are willing to use it as an entry
  1545. * right now. (Else return NULL.) In particular, it must be
  1546. * - Listed as either up or never yet contacted;
  1547. * - Present in the routerlist;
  1548. * - Listed as 'stable' or 'fast' by the current dirserver concensus,
  1549. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>; and
  1550. * - Allowed by our current ReachableAddresses config option.
  1551. */
  1552. static INLINE routerinfo_t *
  1553. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity)
  1554. {
  1555. routerinfo_t *r;
  1556. if (e->down_since && e->made_contact)
  1557. return NULL;
  1558. r = router_get_by_digest(e->identity);
  1559. if (!r)
  1560. return NULL;
  1561. if (router_is_unreliable(r, need_uptime, need_capacity, 0))
  1562. return NULL;
  1563. if (firewall_is_fascist_or() &&
  1564. !fascist_firewall_allows_address_or(r->addr,r->or_port))
  1565. return NULL;
  1566. return r;
  1567. }
  1568. /** Return the number of entry guards that we think are usable. */
  1569. static int
  1570. num_live_entry_guards(void)
  1571. {
  1572. int n = 0;
  1573. if (! entry_guards)
  1574. return 0;
  1575. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1576. {
  1577. if (entry_is_live(entry, 0, 1))
  1578. ++n;
  1579. });
  1580. return n;
  1581. }
  1582. /** Return 1 if <b>digest</b> matches the identity of any node
  1583. * in the entry_guards list. Else return 0. */
  1584. static INLINE int
  1585. is_an_entry_guard(char *digest)
  1586. {
  1587. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1588. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  1589. return 1;
  1590. );
  1591. return 0;
  1592. }
  1593. static void
  1594. log_entry_guards(int severity)
  1595. {
  1596. smartlist_t *elements = smartlist_create();
  1597. char buf[1024];
  1598. char *s;
  1599. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1600. {
  1601. tor_snprintf(buf, sizeof(buf), "%s (%s%s%s)",
  1602. e->nickname,
  1603. (e->down_since || e->unlisted_since) ? "down " : "up ",
  1604. e->unlisted_since ? "unlisted " : "listed ",
  1605. e->made_contact ? "made-contact" : "never-contacted");
  1606. smartlist_add(elements, tor_strdup(buf));
  1607. });
  1608. s = smartlist_join_strings(elements, ",", 0, NULL);
  1609. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1610. smartlist_free(elements);
  1611. log_fn(severity,LD_CIRC,"%s",s);
  1612. tor_free(s);
  1613. }
  1614. #define NUM_ENTRY_PICK_TRIES 100
  1615. /** Add a new (preferably stable and fast) router to our
  1616. * entry_guards list. Return a pointer to the router if we succeed,
  1617. * or NULL if we can't find any more suitable entries.
  1618. *
  1619. * If <b>chosen</b> is defined, use that one, and if it's not
  1620. * already in our entry_guards list, put it at the *beginning*.
  1621. * Else, put the one we pick at the end of the list. */
  1622. static routerinfo_t *
  1623. add_an_entry_guard(routerinfo_t *chosen)
  1624. {
  1625. routerinfo_t *router;
  1626. entry_guard_t *entry;
  1627. if (chosen) {
  1628. router = chosen;
  1629. if (is_an_entry_guard(router->cache_info.identity_digest))
  1630. return NULL;
  1631. } else {
  1632. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  1633. if (!router)
  1634. return NULL;
  1635. }
  1636. entry = tor_malloc_zero(sizeof(entry_guard_t));
  1637. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  1638. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  1639. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  1640. if (chosen) /* prepend */
  1641. smartlist_insert(entry_guards, 0, entry);
  1642. else /* append */
  1643. smartlist_add(entry_guards, entry);
  1644. log_entry_guards(LOG_INFO);
  1645. return router;
  1646. }
  1647. /** If the use of entry guards is configured, choose more entry guards
  1648. * until we have enough in the list. */
  1649. static void
  1650. pick_entry_guards(void)
  1651. {
  1652. or_options_t *options = get_options();
  1653. int changed = 0;
  1654. tor_assert(entry_guards);
  1655. while (num_live_entry_guards() < options->NumEntryGuards) {
  1656. if (!add_an_entry_guard(NULL))
  1657. break;
  1658. changed = 1;
  1659. }
  1660. if (changed)
  1661. entry_guards_changed();
  1662. }
  1663. /** Release all storage held by the list of entry guards. */
  1664. void
  1665. entry_guards_free_all(void)
  1666. {
  1667. if (entry_guards) {
  1668. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  1669. smartlist_free(entry_guards);
  1670. entry_guards = NULL;
  1671. }
  1672. }
  1673. /** How long (in seconds) do we allow an entry guard to be nonfunctional
  1674. * before we give up on it? */
  1675. #define ENTRY_ALLOW_DOWNTIME (30*24*60*60)
  1676. /** How long (in seconds) do we allow an entry guard to be unlisted in the
  1677. * directory before we give up on it? */
  1678. #define ENTRY_ALLOW_UNLISTED (30*24*60*60)
  1679. /** Remove all entry guards that have been down or unlisted for so
  1680. * long that we don't think they'll come up again. Return 1 if we
  1681. * removed any, or 0 if we did nothing. */
  1682. static int
  1683. remove_dead_entries(void)
  1684. {
  1685. char dbuf[HEX_DIGEST_LEN+1];
  1686. char tbuf[ISO_TIME_LEN+1];
  1687. time_t now = time(NULL);
  1688. int i;
  1689. int changed = 0;
  1690. for (i = 0; i < smartlist_len(entry_guards); ) {
  1691. entry_guard_t *entry = smartlist_get(entry_guards, i);
  1692. const char *why = NULL;
  1693. time_t since = 0;
  1694. if (entry->unlisted_since &&
  1695. entry->unlisted_since + ENTRY_ALLOW_UNLISTED < now) {
  1696. why = "unlisted";
  1697. since = entry->unlisted_since;
  1698. } else if (entry->down_since &&
  1699. entry->down_since + ENTRY_ALLOW_DOWNTIME < now) {
  1700. why = "down";
  1701. since = entry->down_since;
  1702. }
  1703. if (why) {
  1704. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  1705. format_local_iso_time(tbuf, since);
  1706. log_info(LD_CIRC,
  1707. "Entry guard '%s' (%s) has been %s since %s; removing.",
  1708. entry->nickname, dbuf, why, tbuf);
  1709. tor_free(entry);
  1710. smartlist_del_keeporder(entry_guards, i);
  1711. log_entry_guards(LOG_INFO);
  1712. changed = 1;
  1713. } else
  1714. ++i;
  1715. }
  1716. return changed ? 1 : 0;
  1717. }
  1718. /** A new directory or router-status has arrived; update the down/listed
  1719. * status of the entry guards.
  1720. *
  1721. * An entry is 'down' if the directory lists it as nonrunning.
  1722. * An entry is 'unlisted' if the directory doesn't include it.
  1723. */
  1724. void
  1725. entry_guards_set_status_from_directory(void)
  1726. {
  1727. /* Don't call this on startup; only on a fresh download. Otherwise we'll
  1728. * think that things are unlisted. */
  1729. routerlist_t *routers;
  1730. time_t now;
  1731. int changed = 0;
  1732. int severity = LOG_INFO;
  1733. if (! entry_guards)
  1734. return;
  1735. routers = router_get_routerlist();
  1736. now = time(NULL);
  1737. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1738. {
  1739. routerinfo_t *r = router_get_by_digest(entry->identity);
  1740. if (! r) {
  1741. if (! entry->unlisted_since) {
  1742. entry->unlisted_since = time(NULL);
  1743. changed = 1;
  1744. log_info(LD_CIRC,"Entry guard '%s' is not listed by directories.",
  1745. entry->nickname);
  1746. severity = LOG_INFO;
  1747. }
  1748. } else {
  1749. if (entry->unlisted_since) {
  1750. log_info(LD_CIRC,"Entry guard '%s' is listed again by directories.",
  1751. entry->nickname);
  1752. changed = 1;
  1753. severity = LOG_INFO;
  1754. }
  1755. entry->unlisted_since = 0;
  1756. if (! r->is_running) {
  1757. if (! entry->down_since) {
  1758. entry->down_since = now;
  1759. log_info(LD_CIRC, "Entry guard '%s' is now down.",
  1760. entry->nickname);
  1761. changed = 1;
  1762. severity = LOG_INFO;
  1763. }
  1764. } else {
  1765. if (entry->down_since) {
  1766. log_info(LD_CIRC,"Entry guard '%s' is up in latest directories.",
  1767. entry->nickname);
  1768. changed = 1;
  1769. }
  1770. entry->down_since = 0;
  1771. }
  1772. }
  1773. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s, and %s.",
  1774. entry->nickname,
  1775. (entry->down_since || entry->unlisted_since) ? "down" : "up",
  1776. entry->unlisted_since ? "unlisted" : "listed",
  1777. entry_is_live(entry, 0, 1) ? "live" : "not live");
  1778. });
  1779. if (remove_dead_entries())
  1780. changed = 1;
  1781. if (changed) {
  1782. log_fn(severity, LD_CIRC, " (%d/%d entry guards are usable/new)",
  1783. num_live_entry_guards(), smartlist_len(entry_guards));
  1784. log_entry_guards(LOG_INFO);
  1785. entry_guards_changed();
  1786. }
  1787. }
  1788. /** Called when a connection to an OR with the identity digest <b>digest</b>
  1789. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  1790. * If the OR is an entry, change that entry's up/down status.
  1791. * Return 0 normally, or -1 if we want to tear down the new connection.
  1792. */
  1793. int
  1794. entry_guard_set_status(const char *digest, int succeeded)
  1795. {
  1796. int changed = 0;
  1797. int refuse_conn = 0;
  1798. if (! entry_guards)
  1799. return 0;
  1800. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1801. {
  1802. if (!memcmp(entry->identity, digest, DIGEST_LEN)) {
  1803. if (succeeded) {
  1804. if (!entry->made_contact) {
  1805. /* We've just added a new long-term entry guard. Perhaps
  1806. * the network just came back? We should give our earlier
  1807. * entries another try too, and close this connection so
  1808. * we don't use it before we've given the others a shot. */
  1809. entry->made_contact = 1;
  1810. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1811. {
  1812. routerinfo_t *r;
  1813. if (e == entry)
  1814. break;
  1815. if (e->made_contact) {
  1816. e->down_since = 0;
  1817. r = entry_is_live(e, 0, 1);
  1818. if (r) {
  1819. refuse_conn = 1;
  1820. r->is_running = 1;
  1821. }
  1822. }
  1823. });
  1824. log_info(LD_CIRC,
  1825. "Connected to new entry guard '%s'. Marking earlier "
  1826. "entry guards up. %d/%d entry guards usable/new.",
  1827. entry->nickname,
  1828. num_live_entry_guards(), smartlist_len(entry_guards));
  1829. log_entry_guards(LOG_INFO);
  1830. changed = 1;
  1831. }
  1832. if (entry->down_since) {
  1833. entry->down_since = 0;
  1834. log_info(LD_CIRC,
  1835. "Connection to formerly down entry guard '%s' succeeded. "
  1836. "%d/%d entry guards usable/new.", entry->nickname,
  1837. num_live_entry_guards(), smartlist_len(entry_guards));
  1838. log_entry_guards(LOG_INFO);
  1839. changed = 1;
  1840. }
  1841. } else {
  1842. if (!entry->made_contact) { /* dump him */
  1843. log_info(LD_CIRC,
  1844. "Connection to never-contacted entry guard '%s' failed. "
  1845. "Removing from the list. %d/%d entry guards usable/new.",
  1846. entry->nickname,
  1847. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  1848. tor_free(entry);
  1849. smartlist_del_keeporder(entry_guards, entry_sl_idx);
  1850. log_entry_guards(LOG_INFO);
  1851. changed = 1;
  1852. } else if (!entry->down_since) {
  1853. entry->down_since = time(NULL);
  1854. log_info(LD_CIRC, "Connection to entry guard '%s' failed. "
  1855. "%d/%d entry guards usable/new.",
  1856. entry->nickname,
  1857. num_live_entry_guards(), smartlist_len(entry_guards));
  1858. log_entry_guards(LOG_INFO);
  1859. changed = 1;
  1860. }
  1861. }
  1862. }
  1863. });
  1864. if (changed)
  1865. entry_guards_changed();
  1866. return refuse_conn ? -1 : 0;
  1867. }
  1868. /** When we try to choose an entry guard, should we parse and add
  1869. * config's EntryNodes first? */
  1870. static int should_add_entry_nodes = 0;
  1871. void
  1872. entry_nodes_should_be_added(void)
  1873. {
  1874. log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
  1875. should_add_entry_nodes = 1;
  1876. }
  1877. void
  1878. entry_guards_prepend_from_config(void)
  1879. {
  1880. int missed_some = 0;
  1881. int idx;
  1882. or_options_t *options = get_options();
  1883. smartlist_t *routers = smartlist_create();
  1884. smartlist_t *tmp = smartlist_create();
  1885. tor_assert(entry_guards);
  1886. tor_assert(options->EntryNodes);
  1887. if (options->StrictEntryNodes) {
  1888. log_info(LD_CIRC,"Clearing old entry guards");
  1889. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  1890. smartlist_clear(entry_guards);
  1891. entry_guards_changed();
  1892. }
  1893. add_nickname_list_to_smartlist(routers, options->EntryNodes,
  1894. 0, 1, 1);
  1895. /* take a moment first to notice whether we got them all */
  1896. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
  1897. options->EntryNodes);
  1898. smartlist_split_string(tmp, options->EntryNodes, ",",
  1899. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1900. missed_some = smartlist_len(routers) != smartlist_len(tmp);
  1901. SMARTLIST_FOREACH(tmp, char *, nick, tor_free(nick));
  1902. smartlist_free(tmp);
  1903. for (idx = smartlist_len(routers)-1 ; idx >= 0; idx--) {
  1904. /* pick off the last one, turn it into a router, prepend it
  1905. * to our entry_guards list. If we can't find it, set missed_some
  1906. * to 1. */
  1907. routerinfo_t *r = smartlist_get(routers, idx);
  1908. add_an_entry_guard(r);
  1909. }
  1910. if (!missed_some)
  1911. should_add_entry_nodes = 0; /* whew, we're done */
  1912. smartlist_free(routers);
  1913. }
  1914. /** Pick a live (up and listed) entry guard from entry_guards, and
  1915. * make sure not to pick this circuit's exit. */
  1916. static routerinfo_t *
  1917. choose_random_entry(cpath_build_state_t *state)
  1918. {
  1919. or_options_t *options = get_options();
  1920. smartlist_t *live_entry_guards = smartlist_create();
  1921. routerinfo_t *chosen_exit = build_state_get_exit_router(state);
  1922. routerinfo_t *r = NULL;
  1923. int need_uptime = state->need_uptime;
  1924. int need_capacity = state->need_capacity;
  1925. if (!entry_guards)
  1926. entry_guards = smartlist_create();
  1927. if (should_add_entry_nodes)
  1928. entry_guards_prepend_from_config();
  1929. if (!options->StrictEntryNodes &&
  1930. (! entry_guards ||
  1931. smartlist_len(entry_guards) < options->NumEntryGuards))
  1932. pick_entry_guards();
  1933. retry:
  1934. smartlist_clear(live_entry_guards);
  1935. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1936. {
  1937. r = entry_is_live(entry, need_uptime, need_capacity);
  1938. if (r && r != chosen_exit) {
  1939. smartlist_add(live_entry_guards, r);
  1940. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  1941. break; /* we have enough */
  1942. }
  1943. });
  1944. /* Try to have at least 2 choices available. This way we don't
  1945. * get stuck with a single live-but-crummy entry and just keep
  1946. * using him.
  1947. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  1948. if (smartlist_len(live_entry_guards) < 2) {
  1949. if (need_uptime) {
  1950. need_uptime = 0; /* try without that requirement */
  1951. goto retry;
  1952. }
  1953. if (!options->StrictEntryNodes) {
  1954. /* still no? try adding a new entry then */
  1955. r = add_an_entry_guard(NULL);
  1956. if (r) {
  1957. smartlist_add(live_entry_guards, r);
  1958. entry_guards_changed();
  1959. }
  1960. }
  1961. if (!r && need_capacity) {
  1962. /* still no? last attempt, try without requiring capacity */
  1963. need_capacity = 0;
  1964. goto retry;
  1965. }
  1966. /* live_entry_guards will be empty below. Oh well, we tried. */
  1967. }
  1968. r = smartlist_choose(live_entry_guards);
  1969. smartlist_free(live_entry_guards);
  1970. return r;
  1971. }
  1972. /** Parse <b>state</b> and learn about the entry guards it describes.
  1973. * If <b>set</b> is true, and there are no errors, replace the global
  1974. * entry_list with what we find.
  1975. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  1976. * describing the error, and return -1.
  1977. */
  1978. int
  1979. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  1980. {
  1981. entry_guard_t *node = NULL;
  1982. smartlist_t *new_entry_guards = smartlist_create();
  1983. config_line_t *line;
  1984. *msg = NULL;
  1985. for (line = state->EntryGuards; line; line = line->next) {
  1986. if (!strcasecmp(line->key, "EntryGuard")) {
  1987. smartlist_t *args = smartlist_create();
  1988. node = tor_malloc_zero(sizeof(entry_guard_t));
  1989. /* all entry guards on disk have been contacted */
  1990. node->made_contact = 1;
  1991. smartlist_add(new_entry_guards, node);
  1992. smartlist_split_string(args, line->value, " ",
  1993. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1994. if (smartlist_len(args)<2) {
  1995. *msg = tor_strdup("Unable to parse entry nodes: "
  1996. "Too few arguments to EntryGuard");
  1997. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  1998. *msg = tor_strdup("Unable to parse entry nodes: "
  1999. "Bad nickname for EntryGuard");
  2000. } else {
  2001. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  2002. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  2003. strlen(smartlist_get(args,1)))<0) {
  2004. *msg = tor_strdup("Unable to parse entry nodes: "
  2005. "Bad hex digest for EntryGuard");
  2006. }
  2007. }
  2008. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  2009. smartlist_free(args);
  2010. if (*msg)
  2011. break;
  2012. } else {
  2013. time_t when;
  2014. if (!node) {
  2015. *msg = tor_strdup("Unable to parse entry nodes: "
  2016. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  2017. break;
  2018. }
  2019. if (parse_iso_time(line->value, &when)<0) {
  2020. *msg = tor_strdup("Unable to parse entry nodes: "
  2021. "Bad time in EntryGuardDownSince/UnlistedSince");
  2022. break;
  2023. }
  2024. if (!strcasecmp(line->key, "EntryGuardDownSince"))
  2025. node->down_since = when;
  2026. else
  2027. node->unlisted_since = when;
  2028. }
  2029. }
  2030. if (*msg || !set) {
  2031. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e, tor_free(e));
  2032. smartlist_free(new_entry_guards);
  2033. } else { /* !*err && set */
  2034. if (entry_guards) {
  2035. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
  2036. smartlist_free(entry_guards);
  2037. }
  2038. entry_guards = new_entry_guards;
  2039. entry_guards_dirty = 0;
  2040. }
  2041. return *msg ? -1 : 0;
  2042. }
  2043. /** Our list of entry guards has changed, or some element of one
  2044. * of our entry guards has changed. Write the changes to disk. */
  2045. static void
  2046. entry_guards_changed(void)
  2047. {
  2048. entry_guards_dirty = 1;
  2049. or_state_save();
  2050. }
  2051. /** If the entry guard info has not changed, do nothing and return.
  2052. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2053. * a new one out of the global entry_guards list, and then mark
  2054. * <b>state</b> dirty so it will get saved to disk.
  2055. */
  2056. void
  2057. entry_guards_update_state(or_state_t *state)
  2058. {
  2059. config_line_t **next, *line;
  2060. if (! entry_guards_dirty)
  2061. return;
  2062. config_free_lines(state->EntryGuards);
  2063. next = &state->EntryGuards;
  2064. *next = NULL;
  2065. if (!entry_guards)
  2066. entry_guards = smartlist_create();
  2067. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2068. {
  2069. char dbuf[HEX_DIGEST_LEN+1];
  2070. if (!e->made_contact)
  2071. continue; /* don't write this one to disk */
  2072. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2073. line->key = tor_strdup("EntryGuard");
  2074. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  2075. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  2076. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  2077. "%s %s", e->nickname, dbuf);
  2078. next = &(line->next);
  2079. if (e->down_since) {
  2080. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2081. line->key = tor_strdup("EntryGuardDownSince");
  2082. line->value = tor_malloc(ISO_TIME_LEN+1);
  2083. format_iso_time(line->value, e->down_since);
  2084. next = &(line->next);
  2085. }
  2086. if (e->unlisted_since) {
  2087. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2088. line->key = tor_strdup("EntryGuardUnlistedSince");
  2089. line->value = tor_malloc(ISO_TIME_LEN+1);
  2090. format_iso_time(line->value, e->unlisted_since);
  2091. next = &(line->next);
  2092. }
  2093. });
  2094. state->dirty = 1;
  2095. entry_guards_dirty = 0;
  2096. }
  2097. /** If <b>question</b> is the string "entry-guards", then dump
  2098. * to *<b>answer</b> a newly allocated string describing all of
  2099. * the nodes in the global entry_guards list. See control-spec.txt
  2100. * for details.
  2101. * For backward compatibility, we also handle the string "helper-nodes".
  2102. * */
  2103. int
  2104. entry_guards_getinfo(const char *question, char **answer)
  2105. {
  2106. if (!strcmp(question,"entry-guards") ||
  2107. !strcmp(question,"helper-nodes")) {
  2108. smartlist_t *sl = smartlist_create();
  2109. char tbuf[ISO_TIME_LEN+1];
  2110. char dbuf[HEX_DIGEST_LEN+1];
  2111. if (!entry_guards)
  2112. entry_guards = smartlist_create();
  2113. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2114. {
  2115. size_t len = HEX_DIGEST_LEN+ISO_TIME_LEN+32;
  2116. char *c = tor_malloc(len);
  2117. const char *status = NULL;
  2118. time_t when = 0;
  2119. if (!e->made_contact) {
  2120. status = "never-connected";
  2121. } else if (e->unlisted_since) {
  2122. when = e->unlisted_since;
  2123. status = "unlisted";
  2124. } else if (e->down_since) {
  2125. when = e->down_since;
  2126. status = "down";
  2127. } else {
  2128. status = "up";
  2129. }
  2130. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  2131. if (when) {
  2132. format_iso_time(tbuf, when);
  2133. tor_snprintf(c, len, "$%s %s %s\n", dbuf, status, tbuf);
  2134. } else {
  2135. tor_snprintf(c, len, "$%s %s\n", dbuf, status);
  2136. }
  2137. smartlist_add(sl, c);
  2138. });
  2139. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2140. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2141. smartlist_free(sl);
  2142. }
  2143. return 0;
  2144. }