routerparse.c 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807
  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. const char *eos,
  315. token_rule_t *table);
  316. static int check_signature_token(const char *digest,
  317. directory_token_t *tok,
  318. crypto_pk_env_t *pkey,
  319. int check_authority,
  320. const char *doctype);
  321. static crypto_pk_env_t *find_dir_signing_key(const char *str, const char *eos);
  322. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  323. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  324. * <b>s</b>. Return 0 on success, -1 on failure.
  325. */
  326. int
  327. router_get_dir_hash(const char *s, char *digest)
  328. {
  329. return router_get_hash_impl(s,digest,
  330. "signed-directory","\ndirectory-signature",'\n');
  331. }
  332. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  333. * <b>s</b>. Return 0 on success, -1 on failure.
  334. */
  335. int
  336. router_get_router_hash(const char *s, char *digest)
  337. {
  338. return router_get_hash_impl(s,digest,
  339. "router ","\nrouter-signature", '\n');
  340. }
  341. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  342. * string in <b>s</b>. Return 0 on success, -1 on failure.
  343. */
  344. int
  345. router_get_runningrouters_hash(const char *s, char *digest)
  346. {
  347. return router_get_hash_impl(s,digest,
  348. "network-status","\ndirectory-signature", '\n');
  349. }
  350. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  351. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  352. int
  353. router_get_networkstatus_v2_hash(const char *s, char *digest)
  354. {
  355. return router_get_hash_impl(s,digest,
  356. "network-status-version","\ndirectory-signature",
  357. '\n');
  358. }
  359. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  360. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  361. int
  362. router_get_networkstatus_v3_hash(const char *s, char *digest)
  363. {
  364. return router_get_hash_impl(s,digest,
  365. "network-status-version","\ndirectory-signature",
  366. ' ');
  367. }
  368. /** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
  369. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  370. int
  371. router_get_extrainfo_hash(const char *s, char *digest)
  372. {
  373. return router_get_hash_impl(s,digest,"extra-info","\nrouter-signature",'\n');
  374. }
  375. /** Helper: used to generate signatures for routers, directories and
  376. * network-status objects. Given a digest in <b>digest</b> and a secret
  377. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  378. * surround it with -----BEGIN/END----- pairs, and write it to the
  379. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  380. * failure.
  381. */
  382. int
  383. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  384. crypto_pk_env_t *private_key)
  385. {
  386. char *signature;
  387. int i;
  388. signature = tor_malloc(crypto_pk_keysize(private_key));
  389. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  390. log_warn(LD_BUG,"Couldn't sign digest.");
  391. goto err;
  392. }
  393. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  394. goto truncated;
  395. i = strlen(buf);
  396. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  397. log_warn(LD_BUG,"couldn't base64-encode signature");
  398. tor_free(buf);
  399. goto err;
  400. }
  401. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  402. goto truncated;
  403. tor_free(signature);
  404. return 0;
  405. truncated:
  406. log_warn(LD_BUG,"tried to exceed string length.");
  407. err:
  408. tor_free(signature);
  409. return -1;
  410. }
  411. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  412. * <b>versionlist</b>. Else, return VS_OLD if every member of
  413. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  414. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  415. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  416. * is newer than <b>myversion.</b>. Else, return VS_NEW if every memeber of
  417. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  418. * VS_UNRECOMMENDED.
  419. *
  420. * (versionlist is a comma-separated list of version strings,
  421. * optionally prefixed with "Tor". Versions that can't be parsed are
  422. * ignored.)
  423. */
  424. version_status_t
  425. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  426. {
  427. tor_version_t mine, other;
  428. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  429. found_any_in_series = 0, r, same;
  430. version_status_t ret = VS_UNRECOMMENDED;
  431. smartlist_t *version_sl;
  432. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  433. myversion, versionlist);
  434. if (tor_version_parse(myversion, &mine)) {
  435. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  436. tor_assert(0);
  437. }
  438. version_sl = smartlist_create();
  439. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  440. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  441. if (!strcmpstart(cp, "Tor "))
  442. cp += 4;
  443. if (tor_version_parse(cp, &other)) {
  444. /* Couldn't parse other; it can't be a match. */
  445. } else {
  446. same = tor_version_same_series(&mine, &other);
  447. if (same)
  448. found_any_in_series = 1;
  449. r = tor_version_compare(&mine, &other);
  450. if (r==0) {
  451. ret = VS_RECOMMENDED;
  452. goto done;
  453. } else if (r<0) {
  454. found_newer = 1;
  455. if (same)
  456. found_newer_in_series = 1;
  457. } else if (r>0) {
  458. found_older = 1;
  459. }
  460. }
  461. });
  462. /* We didn't find the listed version. Is it new or old? */
  463. if (found_any_in_series && !found_newer_in_series && found_newer) {
  464. ret = VS_NEW_IN_SERIES;
  465. } else if (found_newer && !found_older) {
  466. ret = VS_OLD;
  467. } else if (found_older && !found_newer) {
  468. ret = VS_NEW;
  469. } else {
  470. ret = VS_UNRECOMMENDED;
  471. }
  472. done:
  473. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  474. smartlist_free(version_sl);
  475. return ret;
  476. }
  477. /** Return the combined status of the current version, given that we know of
  478. * one set of networkstatuses that give us status <b>a</b>, and another that
  479. * gives us status <b>b</b>.
  480. *
  481. * For example, if one authority thinks that we're NEW, and another thinks
  482. * we're OLD, we're simply UNRECOMMENDED.
  483. *
  484. * This function does not handle calculating whether we're RECOMMENDED; that
  485. * follows a simple majority rule. This function simply calculates *why*
  486. * we're not recommended (if we're not).
  487. */
  488. version_status_t
  489. version_status_join(version_status_t a, version_status_t b)
  490. {
  491. if (a == b)
  492. return a;
  493. else if (a == VS_UNRECOMMENDED || b == VS_UNRECOMMENDED)
  494. return VS_UNRECOMMENDED;
  495. else if (a == VS_RECOMMENDED)
  496. return b;
  497. else if (b == VS_RECOMMENDED)
  498. return a;
  499. /* Okay. Neither is 'recommended' or 'unrecommended', and they differ. */
  500. else if (a == VS_OLD || b == VS_OLD)
  501. return VS_UNRECOMMENDED;
  502. /* One is VS_NEW, the other is VS_NEW_IN_SERIES */
  503. else
  504. return VS_NEW_IN_SERIES;
  505. }
  506. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  507. * Otherwise, return -1. If we're a directory cache, cache it.
  508. */
  509. int
  510. router_parse_directory(const char *str)
  511. {
  512. directory_token_t *tok;
  513. char digest[DIGEST_LEN];
  514. time_t published_on;
  515. int r;
  516. const char *end, *cp;
  517. smartlist_t *tokens = NULL;
  518. crypto_pk_env_t *declared_key = NULL;
  519. /* XXXX This could be simplified a lot, but it will all go away
  520. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  521. * touch it. */
  522. if (router_get_dir_hash(str, digest)) {
  523. log_warn(LD_DIR, "Unable to compute digest of directory");
  524. goto err;
  525. }
  526. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  527. /* Check signature first, before we try to tokenize. */
  528. cp = str;
  529. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  530. cp = end;
  531. if (cp == str || !cp) {
  532. log_warn(LD_DIR, "No signature found on directory."); goto err;
  533. }
  534. ++cp;
  535. tokens = smartlist_create();
  536. if (tokenize_string(cp,strchr(cp,'\0'),tokens,dir_token_table)) {
  537. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  538. }
  539. if (smartlist_len(tokens) != 1) {
  540. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  541. }
  542. tok=smartlist_get(tokens,0);
  543. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  544. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  545. }
  546. declared_key = find_dir_signing_key(str, str+strlen(str));
  547. note_crypto_pk_op(VERIFY_DIR);
  548. if (check_signature_token(digest, tok, declared_key, 1, "directory")<0)
  549. goto err;
  550. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  551. smartlist_free(tokens);
  552. tokens = NULL;
  553. /* Now try to parse the first part of the directory. */
  554. if ((end = strstr(str,"\nrouter "))) {
  555. ++end;
  556. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  557. ++end;
  558. } else {
  559. end = str + strlen(str);
  560. }
  561. tokens = smartlist_create();
  562. if (tokenize_string(str,end,tokens,dir_token_table)) {
  563. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  564. }
  565. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  566. tor_assert(tok);
  567. tor_assert(tok->n_args == 1);
  568. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  569. goto err;
  570. }
  571. /* Now that we know the signature is okay, and we have a
  572. * publication time, cache the directory. */
  573. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  574. dirserv_set_cached_directory(str, published_on, 0);
  575. r = 0;
  576. goto done;
  577. err:
  578. r = -1;
  579. done:
  580. if (declared_key) crypto_free_pk_env(declared_key);
  581. if (tokens) {
  582. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  583. smartlist_free(tokens);
  584. }
  585. return r;
  586. }
  587. /** Read a signed router status statement from <b>str</b>. If it's
  588. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  589. * cache it.*/
  590. int
  591. router_parse_runningrouters(const char *str)
  592. {
  593. char digest[DIGEST_LEN];
  594. directory_token_t *tok;
  595. time_t published_on;
  596. int r = -1;
  597. crypto_pk_env_t *declared_key = NULL;
  598. smartlist_t *tokens = NULL;
  599. const char *eos = str + strlen(str);
  600. if (router_get_runningrouters_hash(str, digest)) {
  601. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  602. goto err;
  603. }
  604. tokens = smartlist_create();
  605. if (tokenize_string(str,eos,tokens,dir_token_table)) {
  606. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  607. }
  608. tok = smartlist_get(tokens,0);
  609. if (tok->tp != K_NETWORK_STATUS) {
  610. log_warn(LD_DIR, "Network-status starts with wrong token");
  611. goto err;
  612. }
  613. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  614. tor_assert(tok);
  615. tor_assert(tok->n_args == 1);
  616. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  617. goto err;
  618. }
  619. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  620. log_warn(LD_DIR, "Missing signature on running-routers");
  621. goto err;
  622. }
  623. declared_key = find_dir_signing_key(str, eos);
  624. note_crypto_pk_op(VERIFY_DIR);
  625. if (check_signature_token(digest, tok, declared_key, 1, "running-routers")
  626. < 0)
  627. goto err;
  628. /* Now that we know the signature is okay, and we have a
  629. * publication time, cache the list. */
  630. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  631. dirserv_set_cached_directory(str, published_on, 1);
  632. r = 0;
  633. err:
  634. if (declared_key) crypto_free_pk_env(declared_key);
  635. if (tokens) {
  636. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  637. smartlist_free(tokens);
  638. }
  639. return r;
  640. }
  641. /** Given a directory or running-routers string in <b>str</b>, try to
  642. * find the its dir-signing-key token (if any). If this token is
  643. * present, extract and return the key. Return NULL on failure. */
  644. static crypto_pk_env_t *
  645. find_dir_signing_key(const char *str, const char *eos)
  646. {
  647. const char *cp;
  648. directory_token_t *tok;
  649. crypto_pk_env_t *key = NULL;
  650. tor_assert(str);
  651. tor_assert(eos);
  652. /* Is there a dir-signing-key in the directory? */
  653. cp = tor_memstr(str, eos-str, "\nopt dir-signing-key");
  654. if (!cp)
  655. cp = tor_memstr(str, eos-str, "\ndir-signing-key");
  656. if (!cp)
  657. return NULL;
  658. ++cp; /* Now cp points to the start of the token. */
  659. tok = get_next_token(&cp, eos, dir_token_table);
  660. if (!tok) {
  661. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  662. return NULL;
  663. }
  664. if (tok->tp != K_DIR_SIGNING_KEY) {
  665. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  666. return NULL;
  667. }
  668. if (tok->key) {
  669. key = tok->key;
  670. tok->key = NULL; /* steal reference. */
  671. } else {
  672. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  673. return NULL;
  674. }
  675. token_free(tok);
  676. return key;
  677. }
  678. /** Return true iff <b>key</b> is allowed to sign directories.
  679. */
  680. static int
  681. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  682. {
  683. char digest[DIGEST_LEN];
  684. if (!key) return 0;
  685. if (crypto_pk_get_digest(key, digest) < 0) {
  686. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  687. return 0;
  688. }
  689. if (!router_digest_is_trusted_dir(digest)) {
  690. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  691. return 0;
  692. }
  693. return 1;
  694. }
  695. /** Check whether the object body of the token in <b>tok</b> has a good
  696. * signature for <b>digest</b> using key <b>pkey</b>. If
  697. * <b>check_authority</b> is set, make sure that <b>pkey</b> is the key of a
  698. * directory authority. Use <b>doctype</b> as the type of the document when
  699. * generating log messages. Return 0 on success, negative on failure.
  700. */
  701. static int
  702. check_signature_token(const char *digest,
  703. directory_token_t *tok,
  704. crypto_pk_env_t *pkey,
  705. int check_authority,
  706. const char *doctype)
  707. {
  708. char *signed_digest;
  709. tor_assert(pkey);
  710. tor_assert(tok);
  711. tor_assert(digest);
  712. tor_assert(doctype);
  713. if (check_authority && !dir_signing_key_is_trusted(pkey)) {
  714. log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
  715. doctype);
  716. return -1;
  717. }
  718. if (strcmp(tok->object_type, "SIGNATURE")) {
  719. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  720. return -1;
  721. }
  722. signed_digest = tor_malloc(tok->object_size);
  723. if (crypto_pk_public_checksig(pkey, signed_digest, tok->object_body,
  724. tok->object_size)
  725. != DIGEST_LEN) {
  726. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  727. tor_free(signed_digest);
  728. return -1;
  729. }
  730. log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  731. hex_str(signed_digest,4));
  732. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  733. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  734. tor_free(signed_digest);
  735. return -1;
  736. }
  737. tor_free(signed_digest);
  738. return 0;
  739. }
  740. /** Given a string *<b>s</b> containing a concatenated sequence of router
  741. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  742. * them and stores the result in <b>dest</b>. All routers are marked running
  743. * and valid. Advances *s to a point immediately following the last router
  744. * entry. Ignore any trailing router entries that are not complete.
  745. *
  746. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  747. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  748. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  749. *
  750. * Returns 0 on success and -1 on failure.
  751. */
  752. int
  753. router_parse_list_from_string(const char **s, const char *eos,
  754. smartlist_t *dest,
  755. saved_location_t saved_location,
  756. int want_extrainfo)
  757. {
  758. routerinfo_t *router;
  759. extrainfo_t *extrainfo;
  760. signed_descriptor_t *signed_desc;
  761. void *elt;
  762. const char *end, *start;
  763. int have_extrainfo;
  764. tor_assert(s);
  765. tor_assert(*s);
  766. tor_assert(dest);
  767. start = *s;
  768. if (!eos)
  769. eos = *s + strlen(*s);
  770. tor_assert(eos >= *s);
  771. while (1) {
  772. *s = eat_whitespace_eos(*s, eos);
  773. if ((eos - *s) < 32) /* make sure it's long enough. */
  774. break;
  775. /* Don't start parsing the rest of *s unless it contains a router. */
  776. if (strcmpstart(*s, "extra-info ")==0) {
  777. have_extrainfo = 1;
  778. } else if (strcmpstart(*s, "router ")==0) {
  779. have_extrainfo = 0;
  780. } else {
  781. /* skip junk. */
  782. const char *ei = tor_memstr(*s, eos-*s, "\nextra-info ");
  783. const char *ri = tor_memstr(*s, eos-*s, "\nrouter ");
  784. if (ri && (!ei || ri < ei)) {
  785. have_extrainfo = 0;
  786. *s = ri + 1;
  787. } else if (ei) {
  788. have_extrainfo = 1;
  789. *s = ei + 1;
  790. } else {
  791. break;
  792. }
  793. }
  794. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  795. if (end)
  796. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  797. if (end)
  798. end += strlen("\n-----END SIGNATURE-----\n");
  799. if (!end)
  800. break;
  801. elt = NULL;
  802. if (have_extrainfo && want_extrainfo) {
  803. routerlist_t *rl = router_get_routerlist();
  804. /* XXXX020 fix this cast to digestmap_t* */
  805. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  806. saved_location != SAVED_IN_CACHE,
  807. (digestmap_t*)rl->identity_map);
  808. if (extrainfo) {
  809. signed_desc = &extrainfo->cache_info;
  810. elt = extrainfo;
  811. }
  812. } else if (!have_extrainfo && !want_extrainfo) {
  813. router = router_parse_entry_from_string(*s, end,
  814. saved_location != SAVED_IN_CACHE);
  815. if (router) {
  816. signed_desc = &router->cache_info;
  817. elt = router;
  818. }
  819. }
  820. if (!elt) {
  821. *s = end;
  822. continue;
  823. }
  824. if (saved_location != SAVED_NOWHERE) {
  825. signed_desc->saved_location = saved_location;
  826. signed_desc->saved_offset = *s - start;
  827. }
  828. *s = end;
  829. smartlist_add(dest, elt);
  830. }
  831. return 0;
  832. }
  833. /* For debugging: define to count every descriptor digest we've seen so we
  834. * know if we need to try harder to avoid duplicate verifies. */
  835. #undef COUNT_DISTINCT_DIGESTS
  836. #ifdef COUNT_DISTINCT_DIGESTS
  837. static digestmap_t *verified_digests = NULL;
  838. #endif
  839. /** Log the total count of the number of distinct router digests we've ever
  840. * verified. When compared to the number of times we've verified routerdesc
  841. * signatures <i>in toto</i>, this will tell us if we're doing too much
  842. * multiple-verification. */
  843. void
  844. dump_distinct_digest_count(int severity)
  845. {
  846. #ifdef COUNT_DISTINCT_DIGESTS
  847. if (!verified_digests)
  848. verified_digests = digestmap_new();
  849. log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  850. digestmap_size(verified_digests));
  851. #else
  852. (void)severity; /* suppress "unused parameter" warning */
  853. #endif
  854. }
  855. /** Helper function: reads a single router entry from *<b>s</b> ...
  856. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  857. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  858. * s through end into the signed_descriptor_body of the resulting
  859. * routerinfo_t.
  860. */
  861. routerinfo_t *
  862. router_parse_entry_from_string(const char *s, const char *end,
  863. int cache_copy)
  864. {
  865. routerinfo_t *router = NULL;
  866. char digest[128];
  867. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  868. directory_token_t *tok;
  869. struct in_addr in;
  870. if (!end) {
  871. end = s + strlen(s);
  872. }
  873. /* point 'end' to a point immediately after the final newline. */
  874. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  875. --end;
  876. if (router_get_router_hash(s, digest) < 0) {
  877. log_warn(LD_DIR, "Couldn't compute router hash.");
  878. return NULL;
  879. }
  880. tokens = smartlist_create();
  881. if (tokenize_string(s,end,tokens,routerdesc_token_table)) {
  882. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  883. goto err;
  884. }
  885. if (smartlist_len(tokens) < 2) {
  886. log_warn(LD_DIR, "Impossibly short router descriptor.");
  887. goto err;
  888. }
  889. tok = smartlist_get(tokens,0);
  890. if (tok->tp != K_ROUTER) {
  891. log_warn(LD_DIR,"Entry does not start with \"router\"");
  892. goto err;
  893. }
  894. tor_assert(tok->n_args >= 5);
  895. router = tor_malloc_zero(sizeof(routerinfo_t));
  896. router->routerlist_index = -1;
  897. if (cache_copy)
  898. router->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  899. router->cache_info.signed_descriptor_len = end-s;
  900. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  901. router->nickname = tor_strdup(tok->args[0]);
  902. if (!is_legal_nickname(router->nickname)) {
  903. log_warn(LD_DIR,"Router nickname is invalid");
  904. goto err;
  905. }
  906. router->address = tor_strdup(tok->args[1]);
  907. if (!tor_inet_aton(router->address, &in)) {
  908. log_warn(LD_DIR,"Router address is not an IP.");
  909. goto err;
  910. }
  911. router->addr = ntohl(in.s_addr);
  912. router->or_port =
  913. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  914. router->dir_port =
  915. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  916. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  917. tor_assert(tok && tok->n_args >= 3);
  918. router->bandwidthrate =
  919. tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  920. if (!router->bandwidthrate) {
  921. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  922. escaped(tok->args[0]));
  923. goto err;
  924. }
  925. router->bandwidthburst =
  926. tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  927. router->bandwidthcapacity =
  928. tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  929. /* XXXX020 we don't error-check these values? -RD */
  930. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  931. tor_assert(tok->n_args >= 1);
  932. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  933. }
  934. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  935. tor_assert(tok->n_args >= 1);
  936. router->is_hibernating
  937. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  938. }
  939. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  940. tor_assert(tok);
  941. tor_assert(tok->n_args == 1);
  942. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  943. goto err;
  944. tok = find_first_by_keyword(tokens, K_ONION_KEY);
  945. tor_assert(tok);
  946. router->onion_pkey = tok->key;
  947. tok->key = NULL; /* Prevent free */
  948. tok = find_first_by_keyword(tokens, K_SIGNING_KEY);
  949. tor_assert(tok);
  950. router->identity_pkey = tok->key;
  951. tok->key = NULL; /* Prevent free */
  952. if (crypto_pk_get_digest(router->identity_pkey,
  953. router->cache_info.identity_digest)) {
  954. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  955. }
  956. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  957. /* If there's a fingerprint line, it must match the identity digest. */
  958. char d[DIGEST_LEN];
  959. tor_assert(tok->n_args == 1);
  960. tor_strstrip(tok->args[0], " ");
  961. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  962. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  963. escaped(tok->args[0]));
  964. goto err;
  965. }
  966. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  967. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  968. tok->args[0]);
  969. goto err;
  970. }
  971. }
  972. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  973. router->platform = tor_strdup(tok->args[0]);
  974. }
  975. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  976. router->contact_info = tor_strdup(tok->args[0]);
  977. }
  978. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  979. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  980. } else if (router->platform) {
  981. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  982. router->has_old_dnsworkers = 1;
  983. }
  984. exit_policy_tokens = find_all_exitpolicy(tokens);
  985. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  986. if (router_add_exit_policy(router,t)<0) {
  987. log_warn(LD_DIR,"Error in exit policy");
  988. goto err;
  989. });
  990. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  991. int i;
  992. router->declared_family = smartlist_create();
  993. for (i=0;i<tok->n_args;++i) {
  994. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  995. log_warn(LD_DIR, "Illegal nickname %s in family line",
  996. escaped(tok->args[i]));
  997. goto err;
  998. }
  999. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1000. }
  1001. }
  1002. if ((tok = find_first_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  1003. router->caches_extra_info = 1;
  1004. if ((tok = find_first_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1005. tor_assert(tok->n_args >= 1);
  1006. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1007. base16_decode(router->cache_info.extra_info_digest,
  1008. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1009. } else {
  1010. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1011. }
  1012. }
  1013. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1014. tor_assert(tok);
  1015. note_crypto_pk_op(VERIFY_RTR);
  1016. #ifdef COUNT_DISTINCT_DIGESTS
  1017. if (!verified_digests)
  1018. verified_digests = digestmap_new();
  1019. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1020. #endif
  1021. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1022. "router descriptor") < 0)
  1023. goto err;
  1024. if (!router->or_port) {
  1025. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1026. goto err;
  1027. }
  1028. if (!router->platform) {
  1029. router->platform = tor_strdup("<unknown>");
  1030. }
  1031. goto done;
  1032. err:
  1033. routerinfo_free(router);
  1034. router = NULL;
  1035. done:
  1036. if (tokens) {
  1037. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1038. smartlist_free(tokens);
  1039. }
  1040. if (exit_policy_tokens) {
  1041. smartlist_free(exit_policy_tokens);
  1042. }
  1043. return router;
  1044. }
  1045. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1046. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1047. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1048. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1049. * as a map from router identity to routerinfo_t when looking up signing keys.
  1050. */
  1051. extrainfo_t *
  1052. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1053. int cache_copy, digestmap_t *routermap)
  1054. {
  1055. extrainfo_t *extrainfo = NULL;
  1056. char digest[128];
  1057. smartlist_t *tokens = NULL;
  1058. directory_token_t *tok;
  1059. crypto_pk_env_t *key = NULL;
  1060. routerinfo_t *router;
  1061. if (!end) {
  1062. end = s + strlen(s);
  1063. }
  1064. /* point 'end' to a point immediately after the final newline. */
  1065. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1066. --end;
  1067. if (router_get_extrainfo_hash(s, digest) < 0) {
  1068. log_warn(LD_DIR, "Couldn't compute router hash.");
  1069. return NULL;
  1070. }
  1071. tokens = smartlist_create();
  1072. if (tokenize_string(s,end,tokens,extrainfo_token_table)) {
  1073. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1074. goto err;
  1075. }
  1076. if (smartlist_len(tokens) < 2) {
  1077. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1078. goto err;
  1079. }
  1080. tok = smartlist_get(tokens,0);
  1081. if (tok->tp != K_EXTRA_INFO) {
  1082. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1083. goto err;
  1084. }
  1085. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1086. extrainfo->cache_info.is_extrainfo = 1;
  1087. if (cache_copy)
  1088. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1089. extrainfo->cache_info.signed_descriptor_len = end-s;
  1090. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1091. tor_assert(tok->n_args >= 2);
  1092. if (!is_legal_nickname(tok->args[0])) {
  1093. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1094. goto err;
  1095. }
  1096. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1097. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1098. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1099. tok->args[1], HEX_DIGEST_LEN)) {
  1100. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1101. escaped(tok->args[1]));
  1102. goto err;
  1103. }
  1104. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1105. tor_assert(tok);
  1106. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1107. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1108. escaped(tok->args[0]));
  1109. goto err;
  1110. }
  1111. if (routermap &&
  1112. (router = digestmap_get(routermap,
  1113. extrainfo->cache_info.identity_digest))) {
  1114. key = router->identity_pkey;
  1115. }
  1116. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1117. tor_assert(tok);
  1118. if (strcmp(tok->object_type, "SIGNATURE") ||
  1119. tok->object_size < 128 || tok->object_size > 512) {
  1120. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1121. goto err;
  1122. }
  1123. if (key) {
  1124. note_crypto_pk_op(VERIFY_RTR);
  1125. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1126. goto err;
  1127. } else {
  1128. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1129. tok->object_size);
  1130. extrainfo->pending_sig_len = tok->object_size;
  1131. }
  1132. goto done;
  1133. err:
  1134. if (extrainfo)
  1135. extrainfo_free(extrainfo);
  1136. extrainfo = NULL;
  1137. done:
  1138. if (tokens) {
  1139. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1140. smartlist_free(tokens);
  1141. }
  1142. return extrainfo;
  1143. }
  1144. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1145. * the first character after the certificate. */
  1146. authority_cert_t *
  1147. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1148. {
  1149. authority_cert_t *cert = NULL;
  1150. smartlist_t *tokens = NULL;
  1151. char digest[DIGEST_LEN];
  1152. directory_token_t *tok;
  1153. char fp_declared[DIGEST_LEN];
  1154. char *eos;
  1155. size_t len;
  1156. trusted_dir_server_t *ds;
  1157. s = eat_whitespace(s);
  1158. eos = strstr(s, "\n-----END SIGNATURE-----\n");
  1159. if (! eos) {
  1160. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1161. return NULL;
  1162. }
  1163. eos = strchr(eos+2, '\n');
  1164. tor_assert(eos);
  1165. ++eos;
  1166. len = eos - s;
  1167. tokens = smartlist_create();
  1168. if (tokenize_string(s, eos, tokens, dir_key_certificate_table) < 0) {
  1169. log_warn(LD_DIR, "Error tokenizing key certificate");
  1170. goto err;
  1171. }
  1172. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1173. "\ndir-key-certification", '\n') < 0)
  1174. goto err;
  1175. tok = smartlist_get(tokens, 0);
  1176. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1177. log_warn(LD_DIR,
  1178. "Key certificate does not begin with a recognized version (3).");
  1179. goto err;
  1180. }
  1181. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1182. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1183. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1184. tor_assert(tok && tok->key);
  1185. cert->signing_key = tok->key;
  1186. tok->key = NULL;
  1187. tok = find_first_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1188. tor_assert(tok && tok->key);
  1189. cert->identity_key = tok->key;
  1190. tok->key = NULL;
  1191. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1192. tor_assert(tok && tok->n_args);
  1193. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1194. strlen(tok->args[0]))) {
  1195. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1196. escaped(tok->args[0]));
  1197. goto err;
  1198. }
  1199. if (crypto_pk_get_digest(cert->identity_key,
  1200. cert->cache_info.identity_digest))
  1201. goto err;
  1202. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1203. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1204. "fingerprint");
  1205. goto err;
  1206. }
  1207. tok = find_first_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1208. tor_assert(tok);
  1209. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1210. goto err;
  1211. }
  1212. tok = find_first_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1213. tor_assert(tok);
  1214. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1215. goto err;
  1216. }
  1217. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1218. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1219. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1220. goto err;
  1221. }
  1222. /* If we already have this cert, don't bother checking the signature. */
  1223. ds = trusteddirserver_get_by_v3_auth_digest(
  1224. cert->cache_info.identity_digest);
  1225. if (ds && ds->v3_cert &&
  1226. ds->v3_cert->cache_info.signed_descriptor_len == len &&
  1227. ds->v3_cert->cache_info.signed_descriptor_body &&
  1228. ! memcmp(s, ds->v3_cert->cache_info.signed_descriptor_body, len)) {
  1229. log_debug(LD_DIR, "We already checked the signature on this certificate;"
  1230. " no need to do so again.");
  1231. } else {
  1232. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1233. "key certificate")) {
  1234. goto err;
  1235. }
  1236. }
  1237. cert->cache_info.signed_descriptor_len = len;
  1238. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1239. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1240. cert->cache_info.signed_descriptor_body[len] = 0;
  1241. cert->cache_info.saved_location = SAVED_NOWHERE;
  1242. if (end_of_string) {
  1243. *end_of_string = eat_whitespace(eos);
  1244. }
  1245. return cert;
  1246. err:
  1247. authority_cert_free(cert);
  1248. return NULL;
  1249. }
  1250. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1251. * object (starting with "r " at the start of a line). If none is found,
  1252. * return the start of the next directory signature. If none is found, return
  1253. * the end of the string. */
  1254. static INLINE const char *
  1255. find_start_of_next_routerstatus(const char *s)
  1256. {
  1257. const char *eos = strstr(s, "\nr ");
  1258. if (!eos)
  1259. eos = strstr(s, "\ndirectory-signature");
  1260. if (eos)
  1261. return eos+1;
  1262. else
  1263. return s + strlen(s);
  1264. }
  1265. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1266. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1267. * object in the string, and advance *<b>s</b> to just after the end of the
  1268. * router status. Return NULL and advance *<b>s</b> on error. */
  1269. static routerstatus_t *
  1270. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens,
  1271. networkstatus_vote_t *vote,
  1272. vote_routerstatus_t *vote_rs)
  1273. {
  1274. const char *eos;
  1275. routerstatus_t *rs = NULL;
  1276. directory_token_t *tok;
  1277. char timebuf[ISO_TIME_LEN+1];
  1278. struct in_addr in;
  1279. tor_assert(tokens);
  1280. tor_assert(bool_eq(vote, vote_rs));
  1281. eos = find_start_of_next_routerstatus(*s);
  1282. if (tokenize_string(*s, eos, tokens, rtrstatus_token_table)) {
  1283. log_warn(LD_DIR, "Error tokenizing router status");
  1284. goto err;
  1285. }
  1286. if (smartlist_len(tokens) < 1) {
  1287. log_warn(LD_DIR, "Impossibly short router status");
  1288. goto err;
  1289. }
  1290. tok = find_first_by_keyword(tokens, K_R);
  1291. tor_assert(tok);
  1292. tor_assert(tok->n_args >= 8);
  1293. if (vote_rs) {
  1294. rs = &vote_rs->status;
  1295. } else {
  1296. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1297. }
  1298. if (!is_legal_nickname(tok->args[0])) {
  1299. log_warn(LD_DIR,
  1300. "Invalid nickname %s in router status; skipping.",
  1301. escaped(tok->args[0]));
  1302. goto err;
  1303. }
  1304. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1305. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1306. log_warn(LD_DIR, "Error decoding identity digest %s",
  1307. escaped(tok->args[1]));
  1308. goto err;
  1309. }
  1310. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1311. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1312. escaped(tok->args[2]));
  1313. goto err;
  1314. }
  1315. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1316. tok->args[3], tok->args[4]) < 0 ||
  1317. parse_iso_time(timebuf, &rs->published_on)<0) {
  1318. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1319. tok->args[3], tok->args[4]);
  1320. goto err;
  1321. }
  1322. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1323. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1324. escaped(tok->args[5]));
  1325. goto err;
  1326. }
  1327. rs->addr = ntohl(in.s_addr);
  1328. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1329. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1330. tok = find_first_by_keyword(tokens, K_S);
  1331. if (tok && vote) {
  1332. int i;
  1333. vote_rs->flags = 0;
  1334. for (i=0; i < tok->n_args; ++i) {
  1335. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1336. if (p >= 0) {
  1337. vote_rs->flags |= (1<<p);
  1338. } else {
  1339. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1340. escaped(tok->args[i]));
  1341. goto err;
  1342. }
  1343. }
  1344. } else if (tok) {
  1345. int i;
  1346. for (i=0; i < tok->n_args; ++i) {
  1347. if (!strcmp(tok->args[i], "Exit"))
  1348. rs->is_exit = 1;
  1349. else if (!strcmp(tok->args[i], "Stable"))
  1350. rs->is_stable = 1;
  1351. else if (!strcmp(tok->args[i], "Fast"))
  1352. rs->is_fast = 1;
  1353. else if (!strcmp(tok->args[i], "Running"))
  1354. rs->is_running = 1;
  1355. else if (!strcmp(tok->args[i], "Named"))
  1356. rs->is_named = 1;
  1357. else if (!strcmp(tok->args[i], "Valid"))
  1358. rs->is_valid = 1;
  1359. else if (!strcmp(tok->args[i], "V2Dir"))
  1360. rs->is_v2_dir = 1;
  1361. else if (!strcmp(tok->args[i], "Guard"))
  1362. rs->is_possible_guard = 1;
  1363. else if (!strcmp(tok->args[i], "BadExit"))
  1364. rs->is_bad_exit = 1;
  1365. else if (!strcmp(tok->args[i], "BadDirectory"))
  1366. rs->is_bad_directory = 1;
  1367. else if (!strcmp(tok->args[i], "Authority"))
  1368. rs->is_authority = 1;
  1369. }
  1370. }
  1371. if ((tok = find_first_by_keyword(tokens, K_V))) {
  1372. tor_assert(tok->n_args == 1);
  1373. rs->version_known = 1;
  1374. if (strcmpstart(tok->args[0], "Tor ")) {
  1375. rs->version_supports_begindir = 1;
  1376. rs->version_supports_extrainfo_upload = 1;
  1377. } else {
  1378. rs->version_supports_begindir =
  1379. tor_version_as_new_as(tok->args[0], "0.1.2.2-alpha");
  1380. rs->version_supports_begindir =
  1381. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1382. }
  1383. if (vote_rs) {
  1384. vote_rs->version = tok->args[0];
  1385. tok->args[0] = NULL; /* suppress free() */
  1386. }
  1387. }
  1388. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1389. rs->is_named = 0;
  1390. goto done;
  1391. err:
  1392. if (rs && !vote_rs)
  1393. routerstatus_free(rs);
  1394. rs = NULL;
  1395. done:
  1396. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1397. smartlist_clear(tokens);
  1398. *s = eos;
  1399. return rs;
  1400. }
  1401. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1402. static int
  1403. _compare_routerstatus_entries(const void **_a, const void **_b)
  1404. {
  1405. const routerstatus_t *a = *_a, *b = *_b;
  1406. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1407. }
  1408. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1409. static void
  1410. _free_duplicate_routerstatus_entry(void *e)
  1411. {
  1412. log_warn(LD_DIR,
  1413. "Network-status has two entries for the same router. "
  1414. "Dropping one.");
  1415. routerstatus_free(e);
  1416. }
  1417. /** Given a v2 network-status object in <b>s</b>, try to
  1418. * parse it and return the result. Return NULL on failure. Check the
  1419. * signature of the network status, but do not (yet) check the signing key for
  1420. * authority.
  1421. */
  1422. networkstatus_t *
  1423. networkstatus_parse_from_string(const char *s)
  1424. {
  1425. const char *eos;
  1426. smartlist_t *tokens = smartlist_create();
  1427. smartlist_t *footer_tokens = smartlist_create();
  1428. networkstatus_t *ns = NULL;
  1429. char ns_digest[DIGEST_LEN];
  1430. char tmp_digest[DIGEST_LEN];
  1431. struct in_addr in;
  1432. directory_token_t *tok;
  1433. int i;
  1434. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1435. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1436. goto err;
  1437. }
  1438. eos = find_start_of_next_routerstatus(s);
  1439. if (tokenize_string(s, eos, tokens, netstatus_token_table)) {
  1440. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1441. goto err;
  1442. }
  1443. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1444. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1445. tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1446. tor_assert(tok && tok->n_args >= 1);
  1447. if (strcmp(tok->args[0], "2")) {
  1448. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1449. "%s", escaped(tok->args[0]));
  1450. goto err;
  1451. }
  1452. tok = find_first_by_keyword(tokens, K_DIR_SOURCE);
  1453. tor_assert(tok);
  1454. tor_assert(tok->n_args >= 3);
  1455. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1456. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1457. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1458. escaped(tok->args[1]));
  1459. goto err;
  1460. }
  1461. ns->source_addr = ntohl(in.s_addr);
  1462. ns->source_dirport =
  1463. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1464. if (ns->source_dirport == 0) {
  1465. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1466. goto err;
  1467. }
  1468. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1469. tor_assert(tok);
  1470. tor_assert(tok->n_args);
  1471. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1472. strlen(tok->args[0]))) {
  1473. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1474. escaped(tok->args[0]));
  1475. goto err;
  1476. }
  1477. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1478. tor_assert(tok->n_args);
  1479. ns->contact = tok->args[0];
  1480. tok->args[0] = NULL;
  1481. }
  1482. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1483. tor_assert(tok && tok->key);
  1484. ns->signing_key = tok->key;
  1485. tok->key = NULL;
  1486. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1487. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1488. goto err;
  1489. }
  1490. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1491. log_warn(LD_DIR,
  1492. "network-status fingerprint did not match dir-signing-key");
  1493. goto err;
  1494. }
  1495. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1496. for (i=0; i < tok->n_args; ++i) {
  1497. if (!strcmp(tok->args[i], "Names"))
  1498. ns->binds_names = 1;
  1499. if (!strcmp(tok->args[i], "Versions"))
  1500. ns->recommends_versions = 1;
  1501. if (!strcmp(tok->args[i], "BadExits"))
  1502. ns->lists_bad_exits = 1;
  1503. if (!strcmp(tok->args[i], "BadDirectories"))
  1504. ns->lists_bad_directories = 1;
  1505. }
  1506. }
  1507. if (ns->recommends_versions) {
  1508. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1509. log_warn(LD_DIR, "Missing client-versions");
  1510. }
  1511. ns->client_versions = tok->args[0];
  1512. tok->args[0] = NULL;
  1513. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1514. tok->n_args<1) {
  1515. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1516. goto err;
  1517. }
  1518. ns->server_versions = tok->args[0];
  1519. tok->args[0] = NULL;
  1520. }
  1521. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1522. tor_assert(tok);
  1523. tor_assert(tok->n_args == 1);
  1524. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1525. goto err;
  1526. }
  1527. ns->entries = smartlist_create();
  1528. s = eos;
  1529. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1530. smartlist_clear(tokens);
  1531. while (!strcmpstart(s, "r ")) {
  1532. routerstatus_t *rs;
  1533. if ((rs = routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL)))
  1534. smartlist_add(ns->entries, rs);
  1535. }
  1536. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1537. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1538. _free_duplicate_routerstatus_entry);
  1539. if (tokenize_string(s, NULL, footer_tokens, dir_footer_token_table)) {
  1540. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1541. goto err;
  1542. }
  1543. if (smartlist_len(footer_tokens) < 1) {
  1544. log_warn(LD_DIR, "Too few items in network-status footer.");
  1545. goto err;
  1546. }
  1547. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1548. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1549. log_warn(LD_DIR,
  1550. "Expected network-status footer to end with a signature.");
  1551. goto err;
  1552. }
  1553. note_crypto_pk_op(VERIFY_DIR);
  1554. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1555. "network-status") < 0)
  1556. goto err;
  1557. goto done;
  1558. err:
  1559. if (ns)
  1560. networkstatus_free(ns);
  1561. ns = NULL;
  1562. done:
  1563. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1564. smartlist_free(tokens);
  1565. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1566. smartlist_free(footer_tokens);
  1567. return ns;
  1568. }
  1569. /** DOCDOC */
  1570. networkstatus_vote_t *
  1571. networkstatus_parse_vote_from_string(const char *s, int is_vote)
  1572. {
  1573. smartlist_t *tokens = smartlist_create();
  1574. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1575. networkstatus_voter_info_t *voter = NULL;
  1576. networkstatus_vote_t *ns = NULL;
  1577. char ns_digest[DIGEST_LEN];
  1578. const char *cert, *end_of_header, *end_of_footer;
  1579. directory_token_t *tok;
  1580. int ok;
  1581. struct in_addr in;
  1582. int i, inorder;
  1583. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  1584. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1585. goto err;
  1586. }
  1587. end_of_header = find_start_of_next_routerstatus(s);
  1588. if (tokenize_string(s, end_of_header, tokens,
  1589. is_vote ? networkstatus_vote_token_table :
  1590. networkstatus_consensus_token_table)) {
  1591. log_warn(LD_DIR, "Error tokenizing network-status vote header.");
  1592. goto err;
  1593. }
  1594. ns = tor_malloc_zero(sizeof(networkstatus_vote_t));
  1595. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1596. if (is_vote) {
  1597. const char *end_of_cert = NULL;
  1598. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  1599. goto err;
  1600. ++cert;
  1601. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  1602. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  1603. goto err;
  1604. }
  1605. tok = find_first_by_keyword(tokens, K_VOTE_STATUS);
  1606. tor_assert(tok);
  1607. tor_assert(tok->n_args);
  1608. if (!strcmp(tok->args[0], "vote")) {
  1609. ns->is_vote = 1;
  1610. } else if (!strcmp(tok->args[0], "consensus")) {
  1611. ns->is_vote = 0;
  1612. } else {
  1613. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  1614. escaped(tok->args[0]));
  1615. goto err;
  1616. }
  1617. if (!bool_eq(ns->is_vote, is_vote)) {
  1618. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  1619. goto err;
  1620. }
  1621. if (ns->is_vote) {
  1622. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1623. if (parse_iso_time(tok->args[0], &ns->published))
  1624. goto err;
  1625. }
  1626. tok = find_first_by_keyword(tokens, K_VALID_AFTER);
  1627. if (parse_iso_time(tok->args[0], &ns->valid_after))
  1628. goto err;
  1629. tok = find_first_by_keyword(tokens, K_FRESH_UNTIL);
  1630. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  1631. goto err;
  1632. tok = find_first_by_keyword(tokens, K_VALID_UNTIL);
  1633. if (parse_iso_time(tok->args[0], &ns->valid_until))
  1634. goto err;
  1635. tok = find_first_by_keyword(tokens, K_VOTING_DELAY);
  1636. tor_assert(tok->n_args >= 2);
  1637. ns->vote_seconds =
  1638. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  1639. if (!ok)
  1640. goto err;
  1641. ns->dist_seconds =
  1642. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  1643. if (!ok)
  1644. goto err;
  1645. if ((tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1646. ns->client_versions = tok->args[0];
  1647. tok->args[0] = NULL;
  1648. }
  1649. if ((tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS))) {
  1650. ns->server_versions = tok->args[0];
  1651. tok->args[0] = NULL;
  1652. }
  1653. tok = find_first_by_keyword(tokens, K_KNOWN_FLAGS);
  1654. ns->known_flags = smartlist_create();
  1655. inorder = 1;
  1656. for (i = 0; i < tok->n_args; ++i) {
  1657. smartlist_add(ns->known_flags, tok->args[i]);
  1658. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  1659. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  1660. inorder = 0;
  1661. }
  1662. }
  1663. tok->n_args = 0; /* suppress free of args members, but not of args itself. */
  1664. if (!inorder) {
  1665. log_warn(LD_DIR, "known-flags not in order");
  1666. goto err;
  1667. }
  1668. ns->voters = smartlist_create();
  1669. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  1670. {
  1671. tok = _tok;
  1672. if (tok->tp == K_DIR_SOURCE) {
  1673. tor_assert(tok->n_args >= 6);
  1674. if (voter)
  1675. smartlist_add(ns->voters, voter);
  1676. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  1677. if (is_vote)
  1678. memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
  1679. voter->nickname = tor_strdup(tok->args[0]);
  1680. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1681. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  1682. tok->args[1], HEX_DIGEST_LEN) < 0) {
  1683. log_warn(LD_DIR, "Error decoding identity digest %s in "
  1684. "network-status vote.", escaped(tok->args[1]));
  1685. goto err;
  1686. }
  1687. voter->address = tor_strdup(tok->args[2]);
  1688. if (!tor_inet_aton(tok->args[3], &in)) {
  1689. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  1690. escaped(tok->args[3]));
  1691. goto err;
  1692. }
  1693. voter->addr = ntohl(in.s_addr);
  1694. voter->dir_port = (uint64_t)
  1695. (int) tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  1696. if (!ok)
  1697. goto err;
  1698. voter->or_port = (uint64_t)
  1699. (int) tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  1700. if (!ok)
  1701. goto err;
  1702. } else if (tok->tp == K_CONTACT) {
  1703. if (!voter || voter->contact) {
  1704. log_warn(LD_DIR, "contact element is out of place.");
  1705. goto err;
  1706. }
  1707. voter->contact = tor_strdup(tok->args[0]);
  1708. } else if (tok->tp == K_VOTE_DIGEST) {
  1709. tor_assert(!is_vote);
  1710. tor_assert(tok->n_args >= 1);
  1711. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  1712. log_warn(LD_DIR, "vote-digest element is out of place.");
  1713. goto err;
  1714. }
  1715. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  1716. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  1717. tok->args[0], HEX_DIGEST_LEN) < 0) {
  1718. log_warn(LD_DIR, "Error decoding vote digest %s in "
  1719. "network-status consensus.", escaped(tok->args[1]));
  1720. goto err;
  1721. }
  1722. }
  1723. });
  1724. if (voter) {
  1725. smartlist_add(ns->voters, voter);
  1726. voter = NULL;
  1727. }
  1728. if (smartlist_len(ns->voters) == 0) {
  1729. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  1730. goto err;
  1731. } else if (is_vote && smartlist_len(ns->voters) != 1) {
  1732. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  1733. goto err;
  1734. }
  1735. /* Parse routerstatus lines. */
  1736. rs_tokens = smartlist_create();
  1737. s = end_of_header;
  1738. ns->routerstatus_list = smartlist_create();
  1739. while (!strcmpstart(s, "r ")) {
  1740. if (is_vote) {
  1741. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  1742. if (routerstatus_parse_entry_from_string(&s, tokens, ns, rs))
  1743. smartlist_add(ns->routerstatus_list, rs);
  1744. else {
  1745. tor_free(rs->version);
  1746. tor_free(rs);
  1747. }
  1748. } else {
  1749. routerstatus_t *rs;
  1750. if ((rs =routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL)))
  1751. smartlist_add(ns->routerstatus_list, rs);
  1752. }
  1753. }
  1754. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  1755. routerstatus_t *rs1, *rs2;
  1756. if (is_vote) {
  1757. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  1758. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  1759. rs1 = &a->status; rs2 = &b->status;
  1760. } else {
  1761. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  1762. rs2 = smartlist_get(ns->routerstatus_list, i);
  1763. }
  1764. if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
  1765. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  1766. "digest");
  1767. goto err;
  1768. }
  1769. }
  1770. /* Parse footer; check signature. */
  1771. footer_tokens = smartlist_create();
  1772. end_of_footer = s + strlen(s);
  1773. if (tokenize_string(s, end_of_footer, footer_tokens,
  1774. networkstatus_vote_footer_token_table)) {
  1775. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  1776. goto err;
  1777. }
  1778. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  1779. {
  1780. char declared_identity[DIGEST_LEN];
  1781. networkstatus_voter_info_t *v;
  1782. tok = _tok;
  1783. if (tok->tp != K_DIRECTORY_SIGNATURE)
  1784. continue;
  1785. tor_assert(tok->n_args >= 2);
  1786. if (!tok->object_type ||
  1787. strcmp(tok->object_type, "SIGNATURE") ||
  1788. tok->object_size < 128 || tok->object_size > 512) {
  1789. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  1790. goto err;
  1791. }
  1792. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  1793. base16_decode(declared_identity, sizeof(declared_identity),
  1794. tok->args[0], HEX_DIGEST_LEN) < 0) {
  1795. log_warn(LD_DIR, "Error decoding declared identity %s in "
  1796. "network-status vote.", escaped(tok->args[0]));
  1797. goto err;
  1798. }
  1799. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  1800. log_warn(LD_DIR, "ID on signature on network-status vote does not match"
  1801. "any declared directory source.");
  1802. goto err;
  1803. }
  1804. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1805. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  1806. tok->args[1], HEX_DIGEST_LEN) < 0) {
  1807. log_warn(LD_DIR, "Error decoding declared digest %s in "
  1808. "network-status vote.", escaped(tok->args[1]));
  1809. goto err;
  1810. }
  1811. if (is_vote &&
  1812. memcmp(declared_identity, ns->cert->cache_info.identity_digest,
  1813. DIGEST_LEN)) {
  1814. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  1815. "network-status vote.");
  1816. goto err;
  1817. /* XXXX020 also check cert against dir-source line. */
  1818. }
  1819. if (is_vote) {
  1820. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  1821. "network-status vote"))
  1822. goto err;
  1823. v->good_signature = 1;
  1824. } else {
  1825. v->pending_signature = tor_memdup(tok->object_body,
  1826. tok->object_size);
  1827. v->pending_signature_len = tok->object_size;
  1828. }
  1829. });
  1830. /* XXXX020 enforce: vote must have at least one signature. */
  1831. /* XXXX020 check dates for plausibility. ??? */
  1832. goto done;
  1833. err:
  1834. if (ns)
  1835. networkstatus_vote_free(ns);
  1836. ns = NULL;
  1837. done:
  1838. if (tokens) {
  1839. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1840. smartlist_free(tokens);
  1841. }
  1842. if (voter) {
  1843. tor_free(voter->nickname);
  1844. tor_free(voter->address);
  1845. tor_free(voter->contact);
  1846. tor_free(voter);
  1847. }
  1848. if (rs_tokens) {
  1849. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  1850. smartlist_free(rs_tokens);
  1851. }
  1852. if (footer_tokens) {
  1853. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1854. smartlist_free(footer_tokens);
  1855. }
  1856. return ns;
  1857. }
  1858. /** Parse the addr policy in the string <b>s</b> and return it. If
  1859. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1860. * ADDR_POLICY_REJECT) for items that specify no action.
  1861. */
  1862. addr_policy_t *
  1863. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1864. {
  1865. directory_token_t *tok = NULL;
  1866. const char *cp;
  1867. char *tmp;
  1868. addr_policy_t *r;
  1869. size_t len, idx;
  1870. const char *eos;
  1871. /* *s might not end with \n, so we need to extend it with one. */
  1872. len = strlen(s);
  1873. cp = tmp = tor_malloc(len+2);
  1874. for (idx = 0; idx < len; ++idx) {
  1875. tmp[idx] = TOR_TOLOWER(s[idx]);
  1876. }
  1877. tmp[len]='\n';
  1878. tmp[len+1]='\0';
  1879. while (TOR_ISSPACE(*cp))
  1880. ++cp;
  1881. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1882. char *new_str = tor_malloc(len+10);
  1883. tor_snprintf(new_str, len+10, "%s %s\n",
  1884. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1885. tor_free(tmp);
  1886. cp = tmp = new_str;
  1887. }
  1888. eos = cp + strlen(cp);
  1889. tok = get_next_token(&cp, eos, routerdesc_token_table);
  1890. if (tok->tp == _ERR) {
  1891. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1892. goto err;
  1893. }
  1894. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1895. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1896. goto err;
  1897. }
  1898. /* Now that we've gotten an addr policy, add it to the router. */
  1899. r = router_parse_addr_policy(tok);
  1900. goto done;
  1901. err:
  1902. r = NULL;
  1903. done:
  1904. tor_free(tmp);
  1905. token_free(tok);
  1906. return r;
  1907. }
  1908. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1909. * <b>router</b>. Return 0 on success, -1 on failure. */
  1910. static int
  1911. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1912. {
  1913. addr_policy_t *newe, **tmpe;
  1914. newe = router_parse_addr_policy(tok);
  1915. if (!newe)
  1916. return -1;
  1917. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1918. ;
  1919. *tmpe = newe;
  1920. return 0;
  1921. }
  1922. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1923. * a new exit_policy_t corresponding to the token. */
  1924. static addr_policy_t *
  1925. router_parse_addr_policy(directory_token_t *tok)
  1926. {
  1927. addr_policy_t *newe;
  1928. char *arg;
  1929. char buf[POLICY_BUF_LEN];
  1930. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1931. if (tok->n_args != 1)
  1932. return NULL;
  1933. arg = tok->args[0];
  1934. if (!strcmpstart(arg,"private"))
  1935. return router_parse_addr_policy_private(tok);
  1936. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1937. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1938. : ADDR_POLICY_ACCEPT;
  1939. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1940. &newe->prt_min, &newe->prt_max))
  1941. goto policy_read_failed;
  1942. if (policy_write_item(buf, sizeof(buf), newe) < 0)
  1943. goto policy_read_failed;
  1944. newe->string = tor_strdup(buf);
  1945. return newe;
  1946. policy_read_failed:
  1947. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1948. tor_free(newe);
  1949. return NULL;
  1950. }
  1951. /** Parse an exit policy line of the format "accept/reject private:...".
  1952. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1953. * router descriptors until earlier versions are obsolete.
  1954. */
  1955. static addr_policy_t *
  1956. router_parse_addr_policy_private(directory_token_t *tok)
  1957. {
  1958. static const char *private_nets[] = {
  1959. "0.0.0.0/8", "169.254.0.0/16",
  1960. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1961. char *arg;
  1962. addr_policy_t *result, **nextp;
  1963. int net;
  1964. uint16_t port_min, port_max;
  1965. arg = tok->args[0];
  1966. if (strcmpstart(arg, "private"))
  1967. return NULL;
  1968. arg += strlen("private");
  1969. arg = (char*) eat_whitespace(arg);
  1970. if (!arg || *arg != ':')
  1971. return NULL;
  1972. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1973. return NULL;
  1974. nextp = &result;
  1975. for (net = 0; private_nets[net]; ++net) {
  1976. size_t len;
  1977. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1978. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1979. : ADDR_POLICY_ACCEPT;
  1980. len = strlen(arg)+strlen(private_nets[net])+16;
  1981. (*nextp)->string = tor_malloc(len+1);
  1982. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1983. tok->tp == K_REJECT ? "reject" : "accept",
  1984. private_nets[net], arg);
  1985. if (parse_addr_and_port_range((*nextp)->string + 7,
  1986. &(*nextp)->addr, &(*nextp)->msk,
  1987. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1988. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1989. return NULL;
  1990. }
  1991. nextp = &(*nextp)->next;
  1992. }
  1993. return result;
  1994. }
  1995. /** Log and exit if <b>t</b> is malformed */
  1996. void
  1997. assert_addr_policy_ok(addr_policy_t *t)
  1998. {
  1999. addr_policy_t *t2;
  2000. while (t) {
  2001. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  2002. t->policy_type == ADDR_POLICY_ACCEPT);
  2003. tor_assert(t->prt_min <= t->prt_max);
  2004. t2 = router_parse_addr_policy_from_string(t->string, -1);
  2005. tor_assert(t2);
  2006. tor_assert(t2->policy_type == t->policy_type);
  2007. tor_assert(t2->addr == t->addr);
  2008. tor_assert(t2->msk == t->msk);
  2009. tor_assert(t2->prt_min == t->prt_min);
  2010. tor_assert(t2->prt_max == t->prt_max);
  2011. tor_assert(!strcmp(t2->string, t->string));
  2012. tor_assert(t2->next == NULL);
  2013. addr_policy_free(t2);
  2014. t = t->next;
  2015. }
  2016. }
  2017. /*
  2018. * Low-level tokenizer for router descriptors and directories.
  2019. */
  2020. /** Free all resources allocated for <b>tok</b> */
  2021. static void
  2022. token_free(directory_token_t *tok)
  2023. {
  2024. int i;
  2025. tor_assert(tok);
  2026. if (tok->args) {
  2027. for (i = 0; i < tok->n_args; ++i) {
  2028. tor_free(tok->args[i]);
  2029. }
  2030. tor_free(tok->args);
  2031. }
  2032. tor_free(tok->object_type);
  2033. tor_free(tok->object_body);
  2034. tor_free(tok->error);
  2035. if (tok->key)
  2036. crypto_free_pk_env(tok->key);
  2037. tor_free(tok);
  2038. }
  2039. #define RET_ERR(msg) \
  2040. STMT_BEGIN \
  2041. if (tok) token_free(tok); \
  2042. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  2043. tok->tp = _ERR; \
  2044. tok->error = tor_strdup(msg); \
  2045. goto done_tokenizing; \
  2046. STMT_END
  2047. static INLINE directory_token_t *
  2048. token_check_object(const char *kwd,
  2049. directory_token_t *tok, obj_syntax o_syn)
  2050. {
  2051. char ebuf[128];
  2052. switch (o_syn) {
  2053. case NO_OBJ:
  2054. if (tok->object_body) {
  2055. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2056. RET_ERR(ebuf);
  2057. }
  2058. if (tok->key) {
  2059. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2060. RET_ERR(ebuf);
  2061. }
  2062. break;
  2063. case NEED_OBJ:
  2064. if (!tok->object_body) {
  2065. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2066. RET_ERR(ebuf);
  2067. }
  2068. break;
  2069. case NEED_KEY_1024:
  2070. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2071. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2072. kwd, (int)crypto_pk_keysize(tok->key));
  2073. RET_ERR(ebuf);
  2074. }
  2075. /* fall through */
  2076. case NEED_KEY:
  2077. if (!tok->key) {
  2078. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2079. }
  2080. break;
  2081. case OBJ_OK:
  2082. break;
  2083. }
  2084. done_tokenizing:
  2085. return tok;
  2086. }
  2087. /** Helper function: read the next token from *s, advance *s to the end of the
  2088. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2089. * of tokens in <b>table</b>.
  2090. */
  2091. static directory_token_t *
  2092. get_next_token(const char **s, const char *eos, token_rule_t *table)
  2093. {
  2094. const char *next, *eol, *obstart;
  2095. int i, j, allocated, obname_len;
  2096. directory_token_t *tok;
  2097. obj_syntax o_syn = NO_OBJ;
  2098. char ebuf[128];
  2099. const char *kwd = "";
  2100. #define RET_ERR(msg) \
  2101. STMT_BEGIN \
  2102. if (tok) token_free(tok); \
  2103. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  2104. tok->tp = _ERR; \
  2105. tok->error = tor_strdup(msg); \
  2106. goto done_tokenizing; \
  2107. STMT_END
  2108. tok = tor_malloc_zero(sizeof(directory_token_t));
  2109. tok->tp = _ERR;
  2110. /* Set *s to first token, eol to end-of-line, next to after first token */
  2111. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  2112. eol = memchr(*s, '\n', eos-*s);
  2113. if (!eol)
  2114. eol = eos;
  2115. next = find_whitespace_eos(*s, eol);
  2116. if (!strcmp_len(*s, "opt", next-*s)) {
  2117. /* Skip past an "opt" at the start of the line. */
  2118. *s = eat_whitespace_eos_no_nl(next, eol);
  2119. next = find_whitespace_eos(*s, eol);
  2120. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  2121. RET_ERR("Unexpected EOF");
  2122. }
  2123. /* Search the table for the appropriate entry. (I tried a binary search
  2124. * instead, but it wasn't any faster.) */
  2125. for (i = 0; table[i].t ; ++i) {
  2126. if (!strcmp_len(*s, table[i].t, next-*s)) {
  2127. /* We've found the keyword. */
  2128. kwd = table[i].t;
  2129. tok->tp = table[i].v;
  2130. o_syn = table[i].os;
  2131. *s = eat_whitespace_eos_no_nl(next, eol);
  2132. next = find_whitespace_eos(*s, eol);
  2133. if (1 || *s < eol) { /* make sure there are arguments to store */
  2134. /* XXXX020 actually, we go ahead whether there are arguments or not,
  2135. * so that tok->args is always set if we want arguments. */
  2136. if (table[i].concat_args) {
  2137. /* The keyword takes the line as a single argument */
  2138. tok->args = tor_malloc(sizeof(char*));
  2139. tok->args[0] = tor_strndup(*s,eol-*s); /* Grab everything on line */
  2140. tok->n_args = 1;
  2141. } else {
  2142. /* This keyword takes multiple arguments. */
  2143. j = 0;
  2144. allocated = 16;
  2145. tok->args = tor_malloc(sizeof(char*)*allocated);
  2146. while (*s < eol) { /* While not at eol, store the next token */
  2147. if (j == allocated) {
  2148. allocated *= 2;
  2149. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  2150. }
  2151. tok->args[j++] = tor_strndup(*s, next-*s);
  2152. *s = eat_whitespace_eos_no_nl(next, eol); /* eat intra-line ws */
  2153. next = find_whitespace_eos(*s, eol); /* find end of token at *s */
  2154. }
  2155. tok->n_args = j;
  2156. }
  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) { /* No keyword matched; call it an "opt". */
  2169. tok->tp = K_OPT;
  2170. tok->args = tor_malloc(sizeof(char*));
  2171. tok->args[0] = tor_strndup(*s, eol-*s);
  2172. tok->n_args = 1;
  2173. o_syn = OBJ_OK;
  2174. }
  2175. /* Check whether there's an object present */
  2176. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  2177. eol = memchr(*s, '\n', eos-*s);
  2178. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  2179. goto check_object;
  2180. obstart = *s; /* Set obstart to start of object spec */
  2181. if (*s+11 >= eol-5 || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  2182. strcmp_len(eol-5, "-----", 5)) { /* nuls or invalid endings */
  2183. RET_ERR("Malformed object: bad begin line");
  2184. }
  2185. tok->object_type = tor_strndup(*s+11, eol-*s-16);
  2186. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  2187. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  2188. /* Go to the end of the object */
  2189. next = tor_memstr(*s, eos-*s, "-----END ");
  2190. if (!next) {
  2191. RET_ERR("Malformed object: missing object end line");
  2192. }
  2193. eol = memchr(next, '\n', eos-next);
  2194. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  2195. eol = eos;
  2196. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  2197. if (eol-next != 9+obname_len+5 ||
  2198. strcmp_len(next+9, tok->object_type, obname_len) ||
  2199. strcmp_len(eol-5, "-----", 5)) {
  2200. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  2201. tok->object_type);
  2202. ebuf[sizeof(ebuf)-1] = '\0';
  2203. RET_ERR(ebuf);
  2204. }
  2205. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a key... */
  2206. tok->key = crypto_new_pk_env();
  2207. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  2208. RET_ERR("Couldn't parse public key.");
  2209. } else { /* If it's something else, try to base64-decode it */
  2210. int r;
  2211. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  2212. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  2213. if (r<0)
  2214. RET_ERR("Malformed object: bad base64-encoded data");
  2215. tok->object_size = r;
  2216. }
  2217. *s = eol;
  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, end, 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_eos(*s, end);
  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. }