routerparse.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432
  1. /* oCpyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerparse_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerparse.c
  10. * \brief Code to parse and validate router descriptors and directories.
  11. **/
  12. #include "or.h"
  13. /****************************************************************************/
  14. /** Enumeration of possible token types. The ones starting with K_
  15. * correspond to directory 'keywords'. _UNRECOGNIZED is for an
  16. * unrecognized keyword; _ERR is an error in the tokenizing process,
  17. * _EOF is an end-of-file marker, and _NIL is used to encode
  18. * not-a-token.
  19. */
  20. typedef enum {
  21. K_ACCEPT = 0,
  22. K_DIRECTORY_SIGNATURE,
  23. K_RECOMMENDED_SOFTWARE,
  24. K_REJECT,
  25. K_ROUTER,
  26. K_SIGNED_DIRECTORY,
  27. K_SIGNING_KEY,
  28. K_ONION_KEY,
  29. K_ROUTER_SIGNATURE,
  30. K_PUBLISHED,
  31. K_RUNNING_ROUTERS,
  32. K_ROUTER_STATUS,
  33. K_PLATFORM,
  34. K_OPT,
  35. K_BANDWIDTH,
  36. K_PORTS,
  37. K_CONTACT,
  38. K_NETWORK_STATUS,
  39. K_UPTIME,
  40. K_DIR_SIGNING_KEY,
  41. K_FAMILY,
  42. K_FINGERPRINT,
  43. K_HIBERNATING,
  44. K_READ_HISTORY,
  45. K_WRITE_HISTORY,
  46. K_NETWORK_STATUS_VERSION,
  47. K_DIR_SOURCE,
  48. K_DIR_OPTIONS,
  49. K_CLIENT_VERSIONS,
  50. K_SERVER_VERSIONS,
  51. K_R,
  52. K_S,
  53. K_V,
  54. K_EVENTDNS,
  55. K_EXTRA_INFO,
  56. K_EXTRA_INFO_DIGEST,
  57. K_CACHES_EXTRA_INFO,
  58. K_DIR_KEY_CERTIFICATE_VERSION,
  59. K_DIR_IDENTITY_KEY,
  60. K_DIR_KEY_PUBLISHED,
  61. K_DIR_KEY_EXPIRES,
  62. K_DIR_KEY_CERTIFICATION,
  63. K_VOTE_STATUS,
  64. K_VALID_UNTIL,
  65. K_KNOWN_FLAGS,
  66. K_VOTE_DIGEST,
  67. K_CONSENSUS_DIGEST,
  68. _UNRECOGNIZED,
  69. _ERR,
  70. _EOF,
  71. _NIL
  72. } directory_keyword;
  73. /** Structure to hold a single directory token.
  74. *
  75. * We parse a directory by breaking it into "tokens", each consisting
  76. * of a keyword, a line full of arguments, and a binary object. The
  77. * arguments and object are both optional, depending on the keyword
  78. * type.
  79. */
  80. typedef struct directory_token_t {
  81. directory_keyword tp; /**< Type of the token. */
  82. int n_args; /**< Number of elements in args */
  83. char **args; /**< Array of arguments from keyword line. */
  84. char *object_type; /**< -----BEGIN [object_type]-----*/
  85. size_t object_size; /**< Bytes in object_body */
  86. char *object_body; /**< Contents of object, base64-decoded. */
  87. crypto_pk_env_t *key; /**< For public keys only. */
  88. char *error; /**< For _ERR tokens only. */
  89. } directory_token_t;
  90. /* ********************************************************************** */
  91. /** We use a table of rules to decide how to parse each token type. */
  92. /** Rules for whether the keyword needs an object. */
  93. typedef enum {
  94. NO_OBJ, /**< No object, ever. */
  95. NEED_OBJ, /**< Object is required. */
  96. NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
  97. NEED_KEY, /**< Object is required, and must be a public key. */
  98. OBJ_OK, /**< Object is optional. */
  99. } obj_syntax;
  100. #define AT_START 1
  101. #define AT_END 1
  102. /** Determines the parsing rules for a single token type. */
  103. typedef struct token_rule_t {
  104. /** The string value of the keyword identifying the type of item. */
  105. const char *t;
  106. /** The corresponding directory_keyword enum. */
  107. directory_keyword v;
  108. /** Minimum number of arguments for this item */
  109. int min_args;
  110. /** Maximum number of arguments for this item */
  111. int max_args;
  112. /** If true, we concatenate all arguments for this item into a single
  113. * string. */
  114. int concat_args;
  115. /** Requirments on object syntax for this item. */
  116. obj_syntax os;
  117. /** Lowest number of times this item may appear in a document. */
  118. int min_cnt;
  119. /** Highest number of times this item may appear in a document. */
  120. int max_cnt;
  121. /** One or more of AT_START/AT_END to limit where the item may appear in a
  122. * document. */
  123. int pos;
  124. } token_rule_t;
  125. /*
  126. * Helper macros to define token tables. 's' is a string, 't' is a
  127. * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
  128. * object syntax.
  129. *
  130. */
  131. /** Appears to indicate the end of a table. */
  132. #define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0 }
  133. /** An item with no restrictions: used for obsolete document types */
  134. #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0 }
  135. /** An item with no restrictions on multiplicity or location. */
  136. #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0 }
  137. /** An item that must appear exactly once */
  138. #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0 }
  139. /** An item that must appear exactly once, at the start of the document */
  140. #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, 0, AT_START }
  141. /** An item that must appear exactly once, at the end of the document */
  142. #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, 0, AT_END }
  143. /** An item that must appear one or more times */
  144. #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0 }
  145. /** An item that must appear no more than once */
  146. #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0 }
  147. /* Argument multiplicity: any number of arguments. */
  148. #define ARGS 0,INT_MAX,0
  149. /* Argument multiplicity: no arguments. */
  150. #define NO_ARGS 0,0,0
  151. /* Argument multiplicity: concatenate all arguments. */
  152. #define CONCAT_ARGS 1,1,1
  153. /* Argument multiplicity: at least <b>n</b> arguments. */
  154. #define GE(n) n,INT_MAX,0
  155. /* Argument multiplicity: exactly <b>n</b> arguments. */
  156. #define EQ(n) n,n,0
  157. /** List of tokens allowable in router derscriptors */
  158. static token_rule_t routerdesc_token_table[] = {
  159. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  160. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  161. T1( "router", K_ROUTER, GE(5), NO_OBJ ),
  162. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  163. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  164. T1( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  165. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  166. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  167. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  168. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  169. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  170. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  171. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  172. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  173. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  174. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  175. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  176. T01("eventdns", K_EVENTDNS, ARGS, NO_OBJ ),
  177. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  178. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  179. END_OF_TABLE
  180. };
  181. /** List of tokens allowable in extra-info documents. */
  182. static token_rule_t extrainfo_token_table[] = {
  183. T1( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  184. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  185. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  186. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  187. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  188. T1( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  189. END_OF_TABLE
  190. };
  191. /** List of tokens allowable in the body part of v2 and v3 networkstatus
  192. * documents. */
  193. static token_rule_t rtrstatus_token_table[] = {
  194. T1( "r", K_R, GE(8), NO_OBJ ),
  195. T1( "s", K_S, ARGS, NO_OBJ ),
  196. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  197. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  198. END_OF_TABLE
  199. };
  200. /** List of tokens allowable in the header part of v2 networkstatus documents.
  201. */
  202. static token_rule_t netstatus_token_table[] = {
  203. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  204. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  205. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  206. /* XXXX should dir-signing-key really have ARGS? */
  207. T1( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, NEED_KEY_1024 ),
  208. T1( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  209. T1( "network-status-version", K_NETWORK_STATUS_VERSION,
  210. GE(1), NO_OBJ ),
  211. T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  212. T01("dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  213. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  214. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  215. END_OF_TABLE
  216. };
  217. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  218. * footers. */
  219. static token_rule_t dir_footer_token_table[] = {
  220. T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
  221. END_OF_TABLE
  222. };
  223. /** List of tokens allowable in v1 diectory headers/footers. */
  224. static token_rule_t dir_token_table[] = {
  225. /* don't enforce counts; this is obsolete. */
  226. T( "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ ),
  227. T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ ),
  228. T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
  229. T( "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ ),
  230. T( "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ ),
  231. T( "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ ),
  232. T( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  233. T( "opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  234. T( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  235. T( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK ),
  236. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  237. END_OF_TABLE
  238. };
  239. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  240. * footers. */
  241. #define CERTIFICATE_MEMBERS \
  242. T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
  243. GE(1), NO_OBJ ), \
  244. T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
  245. T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
  246. T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
  247. T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
  248. T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
  249. NO_ARGS, NEED_OBJ),
  250. static token_rule_t dir_key_certificate_table[] = {
  251. CERTIFICATE_MEMBERS
  252. T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  253. END_OF_TABLE
  254. };
  255. #if 0
  256. /* XXXX This stuff is commented out for now so we can avoid warnings about
  257. * unused variables. */
  258. static token_rule_t status_vote_table[] = {
  259. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  260. GE(1), NO_OBJ ),
  261. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  262. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  263. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  264. T1("known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  265. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  266. CERTIFICATE_MEMBERS
  267. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  268. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  269. T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  270. T1( "dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  271. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  272. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  273. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  274. END_OF_TABLE
  275. };
  276. static token_rule_t status_consensus_table[] = {
  277. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  278. GE(1), NO_OBJ ),
  279. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  280. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  281. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  282. CERTIFICATE_MEMBERS
  283. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  284. T1N("dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  285. T1N("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  286. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  287. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  288. #if 0
  289. T1( "dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  290. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  291. #endif
  292. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  293. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  294. END_OF_TABLE
  295. };
  296. static token_rule_t vote_footer_token_table[] = {
  297. T01("consensus-digest", K_CONSENSUS_DIGEST, EQ(1), NO_OBJ ),
  298. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  299. END_OF_TABLE
  300. };
  301. #endif
  302. #undef T
  303. /* static function prototypes */
  304. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  305. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  306. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  307. static int router_get_hash_impl(const char *s, char *digest,
  308. const char *start_str, const char *end_str);
  309. static void token_free(directory_token_t *tok);
  310. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  311. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  312. directory_keyword keyword);
  313. static int tokenize_string(const char *start, const char *end,
  314. smartlist_t *out,
  315. token_rule_t *table);
  316. static directory_token_t *get_next_token(const char **s,
  317. token_rule_t *table);
  318. static int check_signature_token(const char *digest,
  319. directory_token_t *tok,
  320. crypto_pk_env_t *pkey,
  321. int check_authority,
  322. const char *doctype);
  323. static crypto_pk_env_t *find_dir_signing_key(const char *str);
  324. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  325. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  326. * <b>s</b>. Return 0 on success, -1 on failure.
  327. */
  328. int
  329. router_get_dir_hash(const char *s, char *digest)
  330. {
  331. return router_get_hash_impl(s,digest,
  332. "signed-directory","\ndirectory-signature");
  333. }
  334. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  335. * <b>s</b>. Return 0 on success, -1 on failure.
  336. */
  337. int
  338. router_get_router_hash(const char *s, char *digest)
  339. {
  340. return router_get_hash_impl(s,digest,
  341. "router ","\nrouter-signature");
  342. }
  343. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  344. * string in <b>s</b>. Return 0 on success, -1 on failure.
  345. */
  346. int
  347. router_get_runningrouters_hash(const char *s, char *digest)
  348. {
  349. return router_get_hash_impl(s,digest,
  350. "network-status","\ndirectory-signature");
  351. }
  352. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  353. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  354. int
  355. router_get_networkstatus_v2_hash(const char *s, char *digest)
  356. {
  357. return router_get_hash_impl(s,digest,
  358. "network-status-version","\ndirectory-signature");
  359. }
  360. /** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
  361. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  362. int
  363. router_get_extrainfo_hash(const char *s, char *digest)
  364. {
  365. return router_get_hash_impl(s,digest,"extra-info","\nrouter-signature");
  366. }
  367. /** Helper: used to generate signatures for routers, directories and
  368. * network-status objects. Given a digest in <b>digest</b> and a secret
  369. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  370. * surround it with -----BEGIN/END----- pairs, and write it to the
  371. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  372. * failure.
  373. */
  374. int
  375. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  376. crypto_pk_env_t *private_key)
  377. {
  378. char *signature;
  379. int i;
  380. signature = tor_malloc(crypto_pk_keysize(private_key));
  381. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  382. log_warn(LD_BUG,"Couldn't sign digest.");
  383. goto err;
  384. }
  385. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  386. goto truncated;
  387. i = strlen(buf);
  388. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  389. log_warn(LD_BUG,"couldn't base64-encode signature");
  390. tor_free(buf);
  391. goto err;
  392. }
  393. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  394. goto truncated;
  395. tor_free(signature);
  396. return 0;
  397. truncated:
  398. log_warn(LD_BUG,"tried to exceed string length.");
  399. err:
  400. tor_free(signature);
  401. return -1;
  402. }
  403. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  404. * <b>versionlist</b>. Else, return VS_OLD if every member of
  405. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  406. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  407. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  408. * is newer than <b>myversion.</b>. Else, return VS_NEW if every memeber of
  409. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  410. * VS_UNRECOMMENDED.
  411. *
  412. * (versionlist is a comma-separated list of version strings,
  413. * optionally prefixed with "Tor". Versions that can't be parsed are
  414. * ignored.)
  415. */
  416. version_status_t
  417. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  418. {
  419. tor_version_t mine, other;
  420. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  421. found_any_in_series = 0, r, same;
  422. version_status_t ret = VS_UNRECOMMENDED;
  423. smartlist_t *version_sl;
  424. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  425. myversion, versionlist);
  426. if (tor_version_parse(myversion, &mine)) {
  427. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  428. tor_assert(0);
  429. }
  430. version_sl = smartlist_create();
  431. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  432. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  433. if (!strcmpstart(cp, "Tor "))
  434. cp += 4;
  435. if (tor_version_parse(cp, &other)) {
  436. /* Couldn't parse other; it can't be a match. */
  437. } else {
  438. same = tor_version_same_series(&mine, &other);
  439. if (same)
  440. found_any_in_series = 1;
  441. r = tor_version_compare(&mine, &other);
  442. if (r==0) {
  443. ret = VS_RECOMMENDED;
  444. goto done;
  445. } else if (r<0) {
  446. found_newer = 1;
  447. if (same)
  448. found_newer_in_series = 1;
  449. } else if (r>0) {
  450. found_older = 1;
  451. }
  452. }
  453. });
  454. /* We didn't find the listed version. Is it new or old? */
  455. if (found_any_in_series && !found_newer_in_series && found_newer) {
  456. ret = VS_NEW_IN_SERIES;
  457. } else if (found_newer && !found_older) {
  458. ret = VS_OLD;
  459. } else if (found_older && !found_newer) {
  460. ret = VS_NEW;
  461. } else {
  462. ret = VS_UNRECOMMENDED;
  463. }
  464. done:
  465. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  466. smartlist_free(version_sl);
  467. return ret;
  468. }
  469. /** Return the combined status of the current version, given that we know of
  470. * one set of networkstatuses that give us status <b>a</b>, and another that
  471. * gives us status <b>b</b>.
  472. *
  473. * For example, if one authority thinks that we're NEW, and another thinks
  474. * we're OLD, we're simply UNRECOMMENDED.
  475. *
  476. * This function does not handle calculating whether we're RECOMMENDED; that
  477. * follows a simple majority rule. This function simply calculates *why*
  478. * we're not recommended (if we're not).
  479. */
  480. version_status_t
  481. version_status_join(version_status_t a, version_status_t b)
  482. {
  483. if (a == b)
  484. return a;
  485. else if (a == VS_UNRECOMMENDED || b == VS_UNRECOMMENDED)
  486. return VS_UNRECOMMENDED;
  487. else if (a == VS_RECOMMENDED)
  488. return b;
  489. else if (b == VS_RECOMMENDED)
  490. return a;
  491. /* Okay. Neither is 'recommended' or 'unrecommended', and they differ. */
  492. else if (a == VS_OLD || b == VS_OLD)
  493. return VS_UNRECOMMENDED;
  494. /* One is VS_NEW, the other is VS_NEW_IN_SERIES */
  495. else
  496. return VS_NEW_IN_SERIES;
  497. }
  498. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  499. * Otherwise, return -1. If we're a directory cache, cache it.
  500. */
  501. int
  502. router_parse_directory(const char *str)
  503. {
  504. directory_token_t *tok;
  505. char digest[DIGEST_LEN];
  506. time_t published_on;
  507. int r;
  508. const char *end, *cp;
  509. smartlist_t *tokens = NULL;
  510. crypto_pk_env_t *declared_key = NULL;
  511. /* XXXX This could be simplified a lot, but it will all go away
  512. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  513. * touch it. */
  514. if (router_get_dir_hash(str, digest)) {
  515. log_warn(LD_DIR, "Unable to compute digest of directory");
  516. goto err;
  517. }
  518. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  519. /* Check signature first, before we try to tokenize. */
  520. cp = str;
  521. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  522. cp = end;
  523. if (cp == str || !cp) {
  524. log_warn(LD_DIR, "No signature found on directory."); goto err;
  525. }
  526. ++cp;
  527. tokens = smartlist_create();
  528. if (tokenize_string(cp,strchr(cp,'\0'),tokens,dir_token_table)) {
  529. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  530. }
  531. if (smartlist_len(tokens) != 1) {
  532. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  533. }
  534. tok=smartlist_get(tokens,0);
  535. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  536. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  537. }
  538. declared_key = find_dir_signing_key(str);
  539. note_crypto_pk_op(VERIFY_DIR);
  540. if (check_signature_token(digest, tok, declared_key, 1, "directory")<0)
  541. goto err;
  542. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  543. smartlist_free(tokens);
  544. tokens = NULL;
  545. /* Now try to parse the first part of the directory. */
  546. if ((end = strstr(str,"\nrouter "))) {
  547. ++end;
  548. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  549. ++end;
  550. } else {
  551. end = str + strlen(str);
  552. }
  553. tokens = smartlist_create();
  554. if (tokenize_string(str,end,tokens,dir_token_table)) {
  555. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  556. }
  557. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  558. tor_assert(tok);
  559. tor_assert(tok->n_args == 1);
  560. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  561. goto err;
  562. }
  563. /* Now that we know the signature is okay, and we have a
  564. * publication time, cache the directory. */
  565. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  566. dirserv_set_cached_directory(str, published_on, 0);
  567. r = 0;
  568. goto done;
  569. err:
  570. r = -1;
  571. done:
  572. if (declared_key) crypto_free_pk_env(declared_key);
  573. if (tokens) {
  574. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  575. smartlist_free(tokens);
  576. }
  577. return r;
  578. }
  579. /** Read a signed router status statement from <b>str</b>. If it's
  580. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  581. * cache it.*/
  582. int
  583. router_parse_runningrouters(const char *str)
  584. {
  585. char digest[DIGEST_LEN];
  586. directory_token_t *tok;
  587. time_t published_on;
  588. int r = -1;
  589. crypto_pk_env_t *declared_key = NULL;
  590. smartlist_t *tokens = NULL;
  591. if (router_get_runningrouters_hash(str, digest)) {
  592. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  593. goto err;
  594. }
  595. tokens = smartlist_create();
  596. if (tokenize_string(str,str+strlen(str),tokens,dir_token_table)) {
  597. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  598. }
  599. tok = smartlist_get(tokens,0);
  600. if (tok->tp != K_NETWORK_STATUS) {
  601. log_warn(LD_DIR, "Network-status starts with wrong token");
  602. goto err;
  603. }
  604. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  605. tor_assert(tok);
  606. tor_assert(tok->n_args == 1);
  607. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  608. goto err;
  609. }
  610. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  611. log_warn(LD_DIR, "Missing signature on running-routers");
  612. goto err;
  613. }
  614. declared_key = find_dir_signing_key(str);
  615. note_crypto_pk_op(VERIFY_DIR);
  616. if (check_signature_token(digest, tok, declared_key, 1, "running-routers")
  617. < 0)
  618. goto err;
  619. /* Now that we know the signature is okay, and we have a
  620. * publication time, cache the list. */
  621. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  622. dirserv_set_cached_directory(str, published_on, 1);
  623. r = 0;
  624. err:
  625. if (declared_key) crypto_free_pk_env(declared_key);
  626. if (tokens) {
  627. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  628. smartlist_free(tokens);
  629. }
  630. return r;
  631. }
  632. /** Given a directory or running-routers string in <b>str</b>, try to
  633. * find the its dir-signing-key token (if any). If this token is
  634. * present, extract and return the key. Return NULL on failure. */
  635. static crypto_pk_env_t *
  636. find_dir_signing_key(const char *str)
  637. {
  638. const char *cp;
  639. directory_token_t *tok;
  640. crypto_pk_env_t *key = NULL;
  641. /* Is there a dir-signing-key in the directory? */
  642. cp = strstr(str, "\nopt dir-signing-key");
  643. if (!cp)
  644. cp = strstr(str, "\ndir-signing-key");
  645. if (!cp)
  646. return NULL;
  647. ++cp; /* Now cp points to the start of the token. */
  648. tok = get_next_token(&cp, dir_token_table);
  649. if (!tok) {
  650. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  651. return NULL;
  652. }
  653. if (tok->tp != K_DIR_SIGNING_KEY) {
  654. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  655. return NULL;
  656. }
  657. if (tok->key) {
  658. key = tok->key;
  659. tok->key = NULL; /* steal reference. */
  660. } else {
  661. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  662. return NULL;
  663. }
  664. token_free(tok);
  665. return key;
  666. }
  667. /** Return true iff <b>key</b> is allowed to sign directories.
  668. */
  669. static int
  670. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  671. {
  672. char digest[DIGEST_LEN];
  673. if (!key) return 0;
  674. if (crypto_pk_get_digest(key, digest) < 0) {
  675. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  676. return 0;
  677. }
  678. if (!router_digest_is_trusted_dir(digest)) {
  679. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  680. return 0;
  681. }
  682. return 1;
  683. }
  684. /** Check whether the object body of the token in <b>tok</b> has a good
  685. * signature for <b>digest</b> using key <b>pkey</b>. If
  686. * <b>check_authority</b> is set, make sure that <b>pkey</b> is the key of a
  687. * directory authority. Use <b>doctype</b> as the type of the document when
  688. * generating log messages. Return 0 on success, negative on failure.
  689. */
  690. static int
  691. check_signature_token(const char *digest,
  692. directory_token_t *tok,
  693. crypto_pk_env_t *pkey,
  694. int check_authority,
  695. const char *doctype)
  696. {
  697. char *signed_digest;
  698. tor_assert(pkey);
  699. tor_assert(tok);
  700. tor_assert(digest);
  701. tor_assert(doctype);
  702. if (check_authority && !dir_signing_key_is_trusted(pkey)) {
  703. log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
  704. doctype);
  705. return -1;
  706. }
  707. if (strcmp(tok->object_type, "SIGNATURE")) {
  708. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  709. return -1;
  710. }
  711. signed_digest = tor_malloc(tok->object_size);
  712. if (crypto_pk_public_checksig(pkey, signed_digest, tok->object_body,
  713. tok->object_size)
  714. != DIGEST_LEN) {
  715. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  716. return -1;
  717. }
  718. log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  719. hex_str(signed_digest,4));
  720. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  721. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  722. return -1;
  723. }
  724. return 0;
  725. }
  726. /** Given a string *<b>s</b> containing a concatenated sequence of router
  727. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  728. * them and stores the result in <b>dest</b>. All routers are marked running
  729. * and valid. Advances *s to a point immediately following the last router
  730. * entry. Ignore any trailing router entries that are not complete.
  731. *
  732. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  733. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  734. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  735. *
  736. * Returns 0 on success and -1 on failure.
  737. */
  738. int
  739. router_parse_list_from_string(const char **s, smartlist_t *dest,
  740. saved_location_t saved_location,
  741. int want_extrainfo)
  742. {
  743. routerinfo_t *router;
  744. extrainfo_t *extrainfo;
  745. signed_descriptor_t *signed_desc;
  746. void *elt;
  747. const char *end, *start;
  748. int have_extrainfo;
  749. tor_assert(s);
  750. tor_assert(*s);
  751. tor_assert(dest);
  752. start = *s;
  753. while (1) {
  754. *s = eat_whitespace(*s);
  755. /* Don't start parsing the rest of *s unless it contains a router. */
  756. if (strcmpstart(*s, "extra-info ")==0) {
  757. have_extrainfo = 1;
  758. } else if (strcmpstart(*s, "router ")==0) {
  759. have_extrainfo = 0;
  760. } else {
  761. /* skip junk. */
  762. const char *ei = strstr(*s, "\nextra-info ");
  763. const char *ri = strstr(*s, "\nrouter ");
  764. if (ri && (!ei || ri < ei)) {
  765. have_extrainfo = 0;
  766. *s = ri + 1;
  767. } else if (ei) {
  768. have_extrainfo = 1;
  769. *s = ei + 1;
  770. } else {
  771. break;
  772. }
  773. }
  774. end = strstr(*s, "\nrouter-signature");
  775. if (end)
  776. end = strstr(end, "\n-----END SIGNATURE-----\n");
  777. if (end)
  778. end += strlen("\n-----END SIGNATURE-----\n");
  779. if (!end)
  780. break;
  781. if (have_extrainfo && want_extrainfo) {
  782. routerlist_t *rl = router_get_routerlist();
  783. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  784. saved_location != SAVED_IN_CACHE,
  785. rl->identity_map);
  786. signed_desc = &extrainfo->cache_info;
  787. elt = extrainfo;
  788. } else if (!have_extrainfo && !want_extrainfo) {
  789. router = router_parse_entry_from_string(*s, end,
  790. saved_location != SAVED_IN_CACHE);
  791. signed_desc = &router->cache_info;
  792. elt = router;
  793. } else {
  794. *s = end;
  795. continue;
  796. }
  797. if (saved_location != SAVED_NOWHERE) {
  798. signed_desc->saved_location = saved_location;
  799. signed_desc->saved_offset = *s - start;
  800. }
  801. *s = end;
  802. smartlist_add(dest, elt);
  803. }
  804. return 0;
  805. }
  806. /* For debugging: define to count every descriptor digest we've seen so we
  807. * know if we need to try harder to avoid duplicate verifies. */
  808. #undef COUNT_DISTINCT_DIGESTS
  809. #ifdef COUNT_DISTINCT_DIGESTS
  810. static digestmap_t *verified_digests = NULL;
  811. #endif
  812. /** Log the total count of the number of distinct router digests we've ever
  813. * verified. When compared to the number of times we've verified routerdesc
  814. * signatures <i>in toto</i>, this will tell us if we're doing too much
  815. * multiple-verification. */
  816. void
  817. dump_distinct_digest_count(int severity)
  818. {
  819. #ifdef COUNT_DISTINCT_DIGESTS
  820. if (!verified_digests)
  821. verified_digests = digestmap_new();
  822. log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  823. digestmap_size(verified_digests));
  824. #else
  825. (void)severity; /* suppress "unused parameter" warning */
  826. #endif
  827. }
  828. /** Helper function: reads a single router entry from *<b>s</b> ...
  829. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  830. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  831. * s through end into the signed_descriptor_body of the resulting
  832. * routerinfo_t.
  833. */
  834. routerinfo_t *
  835. router_parse_entry_from_string(const char *s, const char *end,
  836. int cache_copy)
  837. {
  838. routerinfo_t *router = NULL;
  839. char digest[128];
  840. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  841. directory_token_t *tok;
  842. struct in_addr in;
  843. if (!end) {
  844. end = s + strlen(s);
  845. }
  846. /* point 'end' to a point immediately after the final newline. */
  847. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  848. --end;
  849. if (router_get_router_hash(s, digest) < 0) {
  850. log_warn(LD_DIR, "Couldn't compute router hash.");
  851. return NULL;
  852. }
  853. tokens = smartlist_create();
  854. if (tokenize_string(s,end,tokens,routerdesc_token_table)) {
  855. log_warn(LD_DIR, "Error tokeninzing router descriptor.");
  856. goto err;
  857. }
  858. if (smartlist_len(tokens) < 2) {
  859. log_warn(LD_DIR, "Impossibly short router descriptor.");
  860. goto err;
  861. }
  862. tok = smartlist_get(tokens,0);
  863. if (tok->tp != K_ROUTER) {
  864. log_warn(LD_DIR,"Entry does not start with \"router\"");
  865. goto err;
  866. }
  867. tor_assert(tok->n_args >= 5);
  868. router = tor_malloc_zero(sizeof(routerinfo_t));
  869. router->routerlist_index = -1;
  870. if (cache_copy)
  871. router->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  872. router->cache_info.signed_descriptor_len = end-s;
  873. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  874. router->nickname = tor_strdup(tok->args[0]);
  875. if (!is_legal_nickname(router->nickname)) {
  876. log_warn(LD_DIR,"Router nickname is invalid");
  877. goto err;
  878. }
  879. router->address = tor_strdup(tok->args[1]);
  880. if (!tor_inet_aton(router->address, &in)) {
  881. log_warn(LD_DIR,"Router address is not an IP.");
  882. goto err;
  883. }
  884. router->addr = ntohl(in.s_addr);
  885. router->or_port =
  886. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  887. router->dir_port =
  888. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  889. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  890. tor_assert(tok && tok->n_args >= 3);
  891. router->bandwidthrate =
  892. tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  893. if (!router->bandwidthrate) {
  894. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  895. escaped(tok->args[0]));
  896. goto err;
  897. }
  898. router->bandwidthburst =
  899. tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  900. router->bandwidthcapacity =
  901. tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  902. /* XXX we don't error-check these values? -RD */
  903. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  904. tor_assert(tok->n_args >= 1);
  905. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  906. }
  907. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  908. tor_assert(tok->n_args >= 1);
  909. router->is_hibernating
  910. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  911. }
  912. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  913. tor_assert(tok);
  914. tor_assert(tok->n_args == 1);
  915. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  916. goto err;
  917. tok = find_first_by_keyword(tokens, K_ONION_KEY);
  918. tor_assert(tok);
  919. router->onion_pkey = tok->key;
  920. tok->key = NULL; /* Prevent free */
  921. tok = find_first_by_keyword(tokens, K_SIGNING_KEY);
  922. tor_assert(tok);
  923. router->identity_pkey = tok->key;
  924. tok->key = NULL; /* Prevent free */
  925. if (crypto_pk_get_digest(router->identity_pkey,
  926. router->cache_info.identity_digest)) {
  927. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  928. }
  929. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  930. /* If there's a fingerprint line, it must match the identity digest. */
  931. char d[DIGEST_LEN];
  932. tor_assert(tok->n_args == 1);
  933. tor_strstrip(tok->args[0], " ");
  934. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  935. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  936. escaped(tok->args[0]));
  937. goto err;
  938. }
  939. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  940. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  941. tok->args[0]);
  942. goto err;
  943. }
  944. }
  945. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  946. router->platform = tor_strdup(tok->args[0]);
  947. }
  948. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  949. router->contact_info = tor_strdup(tok->args[0]);
  950. }
  951. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  952. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  953. } else if (router->platform) {
  954. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  955. router->has_old_dnsworkers = 1;
  956. }
  957. exit_policy_tokens = find_all_exitpolicy(tokens);
  958. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  959. if (router_add_exit_policy(router,t)<0) {
  960. log_warn(LD_DIR,"Error in exit policy");
  961. goto err;
  962. });
  963. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  964. int i;
  965. router->declared_family = smartlist_create();
  966. for (i=0;i<tok->n_args;++i) {
  967. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  968. log_warn(LD_DIR, "Illegal nickname %s in family line",
  969. escaped(tok->args[i]));
  970. goto err;
  971. }
  972. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  973. }
  974. }
  975. if ((tok = find_first_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  976. router->caches_extra_info = 1;
  977. if ((tok = find_first_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  978. tor_assert(tok->n_args >= 1);
  979. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  980. base16_decode(router->cache_info.extra_info_digest,
  981. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  982. } else {
  983. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  984. }
  985. }
  986. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  987. tor_assert(tok);
  988. note_crypto_pk_op(VERIFY_RTR);
  989. #ifdef COUNT_DISTINCT_DIGESTS
  990. if (!verified_digests)
  991. verified_digests = digestmap_new();
  992. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  993. #endif
  994. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  995. "router descriptor") < 0)
  996. goto err;
  997. if (!router->or_port) {
  998. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  999. goto err;
  1000. }
  1001. if (!router->platform) {
  1002. router->platform = tor_strdup("<unknown>");
  1003. }
  1004. goto done;
  1005. err:
  1006. routerinfo_free(router);
  1007. router = NULL;
  1008. done:
  1009. if (tokens) {
  1010. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1011. smartlist_free(tokens);
  1012. }
  1013. if (exit_policy_tokens) {
  1014. smartlist_free(exit_policy_tokens);
  1015. }
  1016. return router;
  1017. }
  1018. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1019. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1020. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1021. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1022. * as a map from router identity to routerinfo_t when looking up signing keys.
  1023. */
  1024. extrainfo_t *
  1025. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1026. int cache_copy, digestmap_t *routermap)
  1027. {
  1028. extrainfo_t *extrainfo = NULL;
  1029. char digest[128];
  1030. smartlist_t *tokens = NULL;
  1031. directory_token_t *tok;
  1032. crypto_pk_env_t *key = NULL;
  1033. routerinfo_t *router;
  1034. if (!end) {
  1035. end = s + strlen(s);
  1036. }
  1037. /* point 'end' to a point immediately after the final newline. */
  1038. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1039. --end;
  1040. if (router_get_extrainfo_hash(s, digest) < 0) {
  1041. log_warn(LD_DIR, "Couldn't compute router hash.");
  1042. return NULL;
  1043. }
  1044. tokens = smartlist_create();
  1045. if (tokenize_string(s,end,tokens,extrainfo_token_table)) {
  1046. log_warn(LD_DIR, "Error tokeninzing router descriptor.");
  1047. goto err;
  1048. }
  1049. if (smartlist_len(tokens) < 2) {
  1050. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1051. goto err;
  1052. }
  1053. tok = smartlist_get(tokens,0);
  1054. if (tok->tp != K_EXTRA_INFO) {
  1055. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1056. goto err;
  1057. }
  1058. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1059. extrainfo->cache_info.is_extrainfo = 1;
  1060. if (cache_copy)
  1061. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1062. extrainfo->cache_info.signed_descriptor_len = end-s;
  1063. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1064. tor_assert(tok->n_args >= 2);
  1065. if (!is_legal_nickname(tok->args[0])) {
  1066. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1067. goto err;
  1068. }
  1069. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1070. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1071. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1072. tok->args[1], HEX_DIGEST_LEN)) {
  1073. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1074. escaped(tok->args[1]));
  1075. goto err;
  1076. }
  1077. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1078. tor_assert(tok);
  1079. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1080. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1081. escaped(tok->args[0]));
  1082. goto err;
  1083. }
  1084. if (routermap &&
  1085. (router = digestmap_get(routermap,
  1086. extrainfo->cache_info.identity_digest))) {
  1087. key = router->identity_pkey;
  1088. }
  1089. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1090. tor_assert(tok);
  1091. if (strcmp(tok->object_type, "SIGNATURE") ||
  1092. tok->object_size < 128 || tok->object_size > 512) {
  1093. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1094. goto err;
  1095. }
  1096. if (key) {
  1097. note_crypto_pk_op(VERIFY_RTR);
  1098. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1099. goto err;
  1100. } else {
  1101. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1102. tok->object_size);
  1103. extrainfo->pending_sig_len = tok->object_size;
  1104. }
  1105. goto done;
  1106. err:
  1107. if (extrainfo)
  1108. extrainfo_free(extrainfo);
  1109. extrainfo = NULL;
  1110. done:
  1111. if (tokens) {
  1112. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1113. smartlist_free(tokens);
  1114. }
  1115. return extrainfo;
  1116. }
  1117. /** Free storage held in <b>cert</b>. */
  1118. void
  1119. authority_cert_free(authority_cert_t *cert)
  1120. {
  1121. if (!cert)
  1122. return;
  1123. tor_free(cert->cache_info.signed_descriptor_body);
  1124. if (cert->signing_key)
  1125. crypto_free_pk_env(cert->signing_key);
  1126. if (cert->identity_key)
  1127. crypto_free_pk_env(cert->identity_key);
  1128. tor_free(cert);
  1129. }
  1130. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1131. * the first character after the certificate. */
  1132. authority_cert_t *
  1133. authority_cert_parse_from_string(const char *s, char **end_of_string)
  1134. {
  1135. authority_cert_t *cert = NULL;
  1136. smartlist_t *tokens = NULL;
  1137. char digest[DIGEST_LEN];
  1138. directory_token_t *tok;
  1139. char fp_declared[DIGEST_LEN];
  1140. char *eos = strstr(s, "\n-----END SIGNATURE-----\n");
  1141. size_t len;
  1142. if (! eos) {
  1143. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1144. return NULL;
  1145. }
  1146. eos = strchr(eos+2, '\n');
  1147. tor_assert(eos);
  1148. ++eos;
  1149. len = eos - s;
  1150. tokens = smartlist_create();
  1151. if (tokenize_string(s, eos, tokens, dir_key_certificate_table) < 0) {
  1152. log_warn(LD_DIR, "Error tokenizing key certificate");
  1153. goto err;
  1154. }
  1155. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1156. "\ndir-key-certification") < 0)
  1157. goto err;
  1158. tok = smartlist_get(tokens, 0);
  1159. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1160. log_warn(LD_DIR,
  1161. "Key certificate does not begin with a recognized version (3).");
  1162. goto err;
  1163. }
  1164. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1165. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1166. tor_assert(tok && tok->key);
  1167. cert->signing_key = tok->key;
  1168. tok->key = NULL;
  1169. tok = find_first_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1170. tor_assert(tok && tok->key);
  1171. cert->identity_key = tok->key;
  1172. tok->key = NULL;
  1173. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1174. tor_assert(tok && tok->n_args);
  1175. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1176. strlen(tok->args[0]))) {
  1177. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1178. escaped(tok->args[0]));
  1179. goto err;
  1180. }
  1181. if (crypto_pk_get_digest(cert->identity_key,
  1182. cert->cache_info.identity_digest))
  1183. goto err;
  1184. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1185. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1186. "fingerprint");
  1187. goto err;
  1188. }
  1189. tok = find_first_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1190. tor_assert(tok);
  1191. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1192. goto err;
  1193. }
  1194. tok = find_first_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1195. tor_assert(tok);
  1196. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1197. goto err;
  1198. }
  1199. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1200. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1201. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1202. goto err;
  1203. }
  1204. /* XXXXX This doesn't check whether the key is an authority. IS that what we
  1205. * want? */
  1206. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1207. "key certificate")) {
  1208. goto err;
  1209. }
  1210. cert->cache_info.signed_descriptor_len = len;
  1211. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1212. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1213. cert->cache_info.signed_descriptor_body[len] = 0;
  1214. cert->cache_info.saved_location = SAVED_NOWHERE;
  1215. *end_of_string = eos;
  1216. return cert;
  1217. err:
  1218. authority_cert_free(cert);
  1219. return NULL;
  1220. }
  1221. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1222. * object (starting with "r " at the start of a line). If none is found,
  1223. * return the start of the next directory signature. If none is found, return
  1224. * the end of the string. */
  1225. static INLINE const char *
  1226. find_start_of_next_routerstatus(const char *s)
  1227. {
  1228. const char *eos = strstr(s, "\nr ");
  1229. if (!eos)
  1230. eos = strstr(s, "\ndirectory-signature");
  1231. if (eos)
  1232. return eos+1;
  1233. else
  1234. return s + strlen(s);
  1235. }
  1236. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1237. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1238. * object in the string, and advance *<b>s</b> to just after the end of the
  1239. * router status. Return NULL and advance *<b>s</b> on error. */
  1240. static routerstatus_t *
  1241. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens)
  1242. {
  1243. const char *eos;
  1244. routerstatus_t *rs = NULL;
  1245. directory_token_t *tok;
  1246. char timebuf[ISO_TIME_LEN+1];
  1247. struct in_addr in;
  1248. tor_assert(tokens);
  1249. eos = find_start_of_next_routerstatus(*s);
  1250. if (tokenize_string(*s, eos, tokens, rtrstatus_token_table)) {
  1251. log_warn(LD_DIR, "Error tokenizing router status");
  1252. goto err;
  1253. }
  1254. if (smartlist_len(tokens) < 1) {
  1255. log_warn(LD_DIR, "Impossibly short router status");
  1256. goto err;
  1257. }
  1258. tok = find_first_by_keyword(tokens, K_R);
  1259. tor_assert(tok);
  1260. tor_assert(tok->n_args >= 8);
  1261. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1262. if (!is_legal_nickname(tok->args[0])) {
  1263. log_warn(LD_DIR,
  1264. "Invalid nickname %s in router status; skipping.",
  1265. escaped(tok->args[0]));
  1266. goto err;
  1267. }
  1268. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1269. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1270. log_warn(LD_DIR, "Error decoding identity digest %s",
  1271. escaped(tok->args[1]));
  1272. goto err;
  1273. }
  1274. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1275. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1276. escaped(tok->args[2]));
  1277. goto err;
  1278. }
  1279. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1280. tok->args[3], tok->args[4]) < 0 ||
  1281. parse_iso_time(timebuf, &rs->published_on)<0) {
  1282. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1283. tok->args[3], tok->args[4]);
  1284. goto err;
  1285. }
  1286. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1287. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1288. escaped(tok->args[5]));
  1289. goto err;
  1290. }
  1291. rs->addr = ntohl(in.s_addr);
  1292. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1293. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1294. if ((tok = find_first_by_keyword(tokens, K_S))) {
  1295. int i;
  1296. for (i=0; i < tok->n_args; ++i) {
  1297. if (!strcmp(tok->args[i], "Exit"))
  1298. rs->is_exit = 1;
  1299. else if (!strcmp(tok->args[i], "Stable"))
  1300. rs->is_stable = 1;
  1301. else if (!strcmp(tok->args[i], "Fast"))
  1302. rs->is_fast = 1;
  1303. else if (!strcmp(tok->args[i], "Running"))
  1304. rs->is_running = 1;
  1305. else if (!strcmp(tok->args[i], "Named"))
  1306. rs->is_named = 1;
  1307. else if (!strcmp(tok->args[i], "Valid"))
  1308. rs->is_valid = 1;
  1309. else if (!strcmp(tok->args[i], "V2Dir"))
  1310. rs->is_v2_dir = 1;
  1311. else if (!strcmp(tok->args[i], "Guard"))
  1312. rs->is_possible_guard = 1;
  1313. else if (!strcmp(tok->args[i], "BadExit"))
  1314. rs->is_bad_exit = 1;
  1315. else if (!strcmp(tok->args[i], "BadDirectory"))
  1316. rs->is_bad_directory = 1;
  1317. }
  1318. }
  1319. if ((tok = find_first_by_keyword(tokens, K_V))) {
  1320. tor_assert(tok->n_args == 1);
  1321. rs->version_known = 1;
  1322. if (strcmpstart(tok->args[0], "Tor ")) {
  1323. rs->version_supports_begindir = 1;
  1324. rs->version_supports_extrainfo_upload = 1;
  1325. } else {
  1326. rs->version_supports_begindir =
  1327. tor_version_as_new_as(tok->args[0], "0.1.2.2-alpha");
  1328. rs->version_supports_begindir =
  1329. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1330. }
  1331. }
  1332. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1333. rs->is_named = 0;
  1334. goto done;
  1335. err:
  1336. if (rs)
  1337. routerstatus_free(rs);
  1338. rs = NULL;
  1339. done:
  1340. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1341. smartlist_clear(tokens);
  1342. *s = eos;
  1343. return rs;
  1344. }
  1345. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1346. static int
  1347. _compare_routerstatus_entries(const void **_a, const void **_b)
  1348. {
  1349. const routerstatus_t *a = *_a, *b = *_b;
  1350. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1351. }
  1352. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1353. static void
  1354. _free_duplicate_routerstatus_entry(void *e)
  1355. {
  1356. log_warn(LD_DIR,
  1357. "Network-status has two entries for the same router. "
  1358. "Dropping one.");
  1359. routerstatus_free(e);
  1360. }
  1361. /** Given a versioned (v2 or later) network-status object in <b>s</b>, try to
  1362. * parse it and return the result. Return NULL on failure. Check the
  1363. * signature of the network status, but do not (yet) check the signing key for
  1364. * authority.
  1365. */
  1366. networkstatus_t *
  1367. networkstatus_parse_from_string(const char *s)
  1368. {
  1369. const char *eos;
  1370. smartlist_t *tokens = smartlist_create();
  1371. smartlist_t *footer_tokens = smartlist_create();
  1372. networkstatus_t *ns = NULL;
  1373. char ns_digest[DIGEST_LEN];
  1374. char tmp_digest[DIGEST_LEN];
  1375. struct in_addr in;
  1376. directory_token_t *tok;
  1377. int i;
  1378. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1379. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1380. goto err;
  1381. }
  1382. eos = find_start_of_next_routerstatus(s);
  1383. if (tokenize_string(s, eos, tokens, netstatus_token_table)) {
  1384. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1385. goto err;
  1386. }
  1387. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1388. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1389. tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1390. tor_assert(tok);
  1391. tok = find_first_by_keyword(tokens, K_DIR_SOURCE);
  1392. tor_assert(tok);
  1393. tor_assert(tok->n_args >= 3);
  1394. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1395. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1396. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1397. escaped(tok->args[1]));
  1398. goto err;
  1399. }
  1400. ns->source_addr = ntohl(in.s_addr);
  1401. ns->source_dirport =
  1402. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1403. if (ns->source_dirport == 0) {
  1404. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1405. goto err;
  1406. }
  1407. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1408. tor_assert(tok);
  1409. tor_assert(tok->n_args);
  1410. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1411. strlen(tok->args[0]))) {
  1412. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1413. escaped(tok->args[0]));
  1414. goto err;
  1415. }
  1416. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1417. tor_assert(tok->n_args);
  1418. ns->contact = tok->args[0];
  1419. tok->args[0] = NULL;
  1420. }
  1421. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1422. tor_assert(tok && tok->key);
  1423. ns->signing_key = tok->key;
  1424. tok->key = NULL;
  1425. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1426. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1427. goto err;
  1428. }
  1429. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1430. log_warn(LD_DIR,
  1431. "network-status fingerprint did not match dir-signing-key");
  1432. goto err;
  1433. }
  1434. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1435. for (i=0; i < tok->n_args; ++i) {
  1436. if (!strcmp(tok->args[i], "Names"))
  1437. ns->binds_names = 1;
  1438. if (!strcmp(tok->args[i], "Versions"))
  1439. ns->recommends_versions = 1;
  1440. if (!strcmp(tok->args[i], "BadExits"))
  1441. ns->lists_bad_exits = 1;
  1442. if (!strcmp(tok->args[i], "BadDirectories"))
  1443. ns->lists_bad_directories = 1;
  1444. }
  1445. }
  1446. if (ns->recommends_versions) {
  1447. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1448. log_warn(LD_DIR, "Missing client-versions");
  1449. }
  1450. ns->client_versions = tok->args[0];
  1451. tok->args[0] = NULL;
  1452. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1453. tok->n_args<1) {
  1454. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1455. goto err;
  1456. }
  1457. ns->server_versions = tok->args[0];
  1458. tok->args[0] = NULL;
  1459. }
  1460. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1461. tor_assert(tok);
  1462. tor_assert(tok->n_args == 1);
  1463. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1464. goto err;
  1465. }
  1466. ns->entries = smartlist_create();
  1467. s = eos;
  1468. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1469. smartlist_clear(tokens);
  1470. while (!strcmpstart(s, "r ")) {
  1471. routerstatus_t *rs;
  1472. if ((rs = routerstatus_parse_entry_from_string(&s, tokens)))
  1473. smartlist_add(ns->entries, rs);
  1474. }
  1475. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1476. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1477. _free_duplicate_routerstatus_entry);
  1478. if (tokenize_string(s, NULL, footer_tokens, dir_footer_token_table)) {
  1479. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1480. goto err;
  1481. }
  1482. if (smartlist_len(footer_tokens) < 1) {
  1483. log_warn(LD_DIR, "Too few items in network-status footer.");
  1484. goto err;
  1485. }
  1486. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1487. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1488. log_warn(LD_DIR,
  1489. "Expected network-status footer to end with a signature.");
  1490. goto err;
  1491. }
  1492. note_crypto_pk_op(VERIFY_DIR);
  1493. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1494. "network-status") < 0)
  1495. goto err;
  1496. goto done;
  1497. err:
  1498. if (ns)
  1499. networkstatus_free(ns);
  1500. ns = NULL;
  1501. done:
  1502. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1503. smartlist_free(tokens);
  1504. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1505. smartlist_free(footer_tokens);
  1506. return ns;
  1507. }
  1508. /** Parse the addr policy in the string <b>s</b> and return it. If
  1509. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1510. * ADDR_POLICY_REJECT) for items that specify no action.
  1511. */
  1512. addr_policy_t *
  1513. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1514. {
  1515. directory_token_t *tok = NULL;
  1516. const char *cp;
  1517. char *tmp;
  1518. addr_policy_t *r;
  1519. size_t len, idx;
  1520. /* *s might not end with \n, so we need to extend it with one. */
  1521. len = strlen(s);
  1522. cp = tmp = tor_malloc(len+2);
  1523. for (idx = 0; idx < len; ++idx) {
  1524. tmp[idx] = TOR_TOLOWER(s[idx]);
  1525. }
  1526. tmp[len]='\n';
  1527. tmp[len+1]='\0';
  1528. while (TOR_ISSPACE(*cp))
  1529. ++cp;
  1530. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1531. char *new_str = tor_malloc(len+10);
  1532. tor_snprintf(new_str, len+10, "%s %s\n",
  1533. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1534. tor_free(tmp);
  1535. cp = tmp = new_str;
  1536. }
  1537. tok = get_next_token(&cp, routerdesc_token_table);
  1538. if (tok->tp == _ERR) {
  1539. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1540. goto err;
  1541. }
  1542. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1543. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1544. goto err;
  1545. }
  1546. /* Now that we've gotten an addr policy, add it to the router. */
  1547. r = router_parse_addr_policy(tok);
  1548. goto done;
  1549. err:
  1550. r = NULL;
  1551. done:
  1552. tor_free(tmp);
  1553. token_free(tok);
  1554. return r;
  1555. }
  1556. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1557. * <b>router</b>. Return 0 on success, -1 on failure. */
  1558. static int
  1559. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1560. {
  1561. addr_policy_t *newe, **tmpe;
  1562. newe = router_parse_addr_policy(tok);
  1563. if (!newe)
  1564. return -1;
  1565. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1566. ;
  1567. *tmpe = newe;
  1568. return 0;
  1569. }
  1570. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1571. * a new exit_policy_t corresponding to the token. */
  1572. static addr_policy_t *
  1573. router_parse_addr_policy(directory_token_t *tok)
  1574. {
  1575. addr_policy_t *newe;
  1576. char *arg;
  1577. char buf[POLICY_BUF_LEN];
  1578. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1579. if (tok->n_args != 1)
  1580. return NULL;
  1581. arg = tok->args[0];
  1582. if (!strcmpstart(arg,"private"))
  1583. return router_parse_addr_policy_private(tok);
  1584. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1585. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1586. : ADDR_POLICY_ACCEPT;
  1587. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1588. &newe->prt_min, &newe->prt_max))
  1589. goto policy_read_failed;
  1590. if (policy_write_item(buf, sizeof(buf), newe) < 0)
  1591. goto policy_read_failed;
  1592. newe->string = tor_strdup(buf);
  1593. return newe;
  1594. policy_read_failed:
  1595. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1596. tor_free(newe);
  1597. return NULL;
  1598. }
  1599. /** Parse an exit policy line of the format "accept/reject private:...".
  1600. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1601. * router descriptors until earlier versions are obsolete.
  1602. */
  1603. static addr_policy_t *
  1604. router_parse_addr_policy_private(directory_token_t *tok)
  1605. {
  1606. static const char *private_nets[] = {
  1607. "0.0.0.0/8", "169.254.0.0/16",
  1608. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1609. char *arg;
  1610. addr_policy_t *result, **nextp;
  1611. int net;
  1612. uint16_t port_min, port_max;
  1613. arg = tok->args[0];
  1614. if (strcmpstart(arg, "private"))
  1615. return NULL;
  1616. arg += strlen("private");
  1617. arg = (char*) eat_whitespace(arg);
  1618. if (!arg || *arg != ':')
  1619. return NULL;
  1620. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1621. return NULL;
  1622. nextp = &result;
  1623. for (net = 0; private_nets[net]; ++net) {
  1624. size_t len;
  1625. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1626. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1627. : ADDR_POLICY_ACCEPT;
  1628. len = strlen(arg)+strlen(private_nets[net])+16;
  1629. (*nextp)->string = tor_malloc(len+1);
  1630. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1631. tok->tp == K_REJECT ? "reject" : "accept",
  1632. private_nets[net], arg);
  1633. if (parse_addr_and_port_range((*nextp)->string + 7,
  1634. &(*nextp)->addr, &(*nextp)->msk,
  1635. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1636. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1637. return NULL;
  1638. }
  1639. nextp = &(*nextp)->next;
  1640. }
  1641. return result;
  1642. }
  1643. /** Log and exit if <b>t</b> is malformed */
  1644. void
  1645. assert_addr_policy_ok(addr_policy_t *t)
  1646. {
  1647. addr_policy_t *t2;
  1648. while (t) {
  1649. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1650. t->policy_type == ADDR_POLICY_ACCEPT);
  1651. tor_assert(t->prt_min <= t->prt_max);
  1652. t2 = router_parse_addr_policy_from_string(t->string, -1);
  1653. tor_assert(t2);
  1654. tor_assert(t2->policy_type == t->policy_type);
  1655. tor_assert(t2->addr == t->addr);
  1656. tor_assert(t2->msk == t->msk);
  1657. tor_assert(t2->prt_min == t->prt_min);
  1658. tor_assert(t2->prt_max == t->prt_max);
  1659. tor_assert(!strcmp(t2->string, t->string));
  1660. tor_assert(t2->next == NULL);
  1661. addr_policy_free(t2);
  1662. t = t->next;
  1663. }
  1664. }
  1665. /*
  1666. * Low-level tokenizer for router descriptors and directories.
  1667. */
  1668. /** Free all resources allocated for <b>tok</b> */
  1669. static void
  1670. token_free(directory_token_t *tok)
  1671. {
  1672. int i;
  1673. tor_assert(tok);
  1674. if (tok->args) {
  1675. for (i = 0; i < tok->n_args; ++i) {
  1676. tor_free(tok->args[i]);
  1677. }
  1678. tor_free(tok->args);
  1679. }
  1680. tor_free(tok->object_type);
  1681. tor_free(tok->object_body);
  1682. tor_free(tok->error);
  1683. if (tok->key)
  1684. crypto_free_pk_env(tok->key);
  1685. tor_free(tok);
  1686. }
  1687. #define RET_ERR(msg) \
  1688. do { \
  1689. if (tok) token_free(tok); \
  1690. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  1691. tok->tp = _ERR; \
  1692. tok->error = tor_strdup(msg); \
  1693. goto done_tokenizing; } while (0)
  1694. static INLINE directory_token_t *
  1695. token_check_object(const char *kwd,
  1696. directory_token_t *tok, obj_syntax o_syn)
  1697. {
  1698. char ebuf[128];
  1699. switch (o_syn) {
  1700. case NO_OBJ:
  1701. if (tok->object_body) {
  1702. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  1703. RET_ERR(ebuf);
  1704. }
  1705. if (tok->key) {
  1706. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  1707. RET_ERR(ebuf);
  1708. }
  1709. break;
  1710. case NEED_OBJ:
  1711. if (!tok->object_body) {
  1712. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  1713. RET_ERR(ebuf);
  1714. }
  1715. break;
  1716. case NEED_KEY_1024:
  1717. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  1718. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  1719. kwd, (int)crypto_pk_keysize(tok->key));
  1720. RET_ERR(ebuf);
  1721. }
  1722. /* fall through */
  1723. case NEED_KEY:
  1724. if (!tok->key) {
  1725. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  1726. }
  1727. break;
  1728. case OBJ_OK:
  1729. break;
  1730. }
  1731. done_tokenizing:
  1732. return tok;
  1733. }
  1734. /** Helper function: read the next token from *s, advance *s to the end of the
  1735. * token, and return the parsed token. Parse *<b>s</b> according to the list
  1736. * of tokens in <b>table</b>.
  1737. */
  1738. static directory_token_t *
  1739. get_next_token(const char **s, token_rule_t *table)
  1740. {
  1741. const char *next, *obstart;
  1742. int i, j, done, allocated;
  1743. directory_token_t *tok;
  1744. obj_syntax o_syn = NO_OBJ;
  1745. char ebuf[128];
  1746. const char *kwd = "";
  1747. #define RET_ERR(msg) \
  1748. do { \
  1749. if (tok) token_free(tok); \
  1750. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  1751. tok->tp = _ERR; \
  1752. tok->error = tor_strdup(msg); \
  1753. goto done_tokenizing; } while (0)
  1754. tok = tor_malloc_zero(sizeof(directory_token_t));
  1755. tok->tp = _ERR;
  1756. *s = eat_whitespace(*s);
  1757. if (!**s) {
  1758. tok->tp = _EOF;
  1759. return tok;
  1760. }
  1761. next = find_whitespace(*s);
  1762. if (!next) {
  1763. tok->error = tor_strdup("Unexpected EOF"); return tok;
  1764. }
  1765. /* It's a keyword... but which one? */
  1766. if (!strncmp("opt", *s, next-*s)) {
  1767. /* Skip past an "opt" at the start of the line. */
  1768. *s = eat_whitespace(next);
  1769. next = NULL;
  1770. if (**s)
  1771. next = find_whitespace(*s);
  1772. if (!**s || !next) {
  1773. RET_ERR("opt without keyword");
  1774. }
  1775. }
  1776. /* Search the table for the appropriate entry. (I tried a binary search
  1777. * instead, but it wasn't any faster.) */
  1778. for (i = 0; table[i].t ; ++i) {
  1779. if (!strncmp(table[i].t, *s, next-*s)) {
  1780. /* We've found the keyword. */
  1781. kwd = table[i].t;
  1782. tok->tp = table[i].v;
  1783. o_syn = table[i].os;
  1784. if (table[i].concat_args) {
  1785. /* The keyword takes the line as a single argument */
  1786. *s = eat_whitespace_no_nl(next);
  1787. next = strchr(*s, '\n');
  1788. if (!next)
  1789. RET_ERR("Unexpected EOF");
  1790. tok->args = tor_malloc(sizeof(char*));
  1791. tok->args[0] = tor_strndup(*s,next-*s);
  1792. tok->n_args = 1;
  1793. *s = eat_whitespace_no_nl(next+1);
  1794. } else {
  1795. /* This keyword takes multiple arguments. */
  1796. j = 0;
  1797. done = (*next == '\n');
  1798. allocated = 32;
  1799. tok->args = tor_malloc(sizeof(char*)*32);
  1800. *s = eat_whitespace_no_nl(next);
  1801. while (**s != '\n' && !done) {
  1802. next = find_whitespace(*s);
  1803. if (*next == '\n')
  1804. done = 1;
  1805. if (j == allocated) {
  1806. allocated *= 2;
  1807. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1808. }
  1809. tok->args[j++] = tor_strndup(*s,next-*s);
  1810. *s = eat_whitespace_no_nl(next+1);
  1811. }
  1812. tok->n_args = j;
  1813. }
  1814. if (tok->n_args < table[i].min_args) {
  1815. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  1816. RET_ERR(ebuf);
  1817. } else if (tok->n_args > table[i].max_args) {
  1818. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  1819. RET_ERR(ebuf);
  1820. }
  1821. break;
  1822. }
  1823. }
  1824. if (tok->tp == _ERR) {
  1825. tok->tp = K_OPT;
  1826. *s = eat_whitespace_no_nl(next);
  1827. next = strchr(*s,'\n');
  1828. if (!next)
  1829. RET_ERR("Unexpected EOF");
  1830. tok->args = tor_malloc(sizeof(char*));
  1831. tok->args[0] = tor_strndup(*s,next-*s);
  1832. tok->n_args = 1;
  1833. *s = eat_whitespace_no_nl(next+1);
  1834. o_syn = OBJ_OK;
  1835. }
  1836. *s = eat_whitespace(*s);
  1837. if (strcmpstart(*s, "-----BEGIN ")) {
  1838. goto check_object;
  1839. }
  1840. obstart = *s;
  1841. *s += 11; /* length of "-----BEGIN ". */
  1842. next = strchr(*s, '\n');
  1843. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1844. RET_ERR("Malformed object: bad begin line");
  1845. }
  1846. tok->object_type = tor_strndup(*s, next-*s-5);
  1847. *s = next+1;
  1848. next = strstr(*s, "-----END ");
  1849. if (!next) {
  1850. RET_ERR("Malformed object: missing end line");
  1851. }
  1852. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1853. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1854. RET_ERR("Malformed object: mismatched end line");
  1855. next = strchr(next,'\n')+1;
  1856. tok->key = crypto_new_pk_env();
  1857. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1858. RET_ERR("Couldn't parse public key.");
  1859. *s = next;
  1860. } else {
  1861. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1862. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1863. if (i<0) {
  1864. RET_ERR("Malformed object: bad base64-encoded data");
  1865. }
  1866. tok->object_size = i;
  1867. *s = next + 9; /* length of "-----END ". */
  1868. i = strlen(tok->object_type);
  1869. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1870. RET_ERR("Malformed object: mismatched end tag");
  1871. }
  1872. *s += i+6;
  1873. }
  1874. check_object:
  1875. tok = token_check_object(kwd, tok, o_syn);
  1876. done_tokenizing:
  1877. return tok;
  1878. #undef RET_ERR
  1879. }
  1880. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1881. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  1882. */
  1883. static int
  1884. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1885. token_rule_t *table)
  1886. {
  1887. const char **s;
  1888. directory_token_t *tok = NULL;
  1889. int counts[_NIL];
  1890. int i;
  1891. s = &start;
  1892. if (!end)
  1893. end = start+strlen(start);
  1894. for (i = 0; i < _NIL; ++i)
  1895. counts[i] = 0;
  1896. while (*s < end && (!tok || tok->tp != _EOF)) {
  1897. tok = get_next_token(s, table);
  1898. if (tok->tp == _ERR) {
  1899. log_warn(LD_DIR, "parse error: %s", tok->error);
  1900. return -1;
  1901. }
  1902. ++counts[tok->tp];
  1903. smartlist_add(out, tok);
  1904. *s = eat_whitespace(*s);
  1905. }
  1906. for (i = 0; table[i].t; ++i) {
  1907. if (counts[table[i].v] < table[i].min_cnt) {
  1908. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  1909. tor_assert(0); /* XXX020 is this assert a remote crash waiting to
  1910. * happen? -RD */
  1911. return -1;
  1912. }
  1913. if (counts[table[i].v] > table[i].max_cnt) {
  1914. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  1915. return -1;
  1916. }
  1917. if (table[i].pos & AT_START) {
  1918. if (smartlist_len(out) < 1 ||
  1919. (tok = smartlist_get(out, 0))->tp != table[i].v) {
  1920. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  1921. return -1;
  1922. }
  1923. }
  1924. if (table[i].pos & AT_END) {
  1925. if (smartlist_len(out) < 1 ||
  1926. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  1927. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  1928. return -1;
  1929. }
  1930. }
  1931. }
  1932. return 0;
  1933. }
  1934. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1935. * NULL if no such keyword is found.
  1936. */
  1937. static directory_token_t *
  1938. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1939. {
  1940. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1941. return NULL;
  1942. }
  1943. /** Return a newly allocated smartlist of all accept or reject tokens in
  1944. * <b>s</b>.
  1945. */
  1946. static smartlist_t *
  1947. find_all_exitpolicy(smartlist_t *s)
  1948. {
  1949. smartlist_t *out = smartlist_create();
  1950. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1951. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1952. smartlist_add(out,t));
  1953. return out;
  1954. }
  1955. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  1956. * occurrence of <b>start_str</b> through the first newline after the first
  1957. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1958. * <b>digest</b>; return 0 on success.
  1959. *
  1960. * If no such substring exists, return -1.
  1961. */
  1962. static int
  1963. router_get_hash_impl(const char *s, char *digest,
  1964. const char *start_str,
  1965. const char *end_str)
  1966. {
  1967. char *start, *end;
  1968. start = strstr(s, start_str);
  1969. if (!start) {
  1970. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  1971. return -1;
  1972. }
  1973. if (start != s && *(start-1) != '\n') {
  1974. log_warn(LD_DIR,
  1975. "first occurrence of \"%s\" is not at the start of a line",
  1976. start_str);
  1977. return -1;
  1978. }
  1979. end = strstr(start+strlen(start_str), end_str);
  1980. if (!end) {
  1981. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  1982. return -1;
  1983. }
  1984. end = strchr(end+strlen(end_str), '\n');
  1985. if (!end) {
  1986. log_warn(LD_DIR,"couldn't find EOL");
  1987. return -1;
  1988. }
  1989. ++end;
  1990. if (crypto_digest(digest, start, end-start)) {
  1991. log_warn(LD_BUG,"couldn't compute digest");
  1992. return -1;
  1993. }
  1994. return 0;
  1995. }
  1996. /** Parse the Tor version of the platform string <b>platform</b>,
  1997. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1998. * the router is at least as new as the cutoff, else return 0.
  1999. */
  2000. int
  2001. tor_version_as_new_as(const char *platform, const char *cutoff)
  2002. {
  2003. tor_version_t cutoff_version, router_version;
  2004. char *s, *s2, *start;
  2005. char tmp[128];
  2006. tor_assert(platform);
  2007. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  2008. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  2009. return 0;
  2010. }
  2011. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  2012. return 1;
  2013. start = (char *)eat_whitespace(platform+3);
  2014. if (!*start) return 0;
  2015. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  2016. s2 = (char*)eat_whitespace(s);
  2017. if (!strcmpstart(s2, "(r"))
  2018. s = (char*)find_whitespace(s2);
  2019. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  2020. return 0;
  2021. strlcpy(tmp, start, s-start+1);
  2022. if (tor_version_parse(tmp, &router_version)<0) {
  2023. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  2024. return 1; /* be safe and say yes */
  2025. }
  2026. /* Here's why we don't need to do any special handling for svn revisions:
  2027. * - If neither has an svn revision, we're fine.
  2028. * - If the router doesn't have an svn revision, we can't assume that it
  2029. * is "at least" any svn revision, so we need to return 0.
  2030. * - If the target version doesn't have an svn revision, any svn revision
  2031. * (or none at all) is good enough, so return 1.
  2032. * - If both target and router have an svn revision, we compare them.
  2033. */
  2034. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  2035. }
  2036. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  2037. * Return 0 on success, -1 on failure. */
  2038. int
  2039. tor_version_parse(const char *s, tor_version_t *out)
  2040. {
  2041. char *eos=NULL;
  2042. const char *cp=NULL;
  2043. /* Format is:
  2044. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  2045. */
  2046. tor_assert(s);
  2047. tor_assert(out);
  2048. memset(out, 0, sizeof(tor_version_t));
  2049. if (!strcasecmpstart(s, "Tor "))
  2050. s += 4;
  2051. /* Get major. */
  2052. out->major = strtol(s,&eos,10);
  2053. if (!eos || eos==s || *eos != '.') return -1;
  2054. cp = eos+1;
  2055. /* Get minor */
  2056. out->minor = strtol(cp,&eos,10);
  2057. if (!eos || eos==cp || *eos != '.') return -1;
  2058. cp = eos+1;
  2059. /* Get micro */
  2060. out->micro = strtol(cp,&eos,10);
  2061. if (!eos || eos==cp) return -1;
  2062. if (!*eos) {
  2063. out->status = VER_RELEASE;
  2064. out->patchlevel = 0;
  2065. return 0;
  2066. }
  2067. cp = eos;
  2068. /* Get status */
  2069. if (*cp == '.') {
  2070. out->status = VER_RELEASE;
  2071. ++cp;
  2072. } else if (0==strncmp(cp, "pre", 3)) {
  2073. out->status = VER_PRE;
  2074. cp += 3;
  2075. } else if (0==strncmp(cp, "rc", 2)) {
  2076. out->status = VER_RC;
  2077. cp += 2;
  2078. } else {
  2079. return -1;
  2080. }
  2081. /* Get patchlevel */
  2082. out->patchlevel = strtol(cp,&eos,10);
  2083. if (!eos || eos==cp) return -1;
  2084. cp = eos;
  2085. /* Get status tag. */
  2086. if (*cp == '-' || *cp == '.')
  2087. ++cp;
  2088. eos = (char*) find_whitespace(cp);
  2089. if (eos-cp >= (int)sizeof(out->status_tag))
  2090. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  2091. else {
  2092. memcpy(out->status_tag, cp, eos-cp);
  2093. out->status_tag[eos-cp] = 0;
  2094. }
  2095. cp = eat_whitespace(eos);
  2096. if (!strcmpstart(cp, "(r")) {
  2097. cp += 2;
  2098. out->svn_revision = strtol(cp,&eos,10);
  2099. }
  2100. return 0;
  2101. }
  2102. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  2103. * b. */
  2104. int
  2105. tor_version_compare(tor_version_t *a, tor_version_t *b)
  2106. {
  2107. int i;
  2108. tor_assert(a);
  2109. tor_assert(b);
  2110. if ((i = a->major - b->major))
  2111. return i;
  2112. else if ((i = a->minor - b->minor))
  2113. return i;
  2114. else if ((i = a->micro - b->micro))
  2115. return i;
  2116. else if ((i = a->status - b->status))
  2117. return i;
  2118. else if ((i = a->patchlevel - b->patchlevel))
  2119. return i;
  2120. else if ((i = strcmp(a->status_tag, b->status_tag)))
  2121. return i;
  2122. else
  2123. return a->svn_revision - b->svn_revision;
  2124. }
  2125. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  2126. */
  2127. static int
  2128. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  2129. {
  2130. tor_assert(a);
  2131. tor_assert(b);
  2132. return ((a->major == b->major) &&
  2133. (a->minor == b->minor) &&
  2134. (a->micro == b->micro));
  2135. }
  2136. /** Helper: Given pointers to two strings describing tor versions, return -1
  2137. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  2138. * Used to sort a list of versions. */
  2139. static int
  2140. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  2141. {
  2142. const char *a = *_a, *b = *_b;
  2143. int ca, cb;
  2144. tor_version_t va, vb;
  2145. ca = tor_version_parse(a, &va);
  2146. cb = tor_version_parse(b, &vb);
  2147. /* If they both parse, compare them. */
  2148. if (!ca && !cb)
  2149. return tor_version_compare(&va,&vb);
  2150. /* If one parses, it comes first. */
  2151. if (!ca && cb)
  2152. return -1;
  2153. if (ca && !cb)
  2154. return 1;
  2155. /* If neither parses, compare strings. Also, the directory server admin
  2156. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  2157. return strcmp(a,b);
  2158. }
  2159. /** Sort a list of string-representations of versions in ascending order. */
  2160. void
  2161. sort_version_list(smartlist_t *versions, int remove_duplicates)
  2162. {
  2163. smartlist_sort(versions, _compare_tor_version_str_ptr);
  2164. if (remove_duplicates)
  2165. smartlist_uniq(versions, _compare_tor_version_str_ptr, NULL);
  2166. }