routerparse.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  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 *, tok, token_free(tok));
  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 *, tok, token_free(tok));
  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 *, tok, token_free(tok));
  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 *, tok, token_free(tok));
  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. if (cache_copy)
  1060. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1061. extrainfo->cache_info.signed_descriptor_len = end-s;
  1062. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1063. tor_assert(tok->n_args >= 2);
  1064. if (!is_legal_nickname(tok->args[0])) {
  1065. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1066. goto err;
  1067. }
  1068. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1069. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1070. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1071. tok->args[1], HEX_DIGEST_LEN)) {
  1072. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1073. escaped(tok->args[1]));
  1074. goto err;
  1075. }
  1076. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1077. tor_assert(tok);
  1078. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1079. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1080. escaped(tok->args[0]));
  1081. goto err;
  1082. }
  1083. if (routermap &&
  1084. (router = digestmap_get(routermap,
  1085. extrainfo->cache_info.identity_digest))) {
  1086. key = router->identity_pkey;
  1087. }
  1088. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1089. tor_assert(tok);
  1090. if (strcmp(tok->object_type, "SIGNATURE") ||
  1091. tok->object_size < 128 || tok->object_size > 512) {
  1092. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1093. goto err;
  1094. }
  1095. if (key) {
  1096. note_crypto_pk_op(VERIFY_RTR);
  1097. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1098. goto err;
  1099. } else {
  1100. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1101. tok->object_size);
  1102. extrainfo->pending_sig_len = tok->object_size;
  1103. }
  1104. goto done;
  1105. err:
  1106. if (extrainfo)
  1107. extrainfo_free(extrainfo);
  1108. extrainfo = NULL;
  1109. done:
  1110. if (tokens) {
  1111. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  1112. smartlist_free(tokens);
  1113. }
  1114. return extrainfo;
  1115. }
  1116. /** Free storage held in <b>cert</b>. */
  1117. void
  1118. authority_cert_free(authority_cert_t *cert)
  1119. {
  1120. if (!cert)
  1121. return;
  1122. tor_free(cert->cache_info.signed_descriptor_body);
  1123. if (cert->signing_key)
  1124. crypto_free_pk_env(cert->signing_key);
  1125. if (cert->identity_key)
  1126. crypto_free_pk_env(cert->identity_key);
  1127. tor_free(cert);
  1128. }
  1129. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1130. * the first character after the certificate. */
  1131. authority_cert_t *
  1132. authority_cert_parse_from_string(const char *s, char **end_of_string)
  1133. {
  1134. authority_cert_t *cert = NULL;
  1135. smartlist_t *tokens = NULL;
  1136. char digest[DIGEST_LEN];
  1137. directory_token_t *tok;
  1138. char fp_declared[DIGEST_LEN];
  1139. char *eos = strstr(s, "\n-----END SIGNATURE-----\n");
  1140. size_t len;
  1141. if (! eos) {
  1142. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1143. return NULL;
  1144. }
  1145. eos = strchr(eos+2, '\n');
  1146. tor_assert(eos);
  1147. ++eos;
  1148. len = eos - s;
  1149. tokens = smartlist_create();
  1150. if (tokenize_string(s, eos, tokens, dir_key_certificate_table) < 0) {
  1151. log_warn(LD_DIR, "Error tokenizing key certificate");
  1152. goto err;
  1153. }
  1154. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1155. "\ndir-key-certification") < 0)
  1156. goto err;
  1157. tok = smartlist_get(tokens, 0);
  1158. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1159. log_warn(LD_DIR,
  1160. "Key certificate does not begin with a recognized version (3).");
  1161. goto err;
  1162. }
  1163. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1164. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1165. tor_assert(tok && tok->key);
  1166. cert->signing_key = tok->key;
  1167. tok->key = NULL;
  1168. tok = find_first_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1169. tor_assert(tok && tok->key);
  1170. cert->identity_key = tok->key;
  1171. tok->key = NULL;
  1172. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1173. tor_assert(tok && tok->n_args);
  1174. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1175. strlen(tok->args[0]))) {
  1176. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1177. escaped(tok->args[0]));
  1178. goto err;
  1179. }
  1180. if (crypto_pk_get_digest(cert->identity_key,
  1181. cert->cache_info.identity_digest))
  1182. goto err;
  1183. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1184. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1185. "fingerprint");
  1186. goto err;
  1187. }
  1188. tok = find_first_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1189. tor_assert(tok);
  1190. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1191. goto err;
  1192. }
  1193. tok = find_first_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1194. tor_assert(tok);
  1195. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1196. goto err;
  1197. }
  1198. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1199. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1200. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1201. goto err;
  1202. }
  1203. /* XXXXX This doesn't check whether the key is an authority. IS that what we
  1204. * want? */
  1205. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1206. "key certificate")) {
  1207. goto err;
  1208. }
  1209. cert->cache_info.signed_descriptor_len = len;
  1210. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1211. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1212. cert->cache_info.signed_descriptor_body[len] = 0;
  1213. cert->cache_info.saved_location = SAVED_NOWHERE;
  1214. *end_of_string = eos;
  1215. return cert;
  1216. err:
  1217. authority_cert_free(cert);
  1218. return NULL;
  1219. }
  1220. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1221. * object (starting with "r " at the start of a line). If none is found,
  1222. * return the start of the next directory signature. If none is found, return
  1223. * the end of the string. */
  1224. static INLINE const char *
  1225. find_start_of_next_routerstatus(const char *s)
  1226. {
  1227. const char *eos = strstr(s, "\nr ");
  1228. if (!eos)
  1229. eos = strstr(s, "\ndirectory-signature");
  1230. if (eos)
  1231. return eos+1;
  1232. else
  1233. return s + strlen(s);
  1234. }
  1235. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1236. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1237. * object in the string, and advance *<b>s</b> to just after the end of the
  1238. * router status. Return NULL and advance *<b>s</b> on error. */
  1239. static routerstatus_t *
  1240. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens)
  1241. {
  1242. const char *eos;
  1243. routerstatus_t *rs = NULL;
  1244. directory_token_t *tok;
  1245. char timebuf[ISO_TIME_LEN+1];
  1246. struct in_addr in;
  1247. tor_assert(tokens);
  1248. eos = find_start_of_next_routerstatus(*s);
  1249. if (tokenize_string(*s, eos, tokens, rtrstatus_token_table)) {
  1250. log_warn(LD_DIR, "Error tokenizing router status");
  1251. goto err;
  1252. }
  1253. if (smartlist_len(tokens) < 1) {
  1254. log_warn(LD_DIR, "Impossibly short router status");
  1255. goto err;
  1256. }
  1257. tok = find_first_by_keyword(tokens, K_R);
  1258. tor_assert(tok);
  1259. tor_assert(tok->n_args >= 8);
  1260. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1261. if (!is_legal_nickname(tok->args[0])) {
  1262. log_warn(LD_DIR,
  1263. "Invalid nickname %s in router status; skipping.",
  1264. escaped(tok->args[0]));
  1265. goto err;
  1266. }
  1267. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1268. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1269. log_warn(LD_DIR, "Error decoding identity digest %s",
  1270. escaped(tok->args[1]));
  1271. goto err;
  1272. }
  1273. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1274. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1275. escaped(tok->args[2]));
  1276. goto err;
  1277. }
  1278. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1279. tok->args[3], tok->args[4]) < 0 ||
  1280. parse_iso_time(timebuf, &rs->published_on)<0) {
  1281. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1282. tok->args[3], tok->args[4]);
  1283. goto err;
  1284. }
  1285. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1286. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1287. escaped(tok->args[5]));
  1288. goto err;
  1289. }
  1290. rs->addr = ntohl(in.s_addr);
  1291. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1292. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1293. if ((tok = find_first_by_keyword(tokens, K_S))) {
  1294. int i;
  1295. for (i=0; i < tok->n_args; ++i) {
  1296. if (!strcmp(tok->args[i], "Exit"))
  1297. rs->is_exit = 1;
  1298. else if (!strcmp(tok->args[i], "Stable"))
  1299. rs->is_stable = 1;
  1300. else if (!strcmp(tok->args[i], "Fast"))
  1301. rs->is_fast = 1;
  1302. else if (!strcmp(tok->args[i], "Running"))
  1303. rs->is_running = 1;
  1304. else if (!strcmp(tok->args[i], "Named"))
  1305. rs->is_named = 1;
  1306. else if (!strcmp(tok->args[i], "Valid"))
  1307. rs->is_valid = 1;
  1308. else if (!strcmp(tok->args[i], "V2Dir"))
  1309. rs->is_v2_dir = 1;
  1310. else if (!strcmp(tok->args[i], "Guard"))
  1311. rs->is_possible_guard = 1;
  1312. else if (!strcmp(tok->args[i], "BadExit"))
  1313. rs->is_bad_exit = 1;
  1314. else if (!strcmp(tok->args[i], "BadDirectory"))
  1315. rs->is_bad_directory = 1;
  1316. }
  1317. }
  1318. if ((tok = find_first_by_keyword(tokens, K_V))) {
  1319. tor_assert(tok->n_args == 1);
  1320. rs->version_known = 1;
  1321. if (strcmpstart(tok->args[0], "Tor ")) {
  1322. rs->version_supports_begindir = 1;
  1323. rs->version_supports_extrainfo_upload = 1;
  1324. } else {
  1325. rs->version_supports_begindir =
  1326. tor_version_as_new_as(tok->args[0], "0.1.2.2-alpha");
  1327. rs->version_supports_begindir =
  1328. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1329. }
  1330. }
  1331. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1332. rs->is_named = 0;
  1333. goto done;
  1334. err:
  1335. if (rs)
  1336. routerstatus_free(rs);
  1337. rs = NULL;
  1338. done:
  1339. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1340. smartlist_clear(tokens);
  1341. *s = eos;
  1342. return rs;
  1343. }
  1344. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1345. static int
  1346. _compare_routerstatus_entries(const void **_a, const void **_b)
  1347. {
  1348. const routerstatus_t *a = *_a, *b = *_b;
  1349. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1350. }
  1351. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1352. static void
  1353. _free_duplicate_routerstatus_entry(void *e)
  1354. {
  1355. log_warn(LD_DIR,
  1356. "Network-status has two entries for the same router. "
  1357. "Dropping one.");
  1358. routerstatus_free(e);
  1359. }
  1360. /** Given a versioned (v2 or later) network-status object in <b>s</b>, try to
  1361. * parse it and return the result. Return NULL on failure. Check the
  1362. * signature of the network status, but do not (yet) check the signing key for
  1363. * authority.
  1364. */
  1365. networkstatus_t *
  1366. networkstatus_parse_from_string(const char *s)
  1367. {
  1368. const char *eos;
  1369. smartlist_t *tokens = smartlist_create();
  1370. smartlist_t *footer_tokens = smartlist_create();
  1371. networkstatus_t *ns = NULL;
  1372. char ns_digest[DIGEST_LEN];
  1373. char tmp_digest[DIGEST_LEN];
  1374. struct in_addr in;
  1375. directory_token_t *tok;
  1376. int i;
  1377. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1378. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1379. goto err;
  1380. }
  1381. eos = find_start_of_next_routerstatus(s);
  1382. if (tokenize_string(s, eos, tokens, netstatus_token_table)) {
  1383. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1384. goto err;
  1385. }
  1386. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1387. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1388. tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1389. tor_assert(tok);
  1390. tok = find_first_by_keyword(tokens, K_DIR_SOURCE);
  1391. tor_assert(tok);
  1392. tor_assert(tok->n_args >= 3);
  1393. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1394. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1395. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1396. escaped(tok->args[1]));
  1397. goto err;
  1398. }
  1399. ns->source_addr = ntohl(in.s_addr);
  1400. ns->source_dirport =
  1401. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1402. if (ns->source_dirport == 0) {
  1403. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1404. goto err;
  1405. }
  1406. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1407. tor_assert(tok);
  1408. tor_assert(tok->n_args);
  1409. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1410. strlen(tok->args[0]))) {
  1411. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1412. escaped(tok->args[0]));
  1413. goto err;
  1414. }
  1415. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1416. tor_assert(tok->n_args);
  1417. ns->contact = tok->args[0];
  1418. tok->args[0] = NULL;
  1419. }
  1420. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1421. tor_assert(tok && tok->key);
  1422. ns->signing_key = tok->key;
  1423. tok->key = NULL;
  1424. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1425. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1426. goto err;
  1427. }
  1428. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1429. log_warn(LD_DIR,
  1430. "network-status fingerprint did not match dir-signing-key");
  1431. goto err;
  1432. }
  1433. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1434. for (i=0; i < tok->n_args; ++i) {
  1435. if (!strcmp(tok->args[i], "Names"))
  1436. ns->binds_names = 1;
  1437. if (!strcmp(tok->args[i], "Versions"))
  1438. ns->recommends_versions = 1;
  1439. if (!strcmp(tok->args[i], "BadExits"))
  1440. ns->lists_bad_exits = 1;
  1441. if (!strcmp(tok->args[i], "BadDirectories"))
  1442. ns->lists_bad_directories = 1;
  1443. }
  1444. }
  1445. if (ns->recommends_versions) {
  1446. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1447. log_warn(LD_DIR, "Missing client-versions");
  1448. }
  1449. ns->client_versions = tok->args[0];
  1450. tok->args[0] = NULL;
  1451. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1452. tok->n_args<1) {
  1453. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1454. goto err;
  1455. }
  1456. ns->server_versions = tok->args[0];
  1457. tok->args[0] = NULL;
  1458. }
  1459. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1460. tor_assert(tok);
  1461. tor_assert(tok->n_args == 1);
  1462. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1463. goto err;
  1464. }
  1465. ns->entries = smartlist_create();
  1466. s = eos;
  1467. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1468. smartlist_clear(tokens);
  1469. while (!strcmpstart(s, "r ")) {
  1470. routerstatus_t *rs;
  1471. if ((rs = routerstatus_parse_entry_from_string(&s, tokens)))
  1472. smartlist_add(ns->entries, rs);
  1473. }
  1474. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1475. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1476. _free_duplicate_routerstatus_entry);
  1477. if (tokenize_string(s, NULL, footer_tokens, dir_footer_token_table)) {
  1478. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1479. goto err;
  1480. }
  1481. if (smartlist_len(footer_tokens) < 1) {
  1482. log_warn(LD_DIR, "Too few items in network-status footer.");
  1483. goto err;
  1484. }
  1485. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1486. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1487. log_warn(LD_DIR,
  1488. "Expected network-status footer to end with a signature.");
  1489. goto err;
  1490. }
  1491. note_crypto_pk_op(VERIFY_DIR);
  1492. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1493. "network-status") < 0)
  1494. goto err;
  1495. goto done;
  1496. err:
  1497. if (ns)
  1498. networkstatus_free(ns);
  1499. ns = NULL;
  1500. done:
  1501. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1502. smartlist_free(tokens);
  1503. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1504. smartlist_free(footer_tokens);
  1505. return ns;
  1506. }
  1507. /** Parse the addr policy in the string <b>s</b> and return it. If
  1508. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1509. * ADDR_POLICY_REJECT) for items that specify no action.
  1510. */
  1511. addr_policy_t *
  1512. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1513. {
  1514. directory_token_t *tok = NULL;
  1515. const char *cp;
  1516. char *tmp;
  1517. addr_policy_t *r;
  1518. size_t len, idx;
  1519. /* *s might not end with \n, so we need to extend it with one. */
  1520. len = strlen(s);
  1521. cp = tmp = tor_malloc(len+2);
  1522. for (idx = 0; idx < len; ++idx) {
  1523. tmp[idx] = TOR_TOLOWER(s[idx]);
  1524. }
  1525. tmp[len]='\n';
  1526. tmp[len+1]='\0';
  1527. while (TOR_ISSPACE(*cp))
  1528. ++cp;
  1529. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1530. char *new_str = tor_malloc(len+10);
  1531. tor_snprintf(new_str, len+10, "%s %s\n",
  1532. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1533. tor_free(tmp);
  1534. cp = tmp = new_str;
  1535. }
  1536. tok = get_next_token(&cp, routerdesc_token_table);
  1537. if (tok->tp == _ERR) {
  1538. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1539. goto err;
  1540. }
  1541. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1542. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1543. goto err;
  1544. }
  1545. /* Now that we've gotten an addr policy, add it to the router. */
  1546. r = router_parse_addr_policy(tok);
  1547. goto done;
  1548. err:
  1549. r = NULL;
  1550. done:
  1551. tor_free(tmp);
  1552. token_free(tok);
  1553. return r;
  1554. }
  1555. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1556. * <b>router</b>. Return 0 on success, -1 on failure. */
  1557. static int
  1558. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1559. {
  1560. addr_policy_t *newe, **tmpe;
  1561. newe = router_parse_addr_policy(tok);
  1562. if (!newe)
  1563. return -1;
  1564. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1565. ;
  1566. *tmpe = newe;
  1567. return 0;
  1568. }
  1569. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1570. * a new exit_policy_t corresponding to the token. */
  1571. static addr_policy_t *
  1572. router_parse_addr_policy(directory_token_t *tok)
  1573. {
  1574. addr_policy_t *newe;
  1575. char *arg;
  1576. char buf[POLICY_BUF_LEN];
  1577. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1578. if (tok->n_args != 1)
  1579. return NULL;
  1580. arg = tok->args[0];
  1581. if (!strcmpstart(arg,"private"))
  1582. return router_parse_addr_policy_private(tok);
  1583. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1584. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1585. : ADDR_POLICY_ACCEPT;
  1586. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1587. &newe->prt_min, &newe->prt_max))
  1588. goto policy_read_failed;
  1589. if (policy_write_item(buf, sizeof(buf), newe) < 0)
  1590. goto policy_read_failed;
  1591. newe->string = tor_strdup(buf);
  1592. return newe;
  1593. policy_read_failed:
  1594. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1595. tor_free(newe);
  1596. return NULL;
  1597. }
  1598. /** Parse an exit policy line of the format "accept/reject private:...".
  1599. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1600. * router descriptors until earlier versions are obsolete.
  1601. */
  1602. static addr_policy_t *
  1603. router_parse_addr_policy_private(directory_token_t *tok)
  1604. {
  1605. static const char *private_nets[] = {
  1606. "0.0.0.0/8", "169.254.0.0/16",
  1607. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1608. char *arg;
  1609. addr_policy_t *result, **nextp;
  1610. int net;
  1611. uint16_t port_min, port_max;
  1612. arg = tok->args[0];
  1613. if (strcmpstart(arg, "private"))
  1614. return NULL;
  1615. arg += strlen("private");
  1616. arg = (char*) eat_whitespace(arg);
  1617. if (!arg || *arg != ':')
  1618. return NULL;
  1619. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1620. return NULL;
  1621. nextp = &result;
  1622. for (net = 0; private_nets[net]; ++net) {
  1623. size_t len;
  1624. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1625. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1626. : ADDR_POLICY_ACCEPT;
  1627. len = strlen(arg)+strlen(private_nets[net])+16;
  1628. (*nextp)->string = tor_malloc(len+1);
  1629. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1630. tok->tp == K_REJECT ? "reject" : "accept",
  1631. private_nets[net], arg);
  1632. if (parse_addr_and_port_range((*nextp)->string + 7,
  1633. &(*nextp)->addr, &(*nextp)->msk,
  1634. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1635. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1636. return NULL;
  1637. }
  1638. nextp = &(*nextp)->next;
  1639. }
  1640. return result;
  1641. }
  1642. /** Log and exit if <b>t</b> is malformed */
  1643. void
  1644. assert_addr_policy_ok(addr_policy_t *t)
  1645. {
  1646. addr_policy_t *t2;
  1647. while (t) {
  1648. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1649. t->policy_type == ADDR_POLICY_ACCEPT);
  1650. tor_assert(t->prt_min <= t->prt_max);
  1651. t2 = router_parse_addr_policy_from_string(t->string, -1);
  1652. tor_assert(t2);
  1653. tor_assert(t2->policy_type == t->policy_type);
  1654. tor_assert(t2->addr == t->addr);
  1655. tor_assert(t2->msk == t->msk);
  1656. tor_assert(t2->prt_min == t->prt_min);
  1657. tor_assert(t2->prt_max == t->prt_max);
  1658. tor_assert(!strcmp(t2->string, t->string));
  1659. tor_assert(t2->next == NULL);
  1660. addr_policy_free(t2);
  1661. t = t->next;
  1662. }
  1663. }
  1664. /*
  1665. * Low-level tokenizer for router descriptors and directories.
  1666. */
  1667. /** Free all resources allocated for <b>tok</b> */
  1668. static void
  1669. token_free(directory_token_t *tok)
  1670. {
  1671. int i;
  1672. tor_assert(tok);
  1673. if (tok->args) {
  1674. for (i = 0; i < tok->n_args; ++i) {
  1675. tor_free(tok->args[i]);
  1676. }
  1677. tor_free(tok->args);
  1678. }
  1679. tor_free(tok->object_type);
  1680. tor_free(tok->object_body);
  1681. tor_free(tok->error);
  1682. if (tok->key)
  1683. crypto_free_pk_env(tok->key);
  1684. tor_free(tok);
  1685. }
  1686. #define RET_ERR(msg) \
  1687. do { \
  1688. if (tok) token_free(tok); \
  1689. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  1690. tok->tp = _ERR; \
  1691. tok->error = tor_strdup(msg); \
  1692. goto done_tokenizing; } while (0)
  1693. static INLINE directory_token_t *
  1694. token_check_object(const char *kwd,
  1695. directory_token_t *tok, obj_syntax o_syn)
  1696. {
  1697. char ebuf[128];
  1698. switch (o_syn) {
  1699. case NO_OBJ:
  1700. if (tok->object_body) {
  1701. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  1702. RET_ERR(ebuf);
  1703. }
  1704. if (tok->key) {
  1705. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  1706. RET_ERR(ebuf);
  1707. }
  1708. break;
  1709. case NEED_OBJ:
  1710. if (!tok->object_body) {
  1711. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  1712. RET_ERR(ebuf);
  1713. }
  1714. break;
  1715. case NEED_KEY_1024:
  1716. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  1717. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  1718. kwd, (int)crypto_pk_keysize(tok->key));
  1719. RET_ERR(ebuf);
  1720. }
  1721. /* fall through */
  1722. case NEED_KEY:
  1723. if (!tok->key) {
  1724. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  1725. }
  1726. break;
  1727. case OBJ_OK:
  1728. break;
  1729. }
  1730. done_tokenizing:
  1731. return tok;
  1732. }
  1733. /** Helper function: read the next token from *s, advance *s to the end of the
  1734. * token, and return the parsed token. Parse *<b>s</b> according to the list
  1735. * of tokens in <b>table</b>.
  1736. */
  1737. static directory_token_t *
  1738. get_next_token(const char **s, token_rule_t *table)
  1739. {
  1740. const char *next, *obstart;
  1741. int i, j, done, allocated;
  1742. directory_token_t *tok;
  1743. obj_syntax o_syn = NO_OBJ;
  1744. char ebuf[128];
  1745. const char *kwd = "";
  1746. #define RET_ERR(msg) \
  1747. do { \
  1748. if (tok) token_free(tok); \
  1749. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  1750. tok->tp = _ERR; \
  1751. tok->error = tor_strdup(msg); \
  1752. goto done_tokenizing; } while (0)
  1753. tok = tor_malloc_zero(sizeof(directory_token_t));
  1754. tok->tp = _ERR;
  1755. *s = eat_whitespace(*s);
  1756. if (!**s) {
  1757. tok->tp = _EOF;
  1758. return tok;
  1759. }
  1760. next = find_whitespace(*s);
  1761. if (!next) {
  1762. tok->error = tor_strdup("Unexpected EOF"); return tok;
  1763. }
  1764. /* It's a keyword... but which one? */
  1765. if (!strncmp("opt", *s, next-*s)) {
  1766. /* Skip past an "opt" at the start of the line. */
  1767. *s = eat_whitespace(next);
  1768. next = NULL;
  1769. if (**s)
  1770. next = find_whitespace(*s);
  1771. if (!**s || !next) {
  1772. RET_ERR("opt without keyword");
  1773. }
  1774. }
  1775. /* Search the table for the appropriate entry. (I tried a binary search
  1776. * instead, but it wasn't any faster.) */
  1777. for (i = 0; table[i].t ; ++i) {
  1778. if (!strncmp(table[i].t, *s, next-*s)) {
  1779. /* We've found the keyword. */
  1780. kwd = table[i].t;
  1781. tok->tp = table[i].v;
  1782. o_syn = table[i].os;
  1783. if (table[i].concat_args) {
  1784. /* The keyword takes the line as a single argument */
  1785. *s = eat_whitespace_no_nl(next);
  1786. next = strchr(*s, '\n');
  1787. if (!next)
  1788. RET_ERR("Unexpected EOF");
  1789. tok->args = tor_malloc(sizeof(char*));
  1790. tok->args[0] = tor_strndup(*s,next-*s);
  1791. tok->n_args = 1;
  1792. *s = eat_whitespace_no_nl(next+1);
  1793. } else {
  1794. /* This keyword takes multiple arguments. */
  1795. j = 0;
  1796. done = (*next == '\n');
  1797. allocated = 32;
  1798. tok->args = tor_malloc(sizeof(char*)*32);
  1799. *s = eat_whitespace_no_nl(next);
  1800. while (**s != '\n' && !done) {
  1801. next = find_whitespace(*s);
  1802. if (*next == '\n')
  1803. done = 1;
  1804. if (j == allocated) {
  1805. allocated *= 2;
  1806. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1807. }
  1808. tok->args[j++] = tor_strndup(*s,next-*s);
  1809. *s = eat_whitespace_no_nl(next+1);
  1810. }
  1811. tok->n_args = j;
  1812. }
  1813. if (tok->n_args < table[i].min_args) {
  1814. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  1815. RET_ERR(ebuf);
  1816. } else if (tok->n_args > table[i].max_args) {
  1817. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  1818. RET_ERR(ebuf);
  1819. }
  1820. break;
  1821. }
  1822. }
  1823. if (tok->tp == _ERR) {
  1824. tok->tp = K_OPT;
  1825. *s = eat_whitespace_no_nl(next);
  1826. next = strchr(*s,'\n');
  1827. if (!next)
  1828. RET_ERR("Unexpected EOF");
  1829. tok->args = tor_malloc(sizeof(char*));
  1830. tok->args[0] = tor_strndup(*s,next-*s);
  1831. tok->n_args = 1;
  1832. *s = eat_whitespace_no_nl(next+1);
  1833. o_syn = OBJ_OK;
  1834. }
  1835. *s = eat_whitespace(*s);
  1836. if (strcmpstart(*s, "-----BEGIN ")) {
  1837. goto check_object;
  1838. }
  1839. obstart = *s;
  1840. *s += 11; /* length of "-----BEGIN ". */
  1841. next = strchr(*s, '\n');
  1842. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1843. RET_ERR("Malformed object: bad begin line");
  1844. }
  1845. tok->object_type = tor_strndup(*s, next-*s-5);
  1846. *s = next+1;
  1847. next = strstr(*s, "-----END ");
  1848. if (!next) {
  1849. RET_ERR("Malformed object: missing end line");
  1850. }
  1851. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1852. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1853. RET_ERR("Malformed object: mismatched end line");
  1854. next = strchr(next,'\n')+1;
  1855. tok->key = crypto_new_pk_env();
  1856. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1857. RET_ERR("Couldn't parse public key.");
  1858. *s = next;
  1859. } else {
  1860. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1861. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1862. if (i<0) {
  1863. RET_ERR("Malformed object: bad base64-encoded data");
  1864. }
  1865. tok->object_size = i;
  1866. *s = next + 9; /* length of "-----END ". */
  1867. i = strlen(tok->object_type);
  1868. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1869. RET_ERR("Malformed object: mismatched end tag");
  1870. }
  1871. *s += i+6;
  1872. }
  1873. check_object:
  1874. tok = token_check_object(kwd, tok, o_syn);
  1875. done_tokenizing:
  1876. return tok;
  1877. #undef RET_ERR
  1878. }
  1879. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1880. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  1881. */
  1882. static int
  1883. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1884. token_rule_t *table)
  1885. {
  1886. const char **s;
  1887. directory_token_t *tok = NULL;
  1888. int counts[_NIL];
  1889. int i;
  1890. s = &start;
  1891. if (!end)
  1892. end = start+strlen(start);
  1893. for (i = 0; i < _NIL; ++i)
  1894. counts[i] = 0;
  1895. while (*s < end && (!tok || tok->tp != _EOF)) {
  1896. tok = get_next_token(s, table);
  1897. if (tok->tp == _ERR) {
  1898. log_warn(LD_DIR, "parse error: %s", tok->error);
  1899. return -1;
  1900. }
  1901. ++counts[tok->tp];
  1902. smartlist_add(out, tok);
  1903. *s = eat_whitespace(*s);
  1904. }
  1905. for (i = 0; table[i].t; ++i) {
  1906. if (counts[table[i].v] < table[i].min_cnt) {
  1907. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  1908. tor_assert(0);
  1909. return -1;
  1910. }
  1911. if (counts[table[i].v] > table[i].max_cnt) {
  1912. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  1913. return -1;
  1914. }
  1915. if (table[i].pos & AT_START) {
  1916. if (smartlist_len(out) < 1 ||
  1917. (tok = smartlist_get(out, 0))->tp != table[i].v) {
  1918. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  1919. return -1;
  1920. }
  1921. }
  1922. if (table[i].pos & AT_END) {
  1923. if (smartlist_len(out) < 1 ||
  1924. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  1925. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  1926. return -1;
  1927. }
  1928. }
  1929. }
  1930. return 0;
  1931. }
  1932. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1933. * NULL if no such keyword is found.
  1934. */
  1935. static directory_token_t *
  1936. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1937. {
  1938. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1939. return NULL;
  1940. }
  1941. /** Return a newly allocated smartlist of all accept or reject tokens in
  1942. * <b>s</b>.
  1943. */
  1944. static smartlist_t *
  1945. find_all_exitpolicy(smartlist_t *s)
  1946. {
  1947. smartlist_t *out = smartlist_create();
  1948. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1949. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1950. smartlist_add(out,t));
  1951. return out;
  1952. }
  1953. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  1954. * occurrence of <b>start_str</b> through the first newline after the first
  1955. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1956. * <b>digest</b>; return 0 on success.
  1957. *
  1958. * If no such substring exists, return -1.
  1959. */
  1960. static int
  1961. router_get_hash_impl(const char *s, char *digest,
  1962. const char *start_str,
  1963. const char *end_str)
  1964. {
  1965. char *start, *end;
  1966. start = strstr(s, start_str);
  1967. if (!start) {
  1968. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  1969. return -1;
  1970. }
  1971. if (start != s && *(start-1) != '\n') {
  1972. log_warn(LD_DIR,
  1973. "first occurrence of \"%s\" is not at the start of a line",
  1974. start_str);
  1975. return -1;
  1976. }
  1977. end = strstr(start+strlen(start_str), end_str);
  1978. if (!end) {
  1979. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  1980. return -1;
  1981. }
  1982. end = strchr(end+strlen(end_str), '\n');
  1983. if (!end) {
  1984. log_warn(LD_DIR,"couldn't find EOL");
  1985. return -1;
  1986. }
  1987. ++end;
  1988. if (crypto_digest(digest, start, end-start)) {
  1989. log_warn(LD_BUG,"couldn't compute digest");
  1990. return -1;
  1991. }
  1992. return 0;
  1993. }
  1994. /** Parse the Tor version of the platform string <b>platform</b>,
  1995. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1996. * the router is at least as new as the cutoff, else return 0.
  1997. */
  1998. int
  1999. tor_version_as_new_as(const char *platform, const char *cutoff)
  2000. {
  2001. tor_version_t cutoff_version, router_version;
  2002. char *s, *s2, *start;
  2003. char tmp[128];
  2004. tor_assert(platform);
  2005. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  2006. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  2007. return 0;
  2008. }
  2009. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  2010. return 1;
  2011. start = (char *)eat_whitespace(platform+3);
  2012. if (!*start) return 0;
  2013. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  2014. s2 = (char*)eat_whitespace(s);
  2015. if (!strcmpstart(s2, "(r"))
  2016. s = (char*)find_whitespace(s2);
  2017. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  2018. return 0;
  2019. strlcpy(tmp, start, s-start+1);
  2020. if (tor_version_parse(tmp, &router_version)<0) {
  2021. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  2022. return 1; /* be safe and say yes */
  2023. }
  2024. /* Here's why we don't need to do any special handling for svn revisions:
  2025. * - If neither has an svn revision, we're fine.
  2026. * - If the router doesn't have an svn revision, we can't assume that it
  2027. * is "at least" any svn revision, so we need to return 0.
  2028. * - If the target version doesn't have an svn revision, any svn revision
  2029. * (or none at all) is good enough, so return 1.
  2030. * - If both target and router have an svn revision, we compare them.
  2031. */
  2032. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  2033. }
  2034. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  2035. * Return 0 on success, -1 on failure. */
  2036. int
  2037. tor_version_parse(const char *s, tor_version_t *out)
  2038. {
  2039. char *eos=NULL;
  2040. const char *cp=NULL;
  2041. /* Format is:
  2042. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  2043. */
  2044. tor_assert(s);
  2045. tor_assert(out);
  2046. memset(out, 0, sizeof(tor_version_t));
  2047. if (!strcasecmpstart(s, "Tor "))
  2048. s += 4;
  2049. /* Get major. */
  2050. out->major = strtol(s,&eos,10);
  2051. if (!eos || eos==s || *eos != '.') return -1;
  2052. cp = eos+1;
  2053. /* Get minor */
  2054. out->minor = strtol(cp,&eos,10);
  2055. if (!eos || eos==cp || *eos != '.') return -1;
  2056. cp = eos+1;
  2057. /* Get micro */
  2058. out->micro = strtol(cp,&eos,10);
  2059. if (!eos || eos==cp) return -1;
  2060. if (!*eos) {
  2061. out->status = VER_RELEASE;
  2062. out->patchlevel = 0;
  2063. return 0;
  2064. }
  2065. cp = eos;
  2066. /* Get status */
  2067. if (*cp == '.') {
  2068. out->status = VER_RELEASE;
  2069. ++cp;
  2070. } else if (0==strncmp(cp, "pre", 3)) {
  2071. out->status = VER_PRE;
  2072. cp += 3;
  2073. } else if (0==strncmp(cp, "rc", 2)) {
  2074. out->status = VER_RC;
  2075. cp += 2;
  2076. } else {
  2077. return -1;
  2078. }
  2079. /* Get patchlevel */
  2080. out->patchlevel = strtol(cp,&eos,10);
  2081. if (!eos || eos==cp) return -1;
  2082. cp = eos;
  2083. /* Get status tag. */
  2084. if (*cp == '-' || *cp == '.')
  2085. ++cp;
  2086. eos = (char*) find_whitespace(cp);
  2087. if (eos-cp >= (int)sizeof(out->status_tag))
  2088. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  2089. else {
  2090. memcpy(out->status_tag, cp, eos-cp);
  2091. out->status_tag[eos-cp] = 0;
  2092. }
  2093. cp = eat_whitespace(eos);
  2094. if (!strcmpstart(cp, "(r")) {
  2095. cp += 2;
  2096. out->svn_revision = strtol(cp,&eos,10);
  2097. }
  2098. return 0;
  2099. }
  2100. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  2101. * b. */
  2102. int
  2103. tor_version_compare(tor_version_t *a, tor_version_t *b)
  2104. {
  2105. int i;
  2106. tor_assert(a);
  2107. tor_assert(b);
  2108. if ((i = a->major - b->major))
  2109. return i;
  2110. else if ((i = a->minor - b->minor))
  2111. return i;
  2112. else if ((i = a->micro - b->micro))
  2113. return i;
  2114. else if ((i = a->status - b->status))
  2115. return i;
  2116. else if ((i = a->patchlevel - b->patchlevel))
  2117. return i;
  2118. else if ((i = strcmp(a->status_tag, b->status_tag)))
  2119. return i;
  2120. else
  2121. return a->svn_revision - b->svn_revision;
  2122. }
  2123. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  2124. */
  2125. static int
  2126. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  2127. {
  2128. tor_assert(a);
  2129. tor_assert(b);
  2130. return ((a->major == b->major) &&
  2131. (a->minor == b->minor) &&
  2132. (a->micro == b->micro));
  2133. }
  2134. /** Helper: Given pointers to two strings describing tor versions, return -1
  2135. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  2136. * Used to sort a list of versions. */
  2137. static int
  2138. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  2139. {
  2140. const char *a = *_a, *b = *_b;
  2141. int ca, cb;
  2142. tor_version_t va, vb;
  2143. ca = tor_version_parse(a, &va);
  2144. cb = tor_version_parse(b, &vb);
  2145. /* If they both parse, compare them. */
  2146. if (!ca && !cb)
  2147. return tor_version_compare(&va,&vb);
  2148. /* If one parses, it comes first. */
  2149. if (!ca && cb)
  2150. return -1;
  2151. if (ca && !cb)
  2152. return 1;
  2153. /* If neither parses, compare strings. Also, the directory server admin
  2154. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  2155. return strcmp(a,b);
  2156. }
  2157. /** Sort a list of string-representations of versions in ascending order. */
  2158. void
  2159. sort_version_list(smartlist_t *versions, int remove_duplicates)
  2160. {
  2161. smartlist_sort(versions, _compare_tor_version_str_ptr);
  2162. if (remove_duplicates)
  2163. smartlist_uniq(versions, _compare_tor_version_str_ptr, NULL);
  2164. }