routerparse.c 88 KB

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