eventdns.c 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529
  1. /* The original version of this module was written by Adam Langley; for
  2. * a history of modifications, check out the subversion logs.
  3. *
  4. * When editing this module, try to keep it re-mergeable by Adam. Don't
  5. * reformat the whitespace, add Tor dependencies, or so on.
  6. *
  7. * TODO:
  8. * - Replace all externally visible magic numbers with #defined constants.
  9. * - Write documentation for APIs of all external functions.
  10. */
  11. /* Async DNS Library
  12. * Adam Langley <agl@imperialviolet.org>
  13. * Public Domain code
  14. *
  15. * This software is Public Domain. To view a copy of the public domain dedication,
  16. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  17. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  18. *
  19. * I ask and expect, but do not require, that all derivative works contain an
  20. * attribution similar to:
  21. * Parts developed by Adam Langley <agl@imperialviolet.org>
  22. *
  23. * You may wish to replace the word "Parts" with something else depending on
  24. * the amount of original code.
  25. *
  26. * (Derivative works does not include programs which link against, run or include
  27. * the source verbatim in their source distributions)
  28. *
  29. * Version: 0.1b
  30. */
  31. #include "eventdns_tor.h"
  32. #include <sys/types.h>
  33. /* #define NDEBUG */
  34. #ifndef DNS_USE_CPU_CLOCK_FOR_ID
  35. #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
  36. #ifndef DNS_USE_OPENSSL_FOR_ID
  37. #error Must configure at least one id generation method.
  38. #error Please see the documentation.
  39. #endif
  40. #endif
  41. #endif
  42. /* #define _POSIX_C_SOURCE 200507 */
  43. #define _GNU_SOURCE
  44. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  45. #ifdef DNS_USE_OPENSSL_FOR_ID
  46. #error Multiple id options selected
  47. #endif
  48. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  49. #error Multiple id options selected
  50. #endif
  51. #include <time.h>
  52. #endif
  53. #ifdef DNS_USE_OPENSSL_FOR_ID
  54. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  55. #error Multiple id options selected
  56. #endif
  57. #include <openssl/rand.h>
  58. #endif
  59. #include <string.h>
  60. #ifdef HAVE_FCNTL_H
  61. #include <fcntl.h>
  62. #endif
  63. #ifdef HAVE_SYS_TIME_H
  64. #include <sys/time.h>
  65. #endif
  66. #ifdef HAVE_STDINT_H
  67. #include <stdint.h>
  68. #endif
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <errno.h>
  72. #include <assert.h>
  73. #ifdef HAVE_UNISTD_H
  74. #include <unistd.h>
  75. #endif
  76. #ifdef HAVE_LIMITS_H
  77. #include <limits.h>
  78. #endif
  79. #include <sys/stat.h>
  80. #include <ctype.h>
  81. #include <stdio.h>
  82. #include <stdarg.h>
  83. #include "eventdns.h"
  84. #ifdef WIN32
  85. #include <windows.h>
  86. #include <winsock2.h>
  87. #include <iphlpapi.h>
  88. #else
  89. #include <sys/socket.h>
  90. #include <netinet/in.h>
  91. #include <arpa/inet.h>
  92. #endif
  93. #ifdef HAVE_NETINET_IN6_H
  94. #include <netinet/in6.h>
  95. #endif
  96. #ifdef WIN32
  97. typedef int socklen_t;
  98. #endif
  99. #define EVDNS_LOG_DEBUG 0
  100. #define EVDNS_LOG_WARN 1
  101. #ifndef HOST_NAME_MAX
  102. #define HOST_NAME_MAX 255
  103. #endif
  104. #ifndef NDEBUG
  105. #include <stdio.h>
  106. #endif
  107. /* for debugging possible memory leaks. */
  108. #define mm_malloc(x) tor_malloc(x)
  109. #define mm_realloc(x,y) tor_realloc((x),(y))
  110. #define mm_free(x) tor_free(x)
  111. #define mm_strdup(x) tor_strdup(x)
  112. #define _mm_free(x) _tor_free(x)
  113. #undef MIN
  114. #define MIN(a,b) ((a)<(b)?(a):(b))
  115. #if 0
  116. #ifdef __USE_ISOC99B
  117. /* libevent doesn't work without this */
  118. typedef uint8_t u_char;
  119. typedef unsigned int uint;
  120. #endif
  121. #endif
  122. #include <event.h>
  123. #define u64 uint64_t
  124. #define u32 uint32_t
  125. #define u16 uint16_t
  126. #define u8 uint8_t
  127. #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
  128. /* which we bother recording */
  129. #define TYPE_A EVDNS_TYPE_A
  130. #define TYPE_CNAME 5
  131. #define TYPE_PTR EVDNS_TYPE_PTR
  132. #define TYPE_AAAA EVDNS_TYPE_AAAA
  133. #define CLASS_INET EVDNS_CLASS_INET
  134. #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
  135. struct evdns_request {
  136. u8 *request; /* the dns packet data */
  137. unsigned int request_len;
  138. int reissue_count;
  139. int tx_count; /* the number of times that this packet has been sent */
  140. unsigned int request_type; /* TYPE_PTR or TYPE_A */
  141. void *user_pointer; /* the pointer given to us for this request */
  142. evdns_callback_type user_callback;
  143. struct nameserver *ns; /* the server which we last sent it */
  144. /* elements used by the searching code */
  145. int search_index;
  146. struct search_state *search_state;
  147. char *search_origname; /* needs to be mm_free()ed */
  148. int search_flags;
  149. /* these objects are kept in a circular list */
  150. struct evdns_request *next, *prev;
  151. u16 timeout_event_deleted; /**< Debugging: where was timeout_event
  152. * deleted? 0 for "it's added." */
  153. struct event timeout_event;
  154. u16 trans_id; /* the transaction id */
  155. char request_appended; /* true if the request pointer is data which follows this struct */
  156. char transmit_me; /* needs to be transmitted */
  157. };
  158. #ifndef HAVE_STRUCT_IN6_ADDR
  159. struct in6_addr {
  160. u8 s6_addr[16];
  161. };
  162. #endif
  163. struct reply {
  164. unsigned int type;
  165. unsigned int have_answer;
  166. union {
  167. struct {
  168. u32 addrcount;
  169. u32 addresses[MAX_ADDRS];
  170. } a;
  171. struct {
  172. u32 addrcount;
  173. struct in6_addr addresses[MAX_ADDRS];
  174. } aaaa;
  175. struct {
  176. char name[HOST_NAME_MAX];
  177. } ptr;
  178. } data;
  179. };
  180. struct nameserver {
  181. int socket; /* a connected UDP socket */
  182. struct sockaddr_storage address;
  183. int failed_times; /* number of times which we have given this server a chance */
  184. int timedout; /* number of times in a row a request has timed out */
  185. struct event event;
  186. /* these objects are kept in a circular list */
  187. struct nameserver *next, *prev;
  188. u16 timeout_event_deleted; /**< Debugging: where was timeout_event
  189. * deleted? 0 for "it's added." */
  190. struct event timeout_event; /* used to keep the timeout for */
  191. /* when we next probe this server. */
  192. /* Valid if state == 0 */
  193. char state; /* zero if we think that this server is down */
  194. char choked; /* true if we have an EAGAIN from this server's socket */
  195. char write_waiting; /* true if we are waiting for EV_WRITE events */
  196. };
  197. static struct evdns_request *req_head = NULL, *req_waiting_head = NULL;
  198. static struct nameserver *server_head = NULL;
  199. /* Represents a local port where we're listening for DNS requests. Right now, */
  200. /* only UDP is supported. */
  201. struct evdns_server_port {
  202. int socket; /* socket we use to read queries and write replies. */
  203. int refcnt; /* reference count. */
  204. char choked; /* Are we currently blocked from writing? */
  205. char closing; /* Are we trying to close this port, pending writes? */
  206. evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
  207. void *user_data; /* Opaque pointer passed to user_callback */
  208. struct event event; /* Read/write event */
  209. /* circular list of replies that we want to write. */
  210. struct server_request *pending_replies;
  211. };
  212. /* Represents part of a reply being built. (That is, a single RR.) */
  213. struct server_reply_item {
  214. struct server_reply_item *next; /* next item in sequence. */
  215. char *name; /* name part of the RR */
  216. u16 type : 16; /* The RR type */
  217. u16 class : 16; /* The RR class (usually CLASS_INET) */
  218. u32 ttl; /* The RR TTL */
  219. char is_name; /* True iff data is a label */
  220. u16 datalen; /* Length of data; -1 if data is a label */
  221. void *data; /* The contents of the RR */
  222. };
  223. /* Represents a request that we've received as a DNS server, and holds */
  224. /* the components of the reply as we're constructing it. */
  225. struct server_request {
  226. /* Pointers to the next and previous entries on the list of replies */
  227. /* that we're waiting to write. Only set if we have tried to respond */
  228. /* and gotten EAGAIN. */
  229. struct server_request *next_pending;
  230. struct server_request *prev_pending;
  231. u16 trans_id; /* Transaction id. */
  232. struct evdns_server_port *port; /* Which port received this request on? */
  233. struct sockaddr_storage addr; /* Where to send the response */
  234. socklen_t addrlen; /* length of addr */
  235. int n_answer; /* how many answer RRs have been set? */
  236. int n_authority; /* how many authority RRs have been set? */
  237. int n_additional; /* how many additional RRs have been set? */
  238. struct server_reply_item *answer; /* linked list of answer RRs */
  239. struct server_reply_item *authority; /* linked list of authority RRs */
  240. struct server_reply_item *additional; /* linked list of additional RRs */
  241. /* Constructed response. Only set once we're ready to send a reply. */
  242. /* Once this is set, the RR fields are cleared, and no more should be set. */
  243. char *response;
  244. size_t response_len;
  245. /* Caller-visible fields: flags, questions. */
  246. struct evdns_server_request base;
  247. };
  248. /* helper macro */
  249. #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
  250. /* Given a pointer to an evdns_server_request, get the corresponding */
  251. /* server_request. */
  252. #define TO_SERVER_REQUEST(base_ptr) \
  253. ((struct server_request*) \
  254. (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
  255. /* The number of good nameservers that we have */
  256. static int global_good_nameservers = 0;
  257. /* inflight requests are contained in the req_head list */
  258. /* and are actually going out across the network */
  259. static int global_requests_inflight = 0;
  260. /* requests which aren't inflight are in the waiting list */
  261. /* and are counted here */
  262. static int global_requests_waiting = 0;
  263. static int global_max_requests_inflight = 64;
  264. static struct timeval global_timeout = {5, 0}; /* 5 seconds */
  265. static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
  266. static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
  267. /* number of timeouts in a row before we consider this server to be down */
  268. static int global_max_nameserver_timeout = 3;
  269. /* true iff we should use the 0x20 hack. */
  270. static int global_randomize_case = 1;
  271. /* These are the timeout values for nameservers. If we find a nameserver is down */
  272. /* we try to probe it at intervals as given below. Values are in seconds. */
  273. static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
  274. static const int global_nameserver_timeouts_length = (int)(sizeof(global_nameserver_timeouts)/sizeof(struct timeval));
  275. static struct nameserver *nameserver_pick(void);
  276. static void evdns_request_insert(struct evdns_request *req, struct evdns_request **head);
  277. static void nameserver_ready_callback(int fd, short events, void *arg);
  278. static int evdns_transmit(void);
  279. static int evdns_request_transmit(struct evdns_request *req);
  280. static void nameserver_send_probe(struct nameserver *const ns);
  281. static void search_request_finished(struct evdns_request *const);
  282. static int search_try_next(struct evdns_request *const req);
  283. static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
  284. static void evdns_requests_pump_waiting_queue(void);
  285. static u16 transaction_id_pick(void);
  286. static struct evdns_request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
  287. static void request_submit(struct evdns_request *req);
  288. static int server_request_free(struct server_request *req);
  289. static void server_request_free_answers(struct server_request *req);
  290. static void server_port_free(struct evdns_server_port *port);
  291. static void server_port_ready_callback(int fd, short events, void *arg);
  292. static int strtoint(const char *const str);
  293. #ifdef WIN32
  294. static int
  295. last_error(int sock)
  296. {
  297. int optval, optvallen=sizeof(optval);
  298. int err = WSAGetLastError();
  299. if (err == WSAEWOULDBLOCK && sock >= 0) {
  300. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
  301. &optvallen))
  302. return err;
  303. if (optval)
  304. return optval;
  305. }
  306. return err;
  307. }
  308. static int
  309. error_is_eagain(int err)
  310. {
  311. return err == EAGAIN || err == WSAEWOULDBLOCK;
  312. }
  313. #define inet_aton(c, addr) tor_inet_aton((c), (addr))
  314. #define CLOSE_SOCKET(x) closesocket(x)
  315. #else
  316. #define last_error(sock) (errno)
  317. #define error_is_eagain(err) ((err) == EAGAIN)
  318. #define CLOSE_SOCKET(x) close(x)
  319. #endif
  320. #define ISSPACE(c) TOR_ISSPACE(c)
  321. #define ISDIGIT(c) TOR_ISDIGIT(c)
  322. #define ISALPHA(c) TOR_ISALPHA(c)
  323. #define TOLOWER(c) TOR_TOLOWER(c)
  324. #define TOUPPER(c) TOR_TOUPPER(c)
  325. #ifndef NDEBUG
  326. static const char *
  327. debug_ntoa(u32 address)
  328. {
  329. static char buf[32];
  330. u32 a = ntohl(address);
  331. snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
  332. (int)(u8)((a>>24)&0xff),
  333. (int)(u8)((a>>16)&0xff),
  334. (int)(u8)((a>>8 )&0xff),
  335. (int)(u8)((a )&0xff));
  336. return buf;
  337. }
  338. static const char *
  339. debug_ntop(const struct sockaddr *sa)
  340. {
  341. if (sa->sa_family == AF_INET) {
  342. struct sockaddr_in *sin = (struct sockaddr_in *) sa;
  343. return debug_ntoa(sin->sin_addr.s_addr);
  344. }
  345. if (sa->sa_family == AF_INET6) {
  346. /* Tor-specific. In libevent, add more check code. */
  347. static char buf[128];
  348. struct sockaddr_in6 *sin = (struct sockaddr_in6 *) sa;
  349. tor_inet_ntop(AF_INET6, &sin->sin6_addr, buf, sizeof(buf));
  350. return buf;
  351. }
  352. return "<unknown>";
  353. }
  354. #endif
  355. static evdns_debug_log_fn_type evdns_log_fn = NULL;
  356. void
  357. evdns_set_log_fn(evdns_debug_log_fn_type fn)
  358. {
  359. evdns_log_fn = fn;
  360. }
  361. #ifdef __GNUC__
  362. #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
  363. #else
  364. #define EVDNS_LOG_CHECK
  365. #endif
  366. static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
  367. static void
  368. _evdns_log(int warn, const char *fmt, ...)
  369. {
  370. va_list args;
  371. static char buf[512];
  372. if (!evdns_log_fn)
  373. return;
  374. va_start(args,fmt);
  375. #ifdef WIN32
  376. _vsnprintf(buf, sizeof(buf), fmt, args);
  377. #else
  378. vsnprintf(buf, sizeof(buf), fmt, args);
  379. #endif
  380. buf[sizeof(buf)-1] = '\0';
  381. evdns_log_fn(warn, buf);
  382. va_end(args);
  383. }
  384. #define log _evdns_log
  385. static int
  386. sockaddr_eq(const struct sockaddr *sa1, const struct sockaddr *sa2,
  387. int include_port)
  388. {
  389. if (sa1->sa_family != sa2->sa_family)
  390. return 0;
  391. if (sa1->sa_family == AF_INET) {
  392. const struct sockaddr_in *sin1, *sin2;
  393. sin1 = (const struct sockaddr_in *)sa1;
  394. sin2 = (const struct sockaddr_in *)sa2;
  395. if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr)
  396. return 0;
  397. else if (include_port && sin1->sin_port != sin2->sin_port)
  398. return 0;
  399. else
  400. return 1;
  401. }
  402. #ifdef AF_INET6
  403. if (sa1->sa_family == AF_INET6) {
  404. const struct sockaddr_in6 *sin1, *sin2;
  405. sin1 = (const struct sockaddr_in6 *)sa1;
  406. sin2 = (const struct sockaddr_in6 *)sa2;
  407. if (memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))
  408. return 0;
  409. else if (include_port && sin1->sin6_port != sin2->sin6_port)
  410. return 0;
  411. else
  412. return 1;
  413. }
  414. #endif
  415. return 1;
  416. }
  417. /* for debugging bug 929. XXXX022 */
  418. static int
  419. _add_timeout_event(u16 *lineno, struct event *ev, struct timeval *to)
  420. {
  421. *lineno = 0;
  422. return evtimer_add(ev, to);
  423. }
  424. #define add_timeout_event(s, to) \
  425. (_add_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, (to)))
  426. /* for debugging bug 929. XXXX022 */
  427. static int
  428. _del_timeout_event(u16 *lineno, struct event *ev, int line)
  429. {
  430. if (*lineno) {
  431. log(EVDNS_LOG_DEBUG,
  432. "Duplicate timeout event_del from line %d: first call "
  433. "was at %d.", line, (int)*lineno);
  434. return 0;
  435. } else {
  436. *lineno = (u16)line;
  437. return event_del(ev);
  438. }
  439. }
  440. #define del_timeout_event(s) \
  441. (_del_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, \
  442. __LINE__))
  443. /* For debugging bug 929/957. XXXX022 */
  444. static int
  445. _del_timeout_event_if_set(u16 *lineno, struct event *ev, int line)
  446. {
  447. if (*lineno == 0) {
  448. log(EVDNS_LOG_DEBUG,
  449. "Event that I thought was non-added as of line %d "
  450. "was actually added on line %d",
  451. line, (int)*lineno);
  452. *lineno = line;
  453. return event_del(ev);
  454. }
  455. return 0;
  456. }
  457. #define del_timeout_event_if_set(s) \
  458. _del_timeout_event_if_set(&(s)->timeout_event_deleted, \
  459. &(s)->timeout_event, \
  460. __LINE__)
  461. /* This walks the list of inflight requests to find the */
  462. /* one with a matching transaction id. Returns NULL on */
  463. /* failure */
  464. static struct evdns_request *
  465. request_find_from_trans_id(u16 trans_id) {
  466. struct evdns_request *req = req_head, *const started_at = req_head;
  467. if (req) {
  468. do {
  469. if (req->trans_id == trans_id) return req;
  470. req = req->next;
  471. } while (req != started_at);
  472. }
  473. return NULL;
  474. }
  475. /* a libevent callback function which is called when a nameserver */
  476. /* has gone down and we want to test if it has came back to life yet */
  477. static void
  478. nameserver_prod_callback(int fd, short events, void *arg) {
  479. struct nameserver *const ns = (struct nameserver *) arg;
  480. (void)fd;
  481. (void)events;
  482. nameserver_send_probe(ns);
  483. }
  484. /* a libevent callback which is called when a nameserver probe (to see if */
  485. /* it has come back to life) times out. We increment the count of failed_times */
  486. /* and wait longer to send the next probe packet. */
  487. static void
  488. nameserver_probe_failed(struct nameserver *const ns) {
  489. const struct timeval * timeout;
  490. del_timeout_event(ns);
  491. CLEAR(&ns->timeout_event);
  492. if (ns->state == 1) {
  493. /* This can happen if the nameserver acts in a way which makes us mark */
  494. /* it as bad and then starts sending good replies. */
  495. return;
  496. }
  497. timeout =
  498. &global_nameserver_timeouts[MIN(ns->failed_times,
  499. global_nameserver_timeouts_length - 1)];
  500. ns->failed_times++;
  501. del_timeout_event_if_set(ns);
  502. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  503. if (add_timeout_event(ns, (struct timeval *) timeout) < 0) {
  504. log(EVDNS_LOG_WARN,
  505. "Error from libevent when adding timer event for %s",
  506. debug_ntop((struct sockaddr *)&ns->address));
  507. /* ???? Do more? */
  508. }
  509. }
  510. /* called when a nameserver has been deemed to have failed. For example, too */
  511. /* many packets have timed out etc */
  512. static void
  513. nameserver_failed(struct nameserver *const ns, const char *msg) {
  514. struct evdns_request *req, *started_at;
  515. /* if this nameserver has already been marked as failed */
  516. /* then don't do anything */
  517. if (!ns->state) return;
  518. log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
  519. debug_ntop((struct sockaddr *)&ns->address), msg);
  520. global_good_nameservers--;
  521. assert(global_good_nameservers >= 0);
  522. if (global_good_nameservers == 0) {
  523. log(EVDNS_LOG_WARN, "All nameservers have failed");
  524. }
  525. ns->state = 0;
  526. ns->failed_times = 1;
  527. del_timeout_event_if_set(ns);
  528. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  529. if (add_timeout_event(ns, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
  530. log(EVDNS_LOG_WARN,
  531. "Error from libevent when adding timer event for %s",
  532. debug_ntop((struct sockaddr *)&ns->address));
  533. /* ???? Do more? */
  534. }
  535. /* walk the list of inflight requests to see if any can be reassigned to */
  536. /* a different server. Requests in the waiting queue don't have a */
  537. /* nameserver assigned yet */
  538. /* if we don't have *any* good nameservers then there's no point */
  539. /* trying to reassign requests to one */
  540. if (!global_good_nameservers) return;
  541. req = req_head;
  542. started_at = req_head;
  543. if (req) {
  544. do {
  545. if (req->tx_count == 0 && req->ns == ns) {
  546. /* still waiting to go out, can be moved */
  547. /* to another server */
  548. req->ns = nameserver_pick();
  549. }
  550. req = req->next;
  551. } while (req != started_at);
  552. }
  553. }
  554. static void
  555. nameserver_up(struct nameserver *const ns) {
  556. if (ns->state) return;
  557. log(EVDNS_LOG_WARN, "Nameserver %s is back up",
  558. debug_ntop((struct sockaddr *)&ns->address));
  559. del_timeout_event(ns);
  560. CLEAR(&ns->timeout_event);
  561. ns->state = 1;
  562. ns->failed_times = 0;
  563. ns->timedout = 0;
  564. global_good_nameservers++;
  565. }
  566. static void
  567. request_trans_id_set(struct evdns_request *const req, const u16 trans_id) {
  568. req->trans_id = trans_id;
  569. *((u16 *) req->request) = htons(trans_id);
  570. }
  571. /* Called to remove a request from a list and dealloc it. */
  572. /* head is a pointer to the head of the list it should be */
  573. /* removed from or NULL if the request isn't in a list. */
  574. static void
  575. request_finished(struct evdns_request *const req, struct evdns_request **head) {
  576. if (head) {
  577. if (req->next == req) {
  578. /* only item in the list */
  579. *head = NULL;
  580. } else {
  581. req->next->prev = req->prev;
  582. req->prev->next = req->next;
  583. if (*head == req) *head = req->next;
  584. }
  585. }
  586. log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
  587. (unsigned long) req);
  588. del_timeout_event(req);
  589. CLEAR(&req->timeout_event);
  590. search_request_finished(req);
  591. global_requests_inflight--;
  592. if (!req->request_appended) {
  593. /* need to free the request data on it's own */
  594. mm_free(req->request);
  595. } else {
  596. /* the request data is appended onto the header */
  597. /* so everything gets mm_free()ed when we: */
  598. }
  599. CLEAR(req);
  600. _mm_free(req);
  601. evdns_requests_pump_waiting_queue();
  602. }
  603. /* This is called when a server returns a funny error code. */
  604. /* We try the request again with another server. */
  605. /* */
  606. /* return: */
  607. /* 0 ok */
  608. /* 1 failed/reissue is pointless */
  609. static int
  610. request_reissue(struct evdns_request *req) {
  611. const struct nameserver *const last_ns = req->ns;
  612. /* the last nameserver should have been marked as failing */
  613. /* by the caller of this function, therefore pick will try */
  614. /* not to return it */
  615. req->ns = nameserver_pick();
  616. if (req->ns == last_ns) {
  617. /* ... but pick did return it */
  618. /* not a lot of point in trying again with the */
  619. /* same server */
  620. return 1;
  621. }
  622. req->reissue_count++;
  623. req->tx_count = 0;
  624. req->transmit_me = 1;
  625. return 0;
  626. }
  627. /* this function looks for space on the inflight queue and promotes */
  628. /* requests from the waiting queue if it can. */
  629. static void
  630. evdns_requests_pump_waiting_queue(void) {
  631. while (global_requests_inflight < global_max_requests_inflight &&
  632. global_requests_waiting) {
  633. struct evdns_request *req;
  634. /* move a request from the waiting queue to the inflight queue */
  635. assert(req_waiting_head);
  636. if (req_waiting_head->next == req_waiting_head) {
  637. /* only one item in the queue */
  638. req = req_waiting_head;
  639. req_waiting_head = NULL;
  640. } else {
  641. req = req_waiting_head;
  642. req->next->prev = req->prev;
  643. req->prev->next = req->next;
  644. req_waiting_head = req->next;
  645. }
  646. global_requests_waiting--;
  647. global_requests_inflight++;
  648. req->ns = nameserver_pick();
  649. request_trans_id_set(req, transaction_id_pick());
  650. evdns_request_insert(req, &req_head);
  651. evdns_request_transmit(req);
  652. evdns_transmit();
  653. }
  654. }
  655. static void
  656. reply_callback(struct evdns_request *const req, u32 ttl, u32 err, struct reply *reply) {
  657. switch (req->request_type) {
  658. case TYPE_A:
  659. if (reply)
  660. req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
  661. reply->data.a.addrcount, ttl,
  662. reply->data.a.addresses,
  663. req->user_pointer);
  664. else
  665. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  666. return;
  667. case TYPE_PTR:
  668. if (reply) {
  669. char *name = reply->data.ptr.name;
  670. req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
  671. &name, req->user_pointer);
  672. } else {
  673. req->user_callback(err, 0, 0, 0, NULL,
  674. req->user_pointer);
  675. }
  676. return;
  677. case TYPE_AAAA:
  678. if (reply)
  679. req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
  680. reply->data.aaaa.addrcount, ttl,
  681. reply->data.aaaa.addresses,
  682. req->user_pointer);
  683. else
  684. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  685. return;
  686. }
  687. assert(0);
  688. }
  689. /* this processes a parsed reply packet */
  690. static void
  691. reply_handle(struct evdns_request *const req, u16 flags, u32 ttl, struct reply *reply) {
  692. int error;
  693. static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
  694. if (flags & 0x020f || !reply || !reply->have_answer) {
  695. /* there was an error */
  696. if (flags & 0x0200) {
  697. error = DNS_ERR_TRUNCATED;
  698. } else {
  699. u16 error_code = (flags & 0x000f) - 1;
  700. if (error_code > 4) {
  701. error = DNS_ERR_UNKNOWN;
  702. } else {
  703. error = error_codes[error_code];
  704. }
  705. }
  706. switch(error) {
  707. case DNS_ERR_NOTIMPL:
  708. case DNS_ERR_REFUSED:
  709. /* we regard these errors as marking a bad nameserver */
  710. if (req->reissue_count < global_max_reissues) {
  711. char msg[64];
  712. snprintf(msg, sizeof(msg), "Bad response %d (%s)",
  713. error, evdns_err_to_string(error));
  714. nameserver_failed(req->ns, msg);
  715. if (!request_reissue(req)) return;
  716. }
  717. break;
  718. case DNS_ERR_SERVERFAILED:
  719. /* rcode 2 (servfailed) sometimes means "we are broken" and
  720. * sometimes (with some binds) means "that request was very
  721. * confusing." Treat this as a timeout, not a failure.
  722. */
  723. /*XXXX refactor the parts of */
  724. log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
  725. "will allow the request to time out.",
  726. debug_ntop((struct sockaddr *)&req->ns->address));
  727. break;
  728. default:
  729. /* we got a good reply from the nameserver */
  730. nameserver_up(req->ns);
  731. }
  732. if (req->search_state && req->request_type != TYPE_PTR) {
  733. /* if we have a list of domains to search in, try the next one */
  734. if (!search_try_next(req)) {
  735. /* a new request was issued so this request is finished and */
  736. /* the user callback will be made when that request (or a */
  737. /* child of it) finishes. */
  738. request_finished(req, &req_head);
  739. return;
  740. }
  741. }
  742. /* all else failed. Pass the failure up */
  743. reply_callback(req, 0, error, NULL);
  744. request_finished(req, &req_head);
  745. } else {
  746. /* all ok, tell the user */
  747. reply_callback(req, ttl, 0, reply);
  748. nameserver_up(req->ns);
  749. request_finished(req, &req_head);
  750. }
  751. }
  752. static INLINE int
  753. name_parse(u8 *packet, int length, int *idx, char *name_out, size_t name_out_len) {
  754. int name_end = -1;
  755. int j = *idx;
  756. int ptr_count = 0;
  757. #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
  758. #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
  759. #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
  760. char *cp = name_out;
  761. const char *const end = name_out + name_out_len;
  762. /* Normally, names are a series of length prefixed strings terminated */
  763. /* with a length of 0 (the lengths are u8's < 63). */
  764. /* However, the length can start with a pair of 1 bits and that */
  765. /* means that the next 14 bits are a pointer within the current */
  766. /* packet. */
  767. for(;;) {
  768. u8 label_len;
  769. if (j >= length) return -1;
  770. GET8(label_len);
  771. if (!label_len) break;
  772. if (label_len & 0xc0) {
  773. u8 ptr_low;
  774. GET8(ptr_low);
  775. if (name_end < 0) name_end = j;
  776. j = (((int)label_len & 0x3f) << 8) + ptr_low;
  777. /* Make sure that the target offset is in-bounds. */
  778. if (j < 0 || j >= length) return -1;
  779. /* If we've jumped more times than there are characters in the
  780. * message, we must have a loop. */
  781. if (++ptr_count > length) return -1;
  782. continue;
  783. }
  784. if (label_len > 63) return -1;
  785. if (cp != name_out) {
  786. if (cp + 1 >= end) return -1;
  787. *cp++ = '.';
  788. }
  789. if (cp + label_len >= end) return -1;
  790. memcpy(cp, packet + j, label_len);
  791. cp += label_len;
  792. j += label_len;
  793. }
  794. if (cp >= end) return -1;
  795. *cp = '\0';
  796. if (name_end < 0)
  797. *idx = j;
  798. else
  799. *idx = name_end;
  800. return 0;
  801. err:
  802. return -1;
  803. }
  804. /* parses a raw reply from a nameserver. */
  805. static int
  806. reply_parse(u8 *packet, int length) {
  807. int j = 0; /* index into packet */
  808. int k;
  809. u16 _t; /* used by the macros */
  810. u32 _t32; /* used by the macros */
  811. char tmp_name[256], cmp_name[256]; /* used by the macros */
  812. u16 trans_id, questions, answers, authority, additional, datalength;
  813. u16 flags = 0;
  814. u32 ttl, ttl_r = 0xffffffff;
  815. struct reply reply;
  816. struct evdns_request *req = NULL;
  817. unsigned int i;
  818. int name_matches = 0;
  819. GET16(trans_id);
  820. GET16(flags);
  821. GET16(questions);
  822. GET16(answers);
  823. GET16(authority);
  824. GET16(additional);
  825. (void) authority; /* suppress "unused variable" warnings. */
  826. (void) additional; /* suppress "unused variable" warnings. */
  827. req = request_find_from_trans_id(trans_id);
  828. /* if no request, can't do anything. */
  829. if (!req) return -1;
  830. memset(&reply, 0, sizeof(reply));
  831. /* If it's not an answer, it doesn't go with any of our requests. */
  832. if (!(flags & 0x8000)) return -1; /* must be an answer */
  833. if (flags & 0x020f) {
  834. /* there was an error */
  835. goto err;
  836. }
  837. /* if (!answers) return; */ /* must have an answer of some form */
  838. /* This macro skips a name in the DNS reply. */
  839. #define GET_NAME \
  840. do { tmp_name[0] = '\0'; \
  841. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
  842. goto err; \
  843. } while(0)
  844. #define TEST_NAME \
  845. do { tmp_name[0] = '\0'; \
  846. cmp_name[0] = '\0'; \
  847. k = j; \
  848. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
  849. goto err; \
  850. if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
  851. goto err; \
  852. if (global_randomize_case) { \
  853. if (strcmp(tmp_name, cmp_name) == 0) \
  854. name_matches = 1; /* we ignore mismatching names */ \
  855. } else { \
  856. if (strcasecmp(tmp_name, cmp_name) == 0) \
  857. name_matches = 1; \
  858. } \
  859. } while(0)
  860. reply.type = req->request_type;
  861. /* skip over each question in the reply */
  862. for (i = 0; i < questions; ++i) {
  863. /* the question looks like
  864. * <label:name><u16:type><u16:class>
  865. */
  866. TEST_NAME;
  867. j += 4;
  868. if (j >= length) goto err;
  869. }
  870. if (!name_matches)
  871. goto err;
  872. /* now we have the answer section which looks like
  873. * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  874. */
  875. for (i = 0; i < answers; ++i) {
  876. u16 type, class;
  877. GET_NAME;
  878. GET16(type);
  879. GET16(class);
  880. GET32(ttl);
  881. GET16(datalength);
  882. if (type == TYPE_A && class == CLASS_INET) {
  883. int addrcount, addrtocopy;
  884. if (req->request_type != TYPE_A) {
  885. j += datalength; continue;
  886. }
  887. if ((datalength & 3) != 0) /* not an even number of As. */
  888. goto err;
  889. addrcount = datalength >> 2;
  890. addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
  891. ttl_r = MIN(ttl_r, ttl);
  892. /* we only bother with the first four addresses. */
  893. if (j + 4*addrtocopy > length) goto err;
  894. memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
  895. packet + j, 4*addrtocopy);
  896. reply.data.a.addrcount += addrtocopy;
  897. reply.have_answer = 1;
  898. if (reply.data.a.addrcount == MAX_ADDRS) break;
  899. j += 4*addrtocopy;
  900. } else if (type == TYPE_PTR && class == CLASS_INET) {
  901. if (req->request_type != TYPE_PTR) {
  902. j += datalength; continue;
  903. }
  904. GET_NAME;
  905. strlcpy(reply.data.ptr.name, tmp_name,
  906. sizeof(reply.data.ptr.name));
  907. ttl_r = MIN(ttl_r, ttl);
  908. reply.have_answer = 1;
  909. break;
  910. } else if (type == TYPE_AAAA && class == CLASS_INET) {
  911. int addrcount, addrtocopy;
  912. if (req->request_type != TYPE_AAAA) {
  913. j += datalength; continue;
  914. }
  915. if ((datalength & 15) != 0) /* not an even number of AAAAs. */
  916. goto err;
  917. addrcount = datalength >> 4; /* each address is 16 bytes long */
  918. addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
  919. ttl_r = MIN(ttl_r, ttl);
  920. /* we only bother with the first four addresses. */
  921. if (j + 16*addrtocopy > length) goto err;
  922. memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
  923. packet + j, 16*addrtocopy);
  924. reply.data.aaaa.addrcount += addrtocopy;
  925. reply.have_answer = 1;
  926. if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
  927. j += 16*addrtocopy;
  928. } else {
  929. /* skip over any other type of resource */
  930. j += datalength;
  931. }
  932. }
  933. reply_handle(req, flags, ttl_r, &reply);
  934. return 0;
  935. err:
  936. if (req)
  937. reply_handle(req, flags, 0, NULL);
  938. return -1;
  939. }
  940. /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
  941. /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
  942. /* callback. */
  943. static int
  944. request_parse(u8 *packet, ssize_t length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
  945. {
  946. int j = 0; /* index into packet */
  947. u16 _t; /* used by the macros */
  948. char tmp_name[256]; /* used by the macros */
  949. int i;
  950. u16 trans_id, flags, questions, answers, authority, additional;
  951. struct server_request *server_req = NULL;
  952. /* Get the header fields */
  953. GET16(trans_id);
  954. GET16(flags);
  955. GET16(questions);
  956. GET16(answers);
  957. GET16(authority);
  958. GET16(additional);
  959. if (flags & 0x8000) return -1; /* Must not be an answer. */
  960. flags &= 0x0110; /* Only RD and CD get preserved. */
  961. if (length > INT_MAX)
  962. return -1;
  963. server_req = mm_malloc(sizeof(struct server_request));
  964. if (server_req == NULL) return -1;
  965. memset(server_req, 0, sizeof(struct server_request));
  966. server_req->trans_id = trans_id;
  967. memcpy(&server_req->addr, addr, addrlen);
  968. server_req->addrlen = addrlen;
  969. server_req->base.flags = flags;
  970. server_req->base.nquestions = 0;
  971. server_req->base.questions = mm_malloc(sizeof(struct evdns_server_question *) * questions);
  972. if (server_req->base.questions == NULL)
  973. goto err;
  974. for (i = 0; i < questions; ++i) {
  975. u16 type, class;
  976. struct evdns_server_question *q;
  977. size_t namelen;
  978. if (name_parse(packet, (int)length, &j, tmp_name, sizeof(tmp_name))<0)
  979. goto err;
  980. GET16(type);
  981. GET16(class);
  982. namelen = strlen(tmp_name);
  983. q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
  984. if (!q)
  985. goto err;
  986. q->type = type;
  987. q->dns_question_class = class;
  988. memcpy(q->name, tmp_name, namelen+1);
  989. server_req->base.questions[server_req->base.nquestions++] = q;
  990. }
  991. /* Ignore answers, authority, and additional. */
  992. server_req->port = port;
  993. port->refcnt++;
  994. /* Only standard queries are supported. */
  995. if (flags & 0x7800) {
  996. evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
  997. return -1;
  998. }
  999. port->user_callback(&(server_req->base), port->user_data);
  1000. return 0;
  1001. err:
  1002. if (server_req) {
  1003. if (server_req->base.questions) {
  1004. for (i = 0; i < server_req->base.nquestions; ++i)
  1005. mm_free(server_req->base.questions[i]);
  1006. mm_free(server_req->base.questions);
  1007. }
  1008. CLEAR(server_req);
  1009. mm_free(server_req);
  1010. }
  1011. return -1;
  1012. #undef SKIP_NAME
  1013. #undef GET32
  1014. #undef GET16
  1015. #undef GET8
  1016. }
  1017. static uint16_t
  1018. default_transaction_id_fn(void)
  1019. {
  1020. u16 trans_id;
  1021. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  1022. struct timespec ts;
  1023. #ifdef CLOCK_MONOTONIC
  1024. if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
  1025. #else
  1026. if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
  1027. #endif
  1028. event_err(1, "clock_gettime");
  1029. trans_id = ts.tv_nsec & 0xffff;
  1030. #endif
  1031. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  1032. struct timeval tv;
  1033. gettimeofday(&tv, NULL);
  1034. trans_id = tv.tv_usec & 0xffff;
  1035. #endif
  1036. #ifdef DNS_USE_OPENSSL_FOR_ID
  1037. if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
  1038. /* in the case that the RAND call fails we back */
  1039. /* down to using gettimeofday. */
  1040. /*
  1041. struct timeval tv;
  1042. gettimeofday(&tv, NULL);
  1043. trans_id = tv.tv_usec & 0xffff;
  1044. */
  1045. abort();
  1046. }
  1047. #endif
  1048. return (unsigned short) trans_id;
  1049. }
  1050. static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
  1051. static void
  1052. default_random_bytes_fn(char *buf, size_t n)
  1053. {
  1054. unsigned i;
  1055. for (i = 0; i < n; i += 2) {
  1056. u16 tid = trans_id_function();
  1057. buf[i] = (tid >> 8) & 0xff;
  1058. if (i+1<n)
  1059. buf[i+1] = tid & 0xff;
  1060. }
  1061. }
  1062. static void (*rand_bytes_function)(char *buf, size_t n) =
  1063. default_random_bytes_fn;
  1064. static u16
  1065. trans_id_from_random_bytes_fn(void)
  1066. {
  1067. u16 tid;
  1068. rand_bytes_function((char*) &tid, sizeof(tid));
  1069. return tid;
  1070. }
  1071. void
  1072. evdns_set_transaction_id_fn(uint16_t (*fn)(void))
  1073. {
  1074. if (fn)
  1075. trans_id_function = fn;
  1076. else
  1077. trans_id_function = default_transaction_id_fn;
  1078. rand_bytes_function = default_random_bytes_fn;
  1079. }
  1080. void
  1081. evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
  1082. {
  1083. rand_bytes_function = fn;
  1084. trans_id_function = trans_id_from_random_bytes_fn;
  1085. }
  1086. /* Try to choose a strong transaction id which isn't already in flight */
  1087. static u16
  1088. transaction_id_pick(void) {
  1089. for (;;) {
  1090. const struct evdns_request *req = req_head, *started_at;
  1091. u16 trans_id = trans_id_function();
  1092. if (trans_id == 0xffff) continue;
  1093. /* now check to see if that id is already inflight */
  1094. req = started_at = req_head;
  1095. if (req) {
  1096. do {
  1097. if (req->trans_id == trans_id) break;
  1098. req = req->next;
  1099. } while (req != started_at);
  1100. }
  1101. /* we didn't find it, so this is a good id */
  1102. if (req == started_at) return trans_id;
  1103. }
  1104. }
  1105. /* choose a namesever to use. This function will try to ignore */
  1106. /* nameservers which we think are down and load balance across the rest */
  1107. /* by updating the server_head global each time. */
  1108. static struct nameserver *
  1109. nameserver_pick(void) {
  1110. struct nameserver *started_at = server_head, *picked;
  1111. if (!server_head) return NULL;
  1112. /* if we don't have any good nameservers then there's no */
  1113. /* point in trying to find one. */
  1114. if (!global_good_nameservers) {
  1115. server_head = server_head->next;
  1116. return server_head;
  1117. }
  1118. /* remember that nameservers are in a circular list */
  1119. for (;;) {
  1120. if (server_head->state) {
  1121. /* we think this server is currently good */
  1122. picked = server_head;
  1123. server_head = server_head->next;
  1124. return picked;
  1125. }
  1126. server_head = server_head->next;
  1127. if (server_head == started_at) {
  1128. /* all the nameservers seem to be down */
  1129. /* so we just return this one and hope for the */
  1130. /* best */
  1131. assert(global_good_nameservers == 0);
  1132. picked = server_head;
  1133. server_head = server_head->next;
  1134. return picked;
  1135. }
  1136. }
  1137. }
  1138. /* this is called when a namesever socket is ready for reading */
  1139. static void
  1140. nameserver_read(struct nameserver *ns) {
  1141. struct sockaddr_storage ss;
  1142. struct sockaddr *sa = (struct sockaddr *) &ss;
  1143. socklen_t addrlen = sizeof(ss);
  1144. u8 packet[1500];
  1145. for (;;) {
  1146. const int r =
  1147. (int)recvfrom(ns->socket, packet, (socklen_t)sizeof(packet), 0,
  1148. sa, &addrlen);
  1149. if (r < 0) {
  1150. int err = last_error(ns->socket);
  1151. if (error_is_eagain(err)) return;
  1152. nameserver_failed(ns, tor_socket_strerror(err));
  1153. return;
  1154. }
  1155. /* XXX Match port too? */
  1156. if (!sockaddr_eq(sa, (struct sockaddr*)&ns->address, 0)) {
  1157. log(EVDNS_LOG_WARN,
  1158. "Address mismatch on received DNS packet. Address was %s",
  1159. debug_ntop(sa));
  1160. return;
  1161. }
  1162. ns->timedout = 0;
  1163. reply_parse(packet, r);
  1164. }
  1165. }
  1166. /* Read a packet from a DNS client on a server port s, parse it, and */
  1167. /* act accordingly. */
  1168. static void
  1169. server_port_read(struct evdns_server_port *s) {
  1170. u8 packet[1500];
  1171. struct sockaddr_storage addr;
  1172. socklen_t addrlen;
  1173. ssize_t r;
  1174. for (;;) {
  1175. addrlen = (socklen_t)sizeof(struct sockaddr_storage);
  1176. r = recvfrom(s->socket, packet, sizeof(packet), 0,
  1177. (struct sockaddr*) &addr, &addrlen);
  1178. if (r < 0) {
  1179. int err = last_error(s->socket);
  1180. if (error_is_eagain(err)) return;
  1181. log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
  1182. tor_socket_strerror(err), err);
  1183. return;
  1184. }
  1185. request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
  1186. }
  1187. }
  1188. /* Try to write all pending replies on a given DNS server port. */
  1189. static void
  1190. server_port_flush(struct evdns_server_port *port)
  1191. {
  1192. while (port->pending_replies) {
  1193. struct server_request *req = port->pending_replies;
  1194. ssize_t r = sendto(port->socket, req->response, req->response_len, 0,
  1195. (struct sockaddr*) &req->addr, (socklen_t)req->addrlen);
  1196. if (r < 0) {
  1197. int err = last_error(port->socket);
  1198. if (error_is_eagain(err))
  1199. return;
  1200. log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", tor_socket_strerror(err), err);
  1201. }
  1202. if (server_request_free(req)) {
  1203. /* we released the last reference to req->port. */
  1204. return;
  1205. }
  1206. }
  1207. /* We have no more pending requests; stop listening for 'writeable' events. */
  1208. (void) event_del(&port->event);
  1209. CLEAR(&port->event);
  1210. event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
  1211. server_port_ready_callback, port);
  1212. if (event_add(&port->event, NULL) < 0) {
  1213. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
  1214. /* ???? Do more? */
  1215. }
  1216. }
  1217. /* set if we are waiting for the ability to write to this server. */
  1218. /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
  1219. /* we stop these events. */
  1220. static void
  1221. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  1222. if (ns->write_waiting == waiting) return;
  1223. ns->write_waiting = waiting;
  1224. (void) event_del(&ns->event);
  1225. CLEAR(&ns->event);
  1226. event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  1227. nameserver_ready_callback, ns);
  1228. if (event_add(&ns->event, NULL) < 0) {
  1229. log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
  1230. debug_ntop((struct sockaddr *)&ns->address));
  1231. /* ???? Do more? */
  1232. }
  1233. }
  1234. /* a callback function. Called by libevent when the kernel says that */
  1235. /* a nameserver socket is ready for writing or reading */
  1236. static void
  1237. nameserver_ready_callback(int fd, short events, void *arg) {
  1238. struct nameserver *ns = (struct nameserver *) arg;
  1239. (void)fd;
  1240. if (events & EV_WRITE) {
  1241. ns->choked = 0;
  1242. if (!evdns_transmit()) {
  1243. nameserver_write_waiting(ns, 0);
  1244. }
  1245. }
  1246. if (events & EV_READ) {
  1247. nameserver_read(ns);
  1248. }
  1249. }
  1250. /* a callback function. Called by libevent when the kernel says that */
  1251. /* a server socket is ready for writing or reading. */
  1252. static void
  1253. server_port_ready_callback(int fd, short events, void *arg) {
  1254. struct evdns_server_port *port = (struct evdns_server_port *) arg;
  1255. (void) fd;
  1256. if (events & EV_WRITE) {
  1257. port->choked = 0;
  1258. server_port_flush(port);
  1259. }
  1260. if (events & EV_READ) {
  1261. server_port_read(port);
  1262. }
  1263. }
  1264. /* This is an inefficient representation; only use it via the dnslabel_table_*
  1265. * functions, so that is can be safely replaced with something smarter later. */
  1266. #define MAX_LABELS 128
  1267. /* Structures used to implement name compression */
  1268. struct dnslabel_entry { char *v; off_t pos; };
  1269. struct dnslabel_table {
  1270. int n_labels; /* number of current entries */
  1271. /* map from name to position in message */
  1272. struct dnslabel_entry labels[MAX_LABELS];
  1273. };
  1274. /* Initialize dnslabel_table. */
  1275. static void
  1276. dnslabel_table_init(struct dnslabel_table *table)
  1277. {
  1278. table->n_labels = 0;
  1279. }
  1280. /* Free all storage held by table, but not the table itself. */
  1281. static void
  1282. dnslabel_clear(struct dnslabel_table *table)
  1283. {
  1284. int i;
  1285. for (i = 0; i < table->n_labels; ++i)
  1286. mm_free(table->labels[i].v);
  1287. table->n_labels = 0;
  1288. }
  1289. /* return the position of the label in the current message, or -1 if the label */
  1290. /* hasn't been used yet. */
  1291. static int
  1292. dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
  1293. {
  1294. int i;
  1295. for (i = 0; i < table->n_labels; ++i) {
  1296. if (!strcmp(label, table->labels[i].v)) {
  1297. off_t pos = table->labels[i].pos;
  1298. if (pos > 65535)
  1299. return -1;
  1300. return (int)pos;
  1301. }
  1302. }
  1303. return -1;
  1304. }
  1305. /* remember that we've used the label at position pos */
  1306. static int
  1307. dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
  1308. {
  1309. char *v;
  1310. int p;
  1311. if (table->n_labels == MAX_LABELS)
  1312. return (-1);
  1313. v = mm_strdup(label);
  1314. if (v == NULL)
  1315. return (-1);
  1316. p = table->n_labels++;
  1317. table->labels[p].v = v;
  1318. table->labels[p].pos = pos;
  1319. return (0);
  1320. }
  1321. /* Converts a string to a length-prefixed set of DNS labels, starting */
  1322. /* at buf[j]. name and buf must not overlap. name_len should be the length */
  1323. /* of name. table is optional, and is used for compression. */
  1324. /* */
  1325. /* Input: abc.def */
  1326. /* Output: <3>abc<3>def<0> */
  1327. /* */
  1328. /* Returns the first index after the encoded name, or negative on error. */
  1329. /* -1 label was > 63 bytes */
  1330. /* -2 name too long to fit in buffer. */
  1331. /* */
  1332. static off_t
  1333. dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
  1334. const char *name, const size_t name_len,
  1335. struct dnslabel_table *table) {
  1336. const char *end = name + name_len;
  1337. int ref = 0;
  1338. u16 _t;
  1339. #define APPEND16(x) do { \
  1340. if (j + 2 > (off_t)buf_len) \
  1341. goto overflow; \
  1342. _t = htons(x); \
  1343. memcpy(buf + j, &_t, 2); \
  1344. j += 2; \
  1345. } while (0)
  1346. #define APPEND32(x) do { \
  1347. if (j + 4 > (off_t)buf_len) \
  1348. goto overflow; \
  1349. _t32 = htonl(x); \
  1350. memcpy(buf + j, &_t32, 4); \
  1351. j += 4; \
  1352. } while (0)
  1353. if (name_len > 255) return -2;
  1354. for (;;) {
  1355. const char *const start = name;
  1356. if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
  1357. APPEND16(ref | 0xc000);
  1358. return j;
  1359. }
  1360. name = strchr(name, '.');
  1361. if (!name) {
  1362. const size_t label_len = end - start;
  1363. if (label_len > 63) return -1;
  1364. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1365. if (table) dnslabel_table_add(table, start, j);
  1366. buf[j++] = (uint8_t)label_len;
  1367. memcpy(buf + j, start, label_len);
  1368. j += end - start;
  1369. break;
  1370. } else {
  1371. /* append length of the label. */
  1372. const size_t label_len = name - start;
  1373. if (label_len > 63) return -1;
  1374. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1375. if (table) dnslabel_table_add(table, start, j);
  1376. buf[j++] = (uint8_t)label_len;
  1377. memcpy(buf + j, start, name - start);
  1378. j += name - start;
  1379. /* hop over the '.' */
  1380. name++;
  1381. }
  1382. }
  1383. /* the labels must be terminated by a 0. */
  1384. /* It's possible that the name ended in a . */
  1385. /* in which case the zero is already there */
  1386. if (!j || buf[j-1]) buf[j++] = 0;
  1387. return j;
  1388. overflow:
  1389. return (-2);
  1390. }
  1391. /* Finds the length of a dns request for a DNS name of the given */
  1392. /* length. The actual request may be smaller than the value returned */
  1393. /* here */
  1394. static size_t
  1395. evdns_request_len(const size_t name_len) {
  1396. return 96 + /* length of the DNS standard header */
  1397. name_len + 2 +
  1398. 4; /* space for the resource type */
  1399. }
  1400. /* build a dns request packet into buf. buf should be at least as long */
  1401. /* as evdns_request_len told you it should be. */
  1402. /* */
  1403. /* Returns the amount of space used. Negative on error. */
  1404. static int
  1405. evdns_request_data_build(const char *const name, const size_t name_len,
  1406. const u16 trans_id, const u16 type, const u16 class,
  1407. u8 *const buf, size_t buf_len) {
  1408. off_t j = 0; /* current offset into buf */
  1409. u16 _t; /* used by the macros */
  1410. APPEND16(trans_id);
  1411. APPEND16(0x0100); /* standard query, recusion needed */
  1412. APPEND16(1); /* one question */
  1413. APPEND16(0); /* no answers */
  1414. APPEND16(0); /* no authority */
  1415. APPEND16(0); /* no additional */
  1416. j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
  1417. if (j < 0) {
  1418. return (int)j;
  1419. }
  1420. APPEND16(type);
  1421. APPEND16(class);
  1422. return (int)j;
  1423. overflow:
  1424. return (-1);
  1425. }
  1426. /* exported function */
  1427. struct evdns_server_port *
  1428. evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
  1429. {
  1430. struct evdns_server_port *port;
  1431. if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
  1432. return NULL;
  1433. memset(port, 0, sizeof(struct evdns_server_port));
  1434. assert(!is_tcp); /* TCP sockets not yet implemented */
  1435. port->socket = socket;
  1436. port->refcnt = 1;
  1437. port->choked = 0;
  1438. port->closing = 0;
  1439. port->user_callback = cb;
  1440. port->user_data = user_data;
  1441. port->pending_replies = NULL;
  1442. event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
  1443. server_port_ready_callback, port);
  1444. if (event_add(&port->event, NULL)<0) {
  1445. mm_free(port);
  1446. return NULL;
  1447. }
  1448. return port;
  1449. }
  1450. /* exported function */
  1451. void
  1452. evdns_close_server_port(struct evdns_server_port *port)
  1453. {
  1454. port->closing = 1;
  1455. if (--port->refcnt == 0)
  1456. server_port_free(port);
  1457. }
  1458. /* exported function */
  1459. int
  1460. evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
  1461. {
  1462. struct server_request *req = TO_SERVER_REQUEST(_req);
  1463. struct server_reply_item **itemp, *item;
  1464. int *countp;
  1465. if (req->response) /* have we already answered? */
  1466. return (-1);
  1467. switch (section) {
  1468. case EVDNS_ANSWER_SECTION:
  1469. itemp = &req->answer;
  1470. countp = &req->n_answer;
  1471. break;
  1472. case EVDNS_AUTHORITY_SECTION:
  1473. itemp = &req->authority;
  1474. countp = &req->n_authority;
  1475. break;
  1476. case EVDNS_ADDITIONAL_SECTION:
  1477. itemp = &req->additional;
  1478. countp = &req->n_additional;
  1479. break;
  1480. default:
  1481. return (-1);
  1482. }
  1483. while (*itemp) {
  1484. itemp = &((*itemp)->next);
  1485. }
  1486. item = mm_malloc(sizeof(struct server_reply_item));
  1487. if (!item)
  1488. return -1;
  1489. CLEAR(item);
  1490. item->next = NULL;
  1491. if (!(item->name = mm_strdup(name))) {
  1492. CLEAR(item);
  1493. mm_free(item);
  1494. return -1;
  1495. }
  1496. item->type = type;
  1497. item->class = class;
  1498. item->ttl = ttl;
  1499. item->is_name = is_name != 0;
  1500. item->datalen = 0;
  1501. item->data = NULL;
  1502. if (data) {
  1503. if (item->is_name) {
  1504. if (!(item->data = mm_strdup(data))) {
  1505. mm_free(item->name);
  1506. CLEAR(item);
  1507. mm_free(item);
  1508. return -1;
  1509. }
  1510. item->datalen = (u16)-1;
  1511. } else {
  1512. if (!(item->data = mm_malloc(datalen))) {
  1513. mm_free(item->name);
  1514. CLEAR(item);
  1515. mm_free(item);
  1516. return -1;
  1517. }
  1518. item->datalen = datalen;
  1519. memcpy(item->data, data, datalen);
  1520. }
  1521. }
  1522. *itemp = item;
  1523. ++(*countp);
  1524. return 0;
  1525. }
  1526. /* exported function */
  1527. int
  1528. evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
  1529. {
  1530. return evdns_server_request_add_reply(
  1531. req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
  1532. ttl, n*4, 0, addrs);
  1533. }
  1534. /* exported function */
  1535. int
  1536. evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
  1537. {
  1538. return evdns_server_request_add_reply(
  1539. req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
  1540. ttl, n*16, 0, addrs);
  1541. }
  1542. /* exported function */
  1543. int
  1544. evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
  1545. {
  1546. u32 a;
  1547. char buf[32];
  1548. assert(in || inaddr_name);
  1549. assert(!(in && inaddr_name));
  1550. if (in) {
  1551. a = ntohl(in->s_addr);
  1552. snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  1553. (int)(u8)((a )&0xff),
  1554. (int)(u8)((a>>8 )&0xff),
  1555. (int)(u8)((a>>16)&0xff),
  1556. (int)(u8)((a>>24)&0xff));
  1557. inaddr_name = buf;
  1558. }
  1559. return evdns_server_request_add_reply(
  1560. req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
  1561. ttl, -1, 1, hostname);
  1562. }
  1563. /* exported function */
  1564. int
  1565. evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
  1566. {
  1567. return evdns_server_request_add_reply(
  1568. req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
  1569. ttl, -1, 1, cname);
  1570. }
  1571. static int
  1572. evdns_server_request_format_response(struct server_request *req, int err)
  1573. {
  1574. unsigned char buf[1500];
  1575. size_t buf_len = sizeof(buf);
  1576. off_t j = 0, r;
  1577. u16 _t;
  1578. u32 _t32;
  1579. int i;
  1580. u16 flags;
  1581. struct dnslabel_table table;
  1582. if (err < 0 || err > 15) return -1;
  1583. /* Set response bit and error code; copy OPCODE and RD fields from
  1584. * question; copy RA and AA if set by caller. */
  1585. flags = req->base.flags;
  1586. flags |= (0x8000 | err);
  1587. dnslabel_table_init(&table);
  1588. APPEND16(req->trans_id);
  1589. APPEND16(flags);
  1590. APPEND16(req->base.nquestions);
  1591. APPEND16(req->n_answer);
  1592. APPEND16(req->n_authority);
  1593. APPEND16(req->n_additional);
  1594. /* Add questions. */
  1595. for (i=0; i < req->base.nquestions; ++i) {
  1596. const char *s = req->base.questions[i]->name;
  1597. j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
  1598. if (j < 0) {
  1599. dnslabel_clear(&table);
  1600. return (int) j;
  1601. }
  1602. APPEND16(req->base.questions[i]->type);
  1603. APPEND16(req->base.questions[i]->dns_question_class);
  1604. }
  1605. /* Add answer, authority, and additional sections. */
  1606. for (i=0; i<3; ++i) {
  1607. struct server_reply_item *item;
  1608. if (i==0)
  1609. item = req->answer;
  1610. else if (i==1)
  1611. item = req->authority;
  1612. else
  1613. item = req->additional;
  1614. while (item) {
  1615. r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
  1616. if (r < 0)
  1617. goto overflow;
  1618. j = r;
  1619. APPEND16(item->type);
  1620. APPEND16(item->class);
  1621. APPEND32(item->ttl);
  1622. if (item->is_name) {
  1623. off_t len_idx = j, name_start;
  1624. j += 2;
  1625. name_start = j;
  1626. r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
  1627. if (r < 0)
  1628. goto overflow;
  1629. j = r;
  1630. _t = htons( (j-name_start) );
  1631. memcpy(buf+len_idx, &_t, 2);
  1632. } else {
  1633. APPEND16(item->datalen);
  1634. if (j+item->datalen > (off_t)buf_len)
  1635. goto overflow;
  1636. memcpy(buf+j, item->data, item->datalen);
  1637. j += item->datalen;
  1638. }
  1639. item = item->next;
  1640. }
  1641. }
  1642. if (j > 512) {
  1643. overflow:
  1644. j = 512;
  1645. buf[2] |= 0x02; /* set the truncated bit. */
  1646. }
  1647. req->response_len = (size_t)j;
  1648. if (!(req->response = mm_malloc(req->response_len))) {
  1649. server_request_free_answers(req);
  1650. dnslabel_clear(&table);
  1651. return (-1);
  1652. }
  1653. memcpy(req->response, buf, req->response_len);
  1654. server_request_free_answers(req);
  1655. dnslabel_clear(&table);
  1656. return (0);
  1657. }
  1658. /* exported function */
  1659. int
  1660. evdns_server_request_respond(struct evdns_server_request *_req, int err)
  1661. {
  1662. struct server_request *req = TO_SERVER_REQUEST(_req);
  1663. struct evdns_server_port *port = req->port;
  1664. ssize_t r;
  1665. if (!req->response) {
  1666. if ((r = evdns_server_request_format_response(req, err))<0)
  1667. return (int)r;
  1668. }
  1669. r = sendto(port->socket, req->response, req->response_len, 0,
  1670. (struct sockaddr*) &req->addr, req->addrlen);
  1671. if (r<0) {
  1672. int err = last_error(port->socket);
  1673. if (! error_is_eagain(err))
  1674. return -1;
  1675. if (port->pending_replies) {
  1676. req->prev_pending = port->pending_replies->prev_pending;
  1677. req->next_pending = port->pending_replies;
  1678. req->prev_pending->next_pending =
  1679. req->next_pending->prev_pending = req;
  1680. } else {
  1681. req->prev_pending = req->next_pending = req;
  1682. port->pending_replies = req;
  1683. port->choked = 1;
  1684. (void) event_del(&port->event);
  1685. CLEAR(&port->event);
  1686. event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
  1687. if (event_add(&port->event, NULL) < 0) {
  1688. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
  1689. }
  1690. }
  1691. return 1;
  1692. }
  1693. if (server_request_free(req))
  1694. return 0;
  1695. if (port->pending_replies)
  1696. server_port_flush(port);
  1697. return 0;
  1698. }
  1699. /* Free all storage held by RRs in req. */
  1700. static void
  1701. server_request_free_answers(struct server_request *req)
  1702. {
  1703. struct server_reply_item *victim, *next, **list;
  1704. int i;
  1705. for (i = 0; i < 3; ++i) {
  1706. if (i==0)
  1707. list = &req->answer;
  1708. else if (i==1)
  1709. list = &req->authority;
  1710. else
  1711. list = &req->additional;
  1712. victim = *list;
  1713. while (victim) {
  1714. next = victim->next;
  1715. mm_free(victim->name);
  1716. if (victim->data)
  1717. mm_free(victim->data);
  1718. mm_free(victim);
  1719. victim = next;
  1720. }
  1721. *list = NULL;
  1722. }
  1723. }
  1724. /* Free all storage held by req, and remove links to it. */
  1725. /* return true iff we just wound up freeing the server_port. */
  1726. static int
  1727. server_request_free(struct server_request *req)
  1728. {
  1729. int i, rc=1;
  1730. if (req->base.questions) {
  1731. for (i = 0; i < req->base.nquestions; ++i)
  1732. mm_free(req->base.questions[i]);
  1733. mm_free(req->base.questions);
  1734. }
  1735. if (req->port) {
  1736. if (req->port->pending_replies == req) {
  1737. if (req->next_pending)
  1738. req->port->pending_replies = req->next_pending;
  1739. else
  1740. req->port->pending_replies = NULL;
  1741. }
  1742. rc = --req->port->refcnt;
  1743. }
  1744. if (req->response) {
  1745. mm_free(req->response);
  1746. }
  1747. server_request_free_answers(req);
  1748. if (req->next_pending && req->next_pending != req) {
  1749. req->next_pending->prev_pending = req->prev_pending;
  1750. req->prev_pending->next_pending = req->next_pending;
  1751. }
  1752. if (rc == 0) {
  1753. server_port_free(req->port);
  1754. CLEAR(req);
  1755. mm_free(req);
  1756. return (1);
  1757. }
  1758. CLEAR(req);
  1759. mm_free(req);
  1760. return (0);
  1761. }
  1762. /* Free all storage held by an evdns_server_port. Only called when the
  1763. * reference count is down to 0. */
  1764. static void
  1765. server_port_free(struct evdns_server_port *port)
  1766. {
  1767. assert(port);
  1768. assert(!port->refcnt);
  1769. assert(!port->pending_replies);
  1770. if (port->socket > 0) {
  1771. CLOSE_SOCKET(port->socket);
  1772. port->socket = -1;
  1773. }
  1774. (void) event_del(&port->event);
  1775. CLEAR(&port->event);
  1776. CLEAR(port);
  1777. mm_free(port);
  1778. }
  1779. /* exported function */
  1780. int
  1781. evdns_server_request_drop(struct evdns_server_request *_req)
  1782. {
  1783. struct server_request *req = TO_SERVER_REQUEST(_req);
  1784. server_request_free(req);
  1785. return 0;
  1786. }
  1787. /* exported function */
  1788. int
  1789. evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
  1790. {
  1791. struct server_request *req = TO_SERVER_REQUEST(_req);
  1792. if (addr_len < (int)req->addrlen)
  1793. return -1;
  1794. memcpy(sa, &(req->addr), req->addrlen);
  1795. return req->addrlen;
  1796. }
  1797. #undef APPEND16
  1798. #undef APPEND32
  1799. /* this is a libevent callback function which is called when a request */
  1800. /* has timed out. */
  1801. static void
  1802. evdns_request_timeout_callback(int fd, short events, void *arg) {
  1803. struct evdns_request *const req = (struct evdns_request *) arg;
  1804. (void) fd;
  1805. (void) events;
  1806. log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
  1807. req->ns->timedout++;
  1808. if (req->ns->timedout > global_max_nameserver_timeout) {
  1809. req->ns->timedout = 0;
  1810. nameserver_failed(req->ns, "request timed out.");
  1811. }
  1812. if (req->tx_count >= global_max_retransmits) {
  1813. /* this request has failed */
  1814. reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
  1815. request_finished(req, &req_head);
  1816. } else {
  1817. /* retransmit it */
  1818. /* Stop waiting for the timeout. No need to do this in
  1819. * request_finished; that one already deletes the timeout event.
  1820. * XXXX021 port this change to libevent. */
  1821. del_timeout_event(req);
  1822. CLEAR(&req->timeout_event);
  1823. evdns_request_transmit(req);
  1824. }
  1825. }
  1826. /* try to send a request to a given server. */
  1827. /* */
  1828. /* return: */
  1829. /* 0 ok */
  1830. /* 1 temporary failure */
  1831. /* 2 other failure */
  1832. static int
  1833. evdns_request_transmit_to(struct evdns_request *req, struct nameserver *server) {
  1834. const ssize_t r = send(server->socket, req->request, req->request_len, 0);
  1835. if (r < 0) {
  1836. int err = last_error(server->socket);
  1837. if (error_is_eagain(err)) return 1;
  1838. nameserver_failed(req->ns, tor_socket_strerror(err));
  1839. return 2;
  1840. } else if (r != (ssize_t)req->request_len) {
  1841. return 1; /* short write */
  1842. } else {
  1843. return 0;
  1844. }
  1845. }
  1846. /* try to send a request, updating the fields of the request */
  1847. /* as needed */
  1848. /* */
  1849. /* return: */
  1850. /* 0 ok */
  1851. /* 1 failed */
  1852. static int
  1853. evdns_request_transmit(struct evdns_request *req) {
  1854. int retcode = 0, r;
  1855. /* if we fail to send this packet then this flag marks it */
  1856. /* for evdns_transmit */
  1857. req->transmit_me = 1;
  1858. if (req->trans_id == 0xffff) abort();
  1859. if (req->ns->choked) {
  1860. /* don't bother trying to write to a socket */
  1861. /* which we have had EAGAIN from */
  1862. return 1;
  1863. }
  1864. r = evdns_request_transmit_to(req, req->ns);
  1865. switch (r) {
  1866. case 1:
  1867. /* temp failure */
  1868. req->ns->choked = 1;
  1869. nameserver_write_waiting(req->ns, 1);
  1870. return 1;
  1871. case 2:
  1872. /* failed to transmit the request entirely. */
  1873. retcode = 1;
  1874. /* fall through: we'll set a timeout, which will time out,
  1875. * and make us retransmit the request anyway. */
  1876. default:
  1877. /* transmitted; we need to check for timeout. */
  1878. log(EVDNS_LOG_DEBUG,
  1879. "Setting timeout for request %lx", (unsigned long) req);
  1880. del_timeout_event_if_set(req);
  1881. evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
  1882. if (add_timeout_event(req, &global_timeout) < 0) {
  1883. log(EVDNS_LOG_WARN,
  1884. "Error from libevent when adding timer for request %lx",
  1885. (unsigned long) req);
  1886. /* ???? Do more? */
  1887. }
  1888. req->tx_count++;
  1889. req->transmit_me = 0;
  1890. return retcode;
  1891. }
  1892. }
  1893. static void
  1894. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  1895. struct sockaddr *addr = arg;
  1896. struct nameserver *server;
  1897. (void) type;
  1898. (void) count;
  1899. (void) ttl;
  1900. (void) addresses;
  1901. for (server = server_head; server; server = server->next) {
  1902. if (sockaddr_eq(addr, (struct sockaddr*) &server->address, 1)) {
  1903. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  1904. /* this is a good reply */
  1905. nameserver_up(server);
  1906. } else {
  1907. nameserver_probe_failed(server);
  1908. }
  1909. }
  1910. if (server->next == server_head)
  1911. break;
  1912. }
  1913. mm_free(addr);
  1914. }
  1915. static void
  1916. nameserver_send_probe(struct nameserver *const ns) {
  1917. struct evdns_request *req;
  1918. struct sockaddr_storage *addr;
  1919. /* here we need to send a probe to a given nameserver */
  1920. /* in the hope that it is up now. */
  1921. /* We identify the nameserver by its address, in case it is removed before
  1922. * our probe comes back. */
  1923. addr = mm_malloc(sizeof(struct sockaddr_storage));
  1924. memcpy(addr, &ns->address, sizeof(struct sockaddr_storage));
  1925. log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntop((struct sockaddr *)&ns->address));
  1926. req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, addr);
  1927. if (!req) {
  1928. mm_free(addr);
  1929. return;
  1930. }
  1931. /* we force this into the inflight queue no matter what */
  1932. request_trans_id_set(req, transaction_id_pick());
  1933. req->ns = ns;
  1934. request_submit(req);
  1935. }
  1936. /* returns: */
  1937. /* 0 didn't try to transmit anything */
  1938. /* 1 tried to transmit something */
  1939. static int
  1940. evdns_transmit(void) {
  1941. char did_try_to_transmit = 0;
  1942. if (req_head) {
  1943. struct evdns_request *const started_at = req_head, *req = req_head;
  1944. /* first transmit all the requests which are currently waiting */
  1945. do {
  1946. if (req->transmit_me) {
  1947. did_try_to_transmit = 1;
  1948. evdns_request_transmit(req);
  1949. }
  1950. req = req->next;
  1951. } while (req != started_at);
  1952. }
  1953. return did_try_to_transmit;
  1954. }
  1955. /* exported function */
  1956. int
  1957. evdns_count_nameservers(void)
  1958. {
  1959. const struct nameserver *server = server_head;
  1960. int n = 0;
  1961. if (!server)
  1962. return 0;
  1963. do {
  1964. ++n;
  1965. server = server->next;
  1966. } while (server != server_head);
  1967. return n;
  1968. }
  1969. /* exported function */
  1970. int
  1971. evdns_clear_nameservers_and_suspend(void)
  1972. {
  1973. struct nameserver *server = server_head, *started_at = server_head;
  1974. struct evdns_request *req = req_head, *req_started_at = req_head;
  1975. if (!server)
  1976. return 0;
  1977. while (1) {
  1978. struct nameserver *next = server->next;
  1979. (void) event_del(&server->event);
  1980. CLEAR(&server->event);
  1981. del_timeout_event(server);
  1982. CLEAR(&server->timeout_event);
  1983. if (server->socket >= 0)
  1984. CLOSE_SOCKET(server->socket);
  1985. CLEAR(server);
  1986. mm_free(server);
  1987. if (next == started_at)
  1988. break;
  1989. server = next;
  1990. }
  1991. server_head = NULL;
  1992. global_good_nameservers = 0;
  1993. while (req) {
  1994. struct evdns_request *next = req->next;
  1995. req->tx_count = req->reissue_count = 0;
  1996. req->ns = NULL;
  1997. /* ???? What to do about searches? */
  1998. del_timeout_event(req);
  1999. CLEAR(&req->timeout_event);
  2000. req->trans_id = 0;
  2001. req->transmit_me = 0;
  2002. global_requests_waiting++;
  2003. evdns_request_insert(req, &req_waiting_head);
  2004. /* We want to insert these suspended elements at the front of
  2005. * the waiting queue, since they were pending before any of
  2006. * the waiting entries were added. This is a circular list,
  2007. * so we can just shift the start back by one.*/
  2008. req_waiting_head = req_waiting_head->prev;
  2009. if (next == req_started_at)
  2010. break;
  2011. req = next;
  2012. }
  2013. req_head = NULL;
  2014. global_requests_inflight = 0;
  2015. return 0;
  2016. }
  2017. static struct sockaddr_storage global_bind_address;
  2018. static socklen_t global_bind_addrlen = 0;
  2019. static int global_bind_addr_is_set = 0;
  2020. void
  2021. evdns_set_default_outgoing_bind_address(const struct sockaddr *addr,
  2022. socklen_t addrlen)
  2023. {
  2024. memset(&global_bind_address, 0, sizeof(global_bind_address));
  2025. if (addr) {
  2026. assert(addrlen <= (socklen_t)sizeof(global_bind_address));
  2027. memcpy(&global_bind_address, addr, addrlen);
  2028. global_bind_addrlen = addrlen;
  2029. global_bind_addr_is_set = 1;
  2030. } else {
  2031. global_bind_addr_is_set = 0;
  2032. }
  2033. }
  2034. /* exported function */
  2035. int
  2036. evdns_resume(void)
  2037. {
  2038. evdns_requests_pump_waiting_queue();
  2039. return 0;
  2040. }
  2041. static int
  2042. _evdns_nameserver_add_impl(const struct sockaddr *address,
  2043. socklen_t addrlen) {
  2044. /* first check to see if we already have this nameserver */
  2045. const struct nameserver *server = server_head, *const started_at = server_head;
  2046. struct nameserver *ns;
  2047. int err = 0;
  2048. if (server) {
  2049. do {
  2050. if (sockaddr_eq(address, (struct sockaddr *)&server->address, 1)) {
  2051. log(EVDNS_LOG_DEBUG, "Duplicate nameserver.");
  2052. return 3;
  2053. }
  2054. server = server->next;
  2055. } while (server != started_at);
  2056. }
  2057. if (addrlen > (int)sizeof(ns->address)) {
  2058. log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
  2059. return 2;
  2060. }
  2061. ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
  2062. if (!ns) return -1;
  2063. memset(ns, 0, sizeof(struct nameserver));
  2064. ns->timeout_event_deleted = __LINE__;
  2065. ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
  2066. if (ns->socket < 0) { err = 1; goto out1; }
  2067. #ifdef WIN32
  2068. {
  2069. u_long nonblocking = 1;
  2070. ioctlsocket(ns->socket, FIONBIO, &nonblocking);
  2071. }
  2072. #else
  2073. fcntl(ns->socket, F_SETFL, O_NONBLOCK);
  2074. #endif
  2075. if (global_bind_addr_is_set) {
  2076. if (bind(ns->socket, (struct sockaddr *)&global_bind_address,
  2077. global_bind_addrlen) < 0) {
  2078. log(EVDNS_LOG_DEBUG, "Couldn't bind to outgoing address.");
  2079. err = 2;
  2080. goto out2;
  2081. }
  2082. }
  2083. if (connect(ns->socket, address, addrlen) != 0) {
  2084. log(EVDNS_LOG_DEBUG, "Couldn't open socket to nameserver.");
  2085. err = 2;
  2086. goto out2;
  2087. }
  2088. memcpy(&ns->address, address, addrlen);
  2089. ns->state = 1;
  2090. event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  2091. if (event_add(&ns->event, NULL) < 0) {
  2092. log(EVDNS_LOG_DEBUG, "Couldn't add event for nameserver.");
  2093. err = 2;
  2094. goto out2;
  2095. }
  2096. log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntop(address));
  2097. /* insert this nameserver into the list of them */
  2098. if (!server_head) {
  2099. ns->next = ns->prev = ns;
  2100. server_head = ns;
  2101. } else {
  2102. ns->next = server_head->next;
  2103. ns->prev = server_head;
  2104. server_head->next = ns;
  2105. if (server_head->prev == server_head) {
  2106. server_head->prev = ns;
  2107. }
  2108. }
  2109. global_good_nameservers++;
  2110. return 0;
  2111. out2:
  2112. CLOSE_SOCKET(ns->socket);
  2113. out1:
  2114. CLEAR(ns);
  2115. mm_free(ns);
  2116. log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntop(address), err);
  2117. return err;
  2118. }
  2119. /* exported function */
  2120. int
  2121. evdns_nameserver_add(uint32_t address) {
  2122. struct sockaddr_in sin;
  2123. memset(&sin, 0, sizeof(sin));
  2124. sin.sin_family = AF_INET;
  2125. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  2126. sin.sin_len = sizeof(sin);
  2127. #endif
  2128. sin.sin_addr.s_addr = htonl(address);
  2129. sin.sin_port = 53;
  2130. return _evdns_nameserver_add_impl((struct sockaddr*) &sin, sizeof(sin));
  2131. }
  2132. /* exported function */
  2133. int
  2134. evdns_nameserver_ip_add(const char *ip_as_string) {
  2135. int port;
  2136. char buf[128];
  2137. const char *cp, *addr_part, *port_part;
  2138. int is_ipv6;
  2139. /* recognized formats are:
  2140. * [ipv6]:port
  2141. * ipv6
  2142. * [ipv6]
  2143. * ipv4:port
  2144. * ipv4
  2145. */
  2146. log(EVDNS_LOG_DEBUG, "Trying to add nameserver <%s>", ip_as_string);
  2147. cp = strchr(ip_as_string, ':');
  2148. if (*ip_as_string == '[') {
  2149. size_t len;
  2150. if (!(cp = strchr(ip_as_string, ']'))) {
  2151. log(EVDNS_LOG_DEBUG, "Nameserver missing closing ]");
  2152. return 4;
  2153. }
  2154. len = cp-(ip_as_string + 1);
  2155. if (len > sizeof(buf)-1) {
  2156. log(EVDNS_LOG_DEBUG, "[Nameserver] does not fit in buffer.");
  2157. return 4;
  2158. }
  2159. memcpy(buf, ip_as_string+1, len);
  2160. buf[len] = '\0';
  2161. addr_part = buf;
  2162. if (cp[1] == ':')
  2163. port_part = cp+2;
  2164. else
  2165. port_part = NULL;
  2166. is_ipv6 = 1;
  2167. } else if (cp && strchr(cp+1, ':')) {
  2168. is_ipv6 = 1;
  2169. addr_part = ip_as_string;
  2170. port_part = NULL;
  2171. } else if (cp) {
  2172. is_ipv6 = 0;
  2173. if (cp - ip_as_string > (int)sizeof(buf)-1) {
  2174. log(EVDNS_LOG_DEBUG, "Nameserver does not fit in buffer.");
  2175. return 4;
  2176. }
  2177. memcpy(buf, ip_as_string, cp-ip_as_string);
  2178. buf[cp-ip_as_string] = '\0';
  2179. addr_part = buf;
  2180. port_part = cp+1;
  2181. } else {
  2182. addr_part = ip_as_string;
  2183. port_part = NULL;
  2184. is_ipv6 = 0;
  2185. }
  2186. if (port_part == NULL) {
  2187. port = 53;
  2188. } else {
  2189. port = strtoint(port_part);
  2190. if (port <= 0 || port > 65535) {
  2191. log(EVDNS_LOG_DEBUG, "Nameserver port <%s> out of range",
  2192. port_part);
  2193. return 4;
  2194. }
  2195. }
  2196. /* Tor-only. needs a more general fix. */
  2197. assert(addr_part);
  2198. if (is_ipv6) {
  2199. struct sockaddr_in6 sin6;
  2200. memset(&sin6, 0, sizeof(sin6));
  2201. #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
  2202. sin6.sin6_len = sizeof(sin6);
  2203. #endif
  2204. sin6.sin6_family = AF_INET6;
  2205. sin6.sin6_port = htons(port);
  2206. if (1 != tor_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) {
  2207. log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
  2208. return 4;
  2209. }
  2210. return _evdns_nameserver_add_impl((struct sockaddr*)&sin6,
  2211. sizeof(sin6));
  2212. } else {
  2213. struct sockaddr_in sin;
  2214. memset(&sin, 0, sizeof(sin));
  2215. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  2216. sin.sin_len = sizeof(sin);
  2217. #endif
  2218. sin.sin_family = AF_INET;
  2219. sin.sin_port = htons(port);
  2220. if (!inet_aton(addr_part, &sin.sin_addr)) {
  2221. log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
  2222. return 4;
  2223. }
  2224. return _evdns_nameserver_add_impl((struct sockaddr*)&sin,
  2225. sizeof(sin));
  2226. }
  2227. }
  2228. int
  2229. evdns_nameserver_sockaddr_add(const struct sockaddr *sa, socklen_t len)
  2230. {
  2231. return _evdns_nameserver_add_impl(sa, len);
  2232. }
  2233. /* insert into the tail of the queue */
  2234. static void
  2235. evdns_request_insert(struct evdns_request *req, struct evdns_request **head) {
  2236. if (!*head) {
  2237. *head = req;
  2238. req->next = req->prev = req;
  2239. return;
  2240. }
  2241. req->prev = (*head)->prev;
  2242. req->prev->next = req;
  2243. req->next = *head;
  2244. (*head)->prev = req;
  2245. }
  2246. static int
  2247. string_num_dots(const char *s) {
  2248. int count = 0;
  2249. while ((s = strchr(s, '.'))) {
  2250. s++;
  2251. count++;
  2252. }
  2253. return count;
  2254. }
  2255. static struct evdns_request *
  2256. request_new(int type, const char *name, int flags,
  2257. evdns_callback_type callback, void *user_ptr) {
  2258. const char issuing_now =
  2259. (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
  2260. const size_t name_len = strlen(name);
  2261. const size_t request_max_len = evdns_request_len(name_len);
  2262. const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
  2263. /* the request data is alloced in a single block with the header */
  2264. struct evdns_request *const req =
  2265. (struct evdns_request *) mm_malloc(sizeof(struct evdns_request) + request_max_len);
  2266. char namebuf[256];
  2267. int rlen;
  2268. (void) flags;
  2269. if (!req) return NULL;
  2270. if (name_len >= sizeof(namebuf)) {
  2271. _mm_free(req);
  2272. return NULL;
  2273. }
  2274. memset(req, 0, sizeof(struct evdns_request));
  2275. req->timeout_event_deleted = __LINE__;
  2276. if (global_randomize_case) {
  2277. unsigned i;
  2278. char randbits[32];
  2279. strlcpy(namebuf, name, sizeof(namebuf));
  2280. rand_bytes_function(randbits, (name_len+7)/8);
  2281. for (i = 0; i < name_len; ++i) {
  2282. if (ISALPHA(namebuf[i])) {
  2283. if ((randbits[i >> 3] & (1<<(i%7))))
  2284. namebuf[i] = TOLOWER(namebuf[i]);
  2285. else
  2286. namebuf[i] = TOUPPER(namebuf[i]);
  2287. }
  2288. }
  2289. name = namebuf;
  2290. }
  2291. /* request data lives just after the header */
  2292. req->request = ((u8 *) req) + sizeof(struct evdns_request);
  2293. /* denotes that the request data shouldn't be mm_free()ed */
  2294. req->request_appended = 1;
  2295. rlen = evdns_request_data_build(name, name_len, trans_id,
  2296. type, CLASS_INET, req->request, request_max_len);
  2297. if (rlen < 0)
  2298. goto err1;
  2299. req->request_len = rlen;
  2300. req->trans_id = trans_id;
  2301. req->tx_count = 0;
  2302. req->request_type = type;
  2303. req->user_pointer = user_ptr;
  2304. req->user_callback = callback;
  2305. req->ns = issuing_now ? nameserver_pick() : NULL;
  2306. req->next = req->prev = NULL;
  2307. return req;
  2308. err1:
  2309. CLEAR(req);
  2310. _mm_free(req);
  2311. return NULL;
  2312. }
  2313. static void
  2314. request_submit(struct evdns_request *const req) {
  2315. if (req->ns) {
  2316. /* if it has a nameserver assigned then this is going */
  2317. /* straight into the inflight queue */
  2318. evdns_request_insert(req, &req_head);
  2319. global_requests_inflight++;
  2320. evdns_request_transmit(req);
  2321. } else {
  2322. evdns_request_insert(req, &req_waiting_head);
  2323. global_requests_waiting++;
  2324. }
  2325. }
  2326. /* exported function */
  2327. int evdns_resolve_ipv4(const char *name, int flags,
  2328. evdns_callback_type callback, void *ptr) {
  2329. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2330. if (flags & DNS_QUERY_NO_SEARCH) {
  2331. struct evdns_request *const req =
  2332. request_new(TYPE_A, name, flags, callback, ptr);
  2333. if (req == NULL)
  2334. return (1);
  2335. request_submit(req);
  2336. return (0);
  2337. } else {
  2338. return (search_request_new(TYPE_A, name, flags, callback, ptr));
  2339. }
  2340. }
  2341. /* exported function */
  2342. int evdns_resolve_ipv6(const char *name, int flags,
  2343. evdns_callback_type callback, void *ptr) {
  2344. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2345. if (flags & DNS_QUERY_NO_SEARCH) {
  2346. struct evdns_request *const req =
  2347. request_new(TYPE_AAAA, name, flags, callback, ptr);
  2348. if (req == NULL)
  2349. return (1);
  2350. request_submit(req);
  2351. return (0);
  2352. } else {
  2353. return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
  2354. }
  2355. }
  2356. int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2357. char buf[32];
  2358. struct evdns_request *req;
  2359. u32 a;
  2360. assert(in);
  2361. a = ntohl(in->s_addr);
  2362. snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  2363. (int)(u8)((a )&0xff),
  2364. (int)(u8)((a>>8 )&0xff),
  2365. (int)(u8)((a>>16)&0xff),
  2366. (int)(u8)((a>>24)&0xff));
  2367. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2368. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  2369. if (!req) return 1;
  2370. request_submit(req);
  2371. return 0;
  2372. }
  2373. int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2374. /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
  2375. char buf[73];
  2376. char *cp;
  2377. struct evdns_request *req;
  2378. int i;
  2379. assert(in);
  2380. cp = buf;
  2381. for (i=15; i >= 0; --i) {
  2382. u8 byte = in->s6_addr[i];
  2383. *cp++ = "0123456789abcdef"[byte & 0x0f];
  2384. *cp++ = '.';
  2385. *cp++ = "0123456789abcdef"[byte >> 4];
  2386. *cp++ = '.';
  2387. }
  2388. assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
  2389. memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
  2390. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2391. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  2392. if (!req) return 1;
  2393. request_submit(req);
  2394. return 0;
  2395. }
  2396. /*/////////////////////////////////////////////////////////////////// */
  2397. /* Search support */
  2398. /* */
  2399. /* the libc resolver has support for searching a number of domains */
  2400. /* to find a name. If nothing else then it takes the single domain */
  2401. /* from the gethostname() call. */
  2402. /* */
  2403. /* It can also be configured via the domain and search options in a */
  2404. /* resolv.conf. */
  2405. /* */
  2406. /* The ndots option controls how many dots it takes for the resolver */
  2407. /* to decide that a name is non-local and so try a raw lookup first. */
  2408. struct search_domain {
  2409. size_t len;
  2410. struct search_domain *next;
  2411. /* the text string is appended to this structure */
  2412. };
  2413. struct search_state {
  2414. int refcount;
  2415. int ndots;
  2416. int num_domains;
  2417. struct search_domain *head;
  2418. };
  2419. static struct search_state *global_search_state = NULL;
  2420. static void
  2421. search_state_decref(struct search_state *const state) {
  2422. if (!state) return;
  2423. state->refcount--;
  2424. if (!state->refcount) {
  2425. struct search_domain *next, *dom;
  2426. for (dom = state->head; dom; dom = next) {
  2427. next = dom->next;
  2428. CLEAR(dom);
  2429. _mm_free(dom);
  2430. }
  2431. CLEAR(state);
  2432. _mm_free(state);
  2433. }
  2434. }
  2435. static struct search_state *
  2436. search_state_new(void) {
  2437. struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
  2438. if (!state) return NULL;
  2439. memset(state, 0, sizeof(struct search_state));
  2440. state->refcount = 1;
  2441. state->ndots = 1;
  2442. return state;
  2443. }
  2444. static void
  2445. search_postfix_clear(void) {
  2446. search_state_decref(global_search_state);
  2447. global_search_state = search_state_new();
  2448. }
  2449. /* exported function */
  2450. void
  2451. evdns_search_clear(void) {
  2452. search_postfix_clear();
  2453. }
  2454. static void
  2455. search_postfix_add(const char *domain) {
  2456. size_t domain_len;
  2457. struct search_domain *sdomain;
  2458. while (domain[0] == '.') domain++;
  2459. domain_len = strlen(domain);
  2460. if (!global_search_state) global_search_state = search_state_new();
  2461. if (!global_search_state) return;
  2462. global_search_state->num_domains++;
  2463. sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
  2464. if (!sdomain) return;
  2465. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  2466. sdomain->next = global_search_state->head;
  2467. sdomain->len = domain_len;
  2468. global_search_state->head = sdomain;
  2469. }
  2470. /* reverse the order of members in the postfix list. This is needed because, */
  2471. /* when parsing resolv.conf we push elements in the wrong order */
  2472. static void
  2473. search_reverse(void) {
  2474. struct search_domain *cur, *prev = NULL, *next;
  2475. cur = global_search_state->head;
  2476. while (cur) {
  2477. next = cur->next;
  2478. cur->next = prev;
  2479. prev = cur;
  2480. cur = next;
  2481. }
  2482. global_search_state->head = prev;
  2483. }
  2484. /* exported function */
  2485. void
  2486. evdns_search_add(const char *domain) {
  2487. search_postfix_add(domain);
  2488. }
  2489. /* exported function */
  2490. void
  2491. evdns_search_ndots_set(const int ndots) {
  2492. if (!global_search_state) global_search_state = search_state_new();
  2493. if (!global_search_state) return;
  2494. global_search_state->ndots = ndots;
  2495. }
  2496. static void
  2497. search_set_from_hostname(void) {
  2498. char hostname[HOST_NAME_MAX + 1], *domainname;
  2499. search_postfix_clear();
  2500. if (gethostname(hostname, sizeof(hostname))) return;
  2501. domainname = strchr(hostname, '.');
  2502. if (!domainname) return;
  2503. search_postfix_add(domainname);
  2504. }
  2505. /* warning: returns malloced string */
  2506. static char *
  2507. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  2508. const size_t base_len = strlen(base_name);
  2509. const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  2510. struct search_domain *dom;
  2511. for (dom = state->head; dom; dom = dom->next) {
  2512. if (!n--) {
  2513. /* this is the postfix we want */
  2514. /* the actual postfix string is kept at the end of the structure */
  2515. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  2516. const size_t postfix_len = dom->len;
  2517. char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
  2518. if (!newname) return NULL;
  2519. memcpy(newname, base_name, base_len);
  2520. if (need_to_append_dot) newname[base_len] = '.';
  2521. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  2522. newname[base_len + need_to_append_dot + postfix_len] = 0;
  2523. return newname;
  2524. }
  2525. }
  2526. /* we ran off the end of the list and still didn't find the requested string */
  2527. abort();
  2528. return NULL; /* unreachable; stops warnings in some compilers. */
  2529. }
  2530. static int
  2531. search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
  2532. assert(type == TYPE_A || type == TYPE_AAAA);
  2533. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  2534. global_search_state &&
  2535. global_search_state->num_domains) {
  2536. /* we have some domains to search */
  2537. struct evdns_request *req;
  2538. if (string_num_dots(name) >= global_search_state->ndots) {
  2539. req = request_new(type, name, flags, user_callback, user_arg);
  2540. if (!req) return 1;
  2541. req->search_index = -1;
  2542. } else {
  2543. char *const new_name = search_make_new(global_search_state, 0, name);
  2544. if (!new_name) return 1;
  2545. req = request_new(type, new_name, flags, user_callback, user_arg);
  2546. _mm_free(new_name);
  2547. if (!req) return 1;
  2548. req->search_index = 0;
  2549. }
  2550. req->search_origname = mm_strdup(name);
  2551. req->search_state = global_search_state;
  2552. req->search_flags = flags;
  2553. global_search_state->refcount++;
  2554. request_submit(req);
  2555. return 0;
  2556. } else {
  2557. struct evdns_request *const req = request_new(type, name, flags, user_callback, user_arg);
  2558. if (!req) return 1;
  2559. request_submit(req);
  2560. return 0;
  2561. }
  2562. }
  2563. /* this is called when a request has failed to find a name. We need to check */
  2564. /* if it is part of a search and, if so, try the next name in the list */
  2565. /* returns: */
  2566. /* 0 another request has been submitted */
  2567. /* 1 no more requests needed */
  2568. static int
  2569. search_try_next(struct evdns_request *const req) {
  2570. if (req->search_state) {
  2571. /* it is part of a search */
  2572. char *new_name;
  2573. struct evdns_request *newreq;
  2574. req->search_index++;
  2575. if (req->search_index >= req->search_state->num_domains) {
  2576. /* no more postfixes to try, however we may need to try */
  2577. /* this name without a postfix */
  2578. if (string_num_dots(req->search_origname) < req->search_state->ndots) {
  2579. /* yep, we need to try it raw */
  2580. struct evdns_request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
  2581. log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
  2582. if (newreq) {
  2583. request_submit(newreq);
  2584. return 0;
  2585. }
  2586. }
  2587. return 1;
  2588. }
  2589. new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
  2590. if (!new_name) return 1;
  2591. log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
  2592. newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
  2593. mm_free(new_name);
  2594. if (!newreq) return 1;
  2595. newreq->search_origname = req->search_origname;
  2596. req->search_origname = NULL;
  2597. newreq->search_state = req->search_state;
  2598. newreq->search_flags = req->search_flags;
  2599. newreq->search_index = req->search_index;
  2600. newreq->search_state->refcount++;
  2601. request_submit(newreq);
  2602. return 0;
  2603. }
  2604. return 1;
  2605. }
  2606. static void
  2607. search_request_finished(struct evdns_request *const req) {
  2608. if (req->search_state) {
  2609. search_state_decref(req->search_state);
  2610. req->search_state = NULL;
  2611. }
  2612. if (req->search_origname) {
  2613. mm_free(req->search_origname);
  2614. req->search_origname = NULL;
  2615. }
  2616. }
  2617. /*/////////////////////////////////////////////////////////////////// */
  2618. /* Parsing resolv.conf files */
  2619. static void
  2620. evdns_resolv_set_defaults(int flags) {
  2621. /* if the file isn't found then we assume a local resolver */
  2622. if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
  2623. if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
  2624. }
  2625. #ifndef HAVE_STRTOK_R
  2626. static char *
  2627. strtok_r(char *s, const char *delim, char **state) {
  2628. (void)state;
  2629. return strtok(s, delim);
  2630. }
  2631. #endif
  2632. /* helper version of atoi which returns -1 on error */
  2633. static int
  2634. strtoint(const char *const str) {
  2635. char *endptr;
  2636. const long r = strtol(str, &endptr, 10);
  2637. if (*endptr || r > INT_MAX) return -1;
  2638. return (int)r;
  2639. }
  2640. /* helper version of atoi that returns -1 on error and clips to bounds. */
  2641. static int
  2642. strtoint_clipped(const char *const str, int min, int max)
  2643. {
  2644. int r = strtoint(str);
  2645. if (r == -1)
  2646. return r;
  2647. else if (r<min)
  2648. return min;
  2649. else if (r>max)
  2650. return max;
  2651. else
  2652. return r;
  2653. }
  2654. /* exported function */
  2655. int
  2656. evdns_set_option(const char *option, const char *val, int flags)
  2657. {
  2658. if (!strncmp(option, "ndots:", 6)) {
  2659. const int ndots = strtoint(val);
  2660. if (ndots == -1) return -1;
  2661. if (!(flags & DNS_OPTION_SEARCH)) return 0;
  2662. log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
  2663. if (!global_search_state) global_search_state = search_state_new();
  2664. if (!global_search_state) return -1;
  2665. global_search_state->ndots = ndots;
  2666. } else if (!strncmp(option, "timeout:", 8)) {
  2667. const int timeout = strtoint(val);
  2668. if (timeout == -1) return -1;
  2669. if (!(flags & DNS_OPTION_MISC)) return 0;
  2670. log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
  2671. global_timeout.tv_sec = timeout;
  2672. } else if (!strncmp(option, "max-timeouts:", 12)) {
  2673. const int maxtimeout = strtoint_clipped(val, 1, 255);
  2674. if (maxtimeout == -1) return -1;
  2675. if (!(flags & DNS_OPTION_MISC)) return 0;
  2676. log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
  2677. maxtimeout);
  2678. global_max_nameserver_timeout = maxtimeout;
  2679. } else if (!strncmp(option, "max-inflight:", 13)) {
  2680. const int maxinflight = strtoint_clipped(val, 1, 65000);
  2681. if (maxinflight == -1) return -1;
  2682. if (!(flags & DNS_OPTION_MISC)) return 0;
  2683. log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
  2684. maxinflight);
  2685. global_max_requests_inflight = maxinflight;
  2686. } else if (!strncmp(option, "attempts:", 9)) {
  2687. int retries = strtoint(val);
  2688. if (retries == -1) return -1;
  2689. if (retries > 255) retries = 255;
  2690. if (!(flags & DNS_OPTION_MISC)) return 0;
  2691. log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
  2692. global_max_retransmits = retries;
  2693. } else if (!strncmp(option, "randomize-case:", 15)) {
  2694. int randcase = strtoint(val);
  2695. if (!(flags & DNS_OPTION_MISC)) return 0;
  2696. log(EVDNS_LOG_DEBUG, "Setting randomize_case to %d", randcase);
  2697. global_randomize_case = randcase;
  2698. }
  2699. return 0;
  2700. }
  2701. static void
  2702. resolv_conf_parse_line(char *const start, int flags) {
  2703. char *strtok_state;
  2704. static const char *const delims = " \t";
  2705. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  2706. char *const first_token = strtok_r(start, delims, &strtok_state);
  2707. if (!first_token) return;
  2708. if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
  2709. const char *const nameserver = NEXT_TOKEN;
  2710. evdns_nameserver_ip_add(nameserver);
  2711. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  2712. const char *const domain = NEXT_TOKEN;
  2713. if (domain) {
  2714. search_postfix_clear();
  2715. search_postfix_add(domain);
  2716. }
  2717. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  2718. const char *domain;
  2719. search_postfix_clear();
  2720. while ((domain = NEXT_TOKEN)) {
  2721. search_postfix_add(domain);
  2722. }
  2723. search_reverse();
  2724. } else if (!strcmp(first_token, "options")) {
  2725. const char *option;
  2726. while ((option = NEXT_TOKEN)) {
  2727. const char *val = strchr(option, ':');
  2728. evdns_set_option(option, val ? val+1 : "", flags);
  2729. }
  2730. }
  2731. #undef NEXT_TOKEN
  2732. }
  2733. /* exported function */
  2734. /* returns: */
  2735. /* 0 no errors */
  2736. /* 1 failed to open file */
  2737. /* 2 failed to stat file */
  2738. /* 3 file too large */
  2739. /* 4 out of memory */
  2740. /* 5 short read from file */
  2741. int
  2742. evdns_resolv_conf_parse(int flags, const char *const filename) {
  2743. struct stat st;
  2744. int fd, n, r;
  2745. u8 *resolv;
  2746. char *start;
  2747. int err = 0;
  2748. log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
  2749. fd = open(filename, O_RDONLY);
  2750. if (fd < 0) {
  2751. evdns_resolv_set_defaults(flags);
  2752. return 1;
  2753. }
  2754. if (fstat(fd, &st)) { err = 2; goto out1; }
  2755. if (!st.st_size) {
  2756. evdns_resolv_set_defaults(flags);
  2757. err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
  2758. goto out1;
  2759. }
  2760. if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
  2761. resolv = (u8 *) mm_malloc((size_t)st.st_size + 1);
  2762. if (!resolv) { err = 4; goto out1; }
  2763. n = 0;
  2764. while ((r = (int)read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
  2765. n += r;
  2766. if (n == st.st_size)
  2767. break;
  2768. assert(n < st.st_size);
  2769. }
  2770. if (r < 0) { err = 5; goto out2; }
  2771. resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
  2772. start = (char *) resolv;
  2773. for (;;) {
  2774. char *const newline = strchr(start, '\n');
  2775. if (!newline) {
  2776. resolv_conf_parse_line(start, flags);
  2777. break;
  2778. } else {
  2779. *newline = 0;
  2780. resolv_conf_parse_line(start, flags);
  2781. start = newline + 1;
  2782. }
  2783. }
  2784. if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
  2785. /* no nameservers were configured. */
  2786. evdns_nameserver_ip_add("127.0.0.1");
  2787. err = 6;
  2788. }
  2789. if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
  2790. search_set_from_hostname();
  2791. }
  2792. out2:
  2793. mm_free(resolv);
  2794. out1:
  2795. close(fd);
  2796. return err;
  2797. }
  2798. #ifdef WIN32
  2799. /* Add multiple nameservers from a space-or-comma-separated list. */
  2800. static int
  2801. evdns_nameserver_ip_add_line(const char *ips) {
  2802. const char *addr;
  2803. char *buf;
  2804. int r;
  2805. while (*ips) {
  2806. while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
  2807. ++ips;
  2808. addr = ips;
  2809. while (ISDIGIT(*ips) || *ips == '.' || *ips == ':' || *ips == '[' || *ips == ']')
  2810. ++ips;
  2811. buf = mm_malloc(ips-addr+1);
  2812. if (!buf) return 4;
  2813. memcpy(buf, addr, ips-addr);
  2814. buf[ips-addr] = '\0';
  2815. r = evdns_nameserver_ip_add(buf);
  2816. mm_free(buf);
  2817. if (r) return r;
  2818. }
  2819. return 0;
  2820. }
  2821. typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
  2822. /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
  2823. /* figure out what our nameservers are. */
  2824. static int
  2825. load_nameservers_with_getnetworkparams(void)
  2826. {
  2827. /* Based on MSDN examples and inspection of c-ares code. */
  2828. FIXED_INFO *fixed;
  2829. HMODULE handle = 0;
  2830. ULONG size = sizeof(FIXED_INFO);
  2831. void *buf = NULL;
  2832. int status = 0, r, added_any;
  2833. IP_ADDR_STRING *ns;
  2834. GetNetworkParams_fn_t fn;
  2835. /* XXXX Possibly, we should hardcode the location of this DLL. */
  2836. if (!(handle = LoadLibrary("iphlpapi.dll"))) {
  2837. log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
  2838. /* right now status = 0, doesn't that mean "good" - mikec */
  2839. status = -1;
  2840. goto done;
  2841. }
  2842. if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
  2843. log(EVDNS_LOG_WARN, "Could not get address of function.");
  2844. /* same as above */
  2845. status = -1;
  2846. goto done;
  2847. }
  2848. buf = mm_malloc(size);
  2849. if (!buf) { status = 4; goto done; }
  2850. fixed = buf;
  2851. r = fn(fixed, &size);
  2852. if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
  2853. status = -1;
  2854. goto done;
  2855. }
  2856. if (r != ERROR_SUCCESS) {
  2857. mm_free(buf);
  2858. buf = mm_malloc(size);
  2859. if (!buf) { status = 4; goto done; }
  2860. fixed = buf;
  2861. r = fn(fixed, &size);
  2862. if (r != ERROR_SUCCESS) {
  2863. log(EVDNS_LOG_DEBUG, "fn() failed.");
  2864. status = -1;
  2865. goto done;
  2866. }
  2867. }
  2868. assert(fixed);
  2869. added_any = 0;
  2870. ns = &(fixed->DnsServerList);
  2871. while (ns) {
  2872. r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
  2873. if (r) {
  2874. log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list, "
  2875. "error: %d; status: %d",
  2876. (ns->IpAddress.String),(int)GetLastError(), r);
  2877. status = r;
  2878. } else {
  2879. log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
  2880. added_any++;
  2881. }
  2882. ns = ns->Next;
  2883. }
  2884. if (!added_any) {
  2885. log(EVDNS_LOG_DEBUG, "No nameservers added.");
  2886. if (status == 0)
  2887. status = -1;
  2888. } else {
  2889. status = 0;
  2890. }
  2891. done:
  2892. if (buf)
  2893. mm_free(buf);
  2894. if (handle)
  2895. FreeLibrary(handle);
  2896. return status;
  2897. }
  2898. static int
  2899. config_nameserver_from_reg_key(HKEY key, const char *subkey)
  2900. {
  2901. char *buf;
  2902. DWORD bufsz = 0, type = 0;
  2903. int status = 0;
  2904. if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
  2905. != ERROR_MORE_DATA)
  2906. return -1;
  2907. if (!(buf = mm_malloc(bufsz)))
  2908. return -1;
  2909. if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
  2910. == ERROR_SUCCESS && bufsz > 1) {
  2911. status = evdns_nameserver_ip_add_line(buf);
  2912. }
  2913. mm_free(buf);
  2914. return status;
  2915. }
  2916. #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
  2917. #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
  2918. #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
  2919. static int
  2920. load_nameservers_from_registry(void)
  2921. {
  2922. int found = 0;
  2923. int r;
  2924. #define TRY(k, name) \
  2925. if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
  2926. log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
  2927. found = 1; \
  2928. } else if (!found) { \
  2929. log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
  2930. #k,#name); \
  2931. }
  2932. if (((int)GetVersion()) > 0) { /* NT */
  2933. HKEY nt_key = 0, interfaces_key = 0;
  2934. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
  2935. KEY_READ, &nt_key) != ERROR_SUCCESS) {
  2936. log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
  2937. return -1;
  2938. }
  2939. r = RegOpenKeyEx(nt_key, "Interfaces", 0,
  2940. KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
  2941. &interfaces_key);
  2942. if (r != ERROR_SUCCESS) {
  2943. log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
  2944. return -1;
  2945. }
  2946. TRY(nt_key, "NameServer");
  2947. TRY(nt_key, "DhcpNameServer");
  2948. TRY(interfaces_key, "NameServer");
  2949. TRY(interfaces_key, "DhcpNameServer");
  2950. RegCloseKey(interfaces_key);
  2951. RegCloseKey(nt_key);
  2952. } else {
  2953. HKEY win_key = 0;
  2954. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
  2955. KEY_READ, &win_key) != ERROR_SUCCESS) {
  2956. log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
  2957. return -1;
  2958. }
  2959. TRY(win_key, "NameServer");
  2960. RegCloseKey(win_key);
  2961. }
  2962. if (found == 0) {
  2963. log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
  2964. }
  2965. return found ? 0 : -1;
  2966. #undef TRY
  2967. }
  2968. int
  2969. evdns_config_windows_nameservers(void)
  2970. {
  2971. if (load_nameservers_with_getnetworkparams() == 0)
  2972. return 0;
  2973. return load_nameservers_from_registry();
  2974. }
  2975. #endif
  2976. int
  2977. evdns_init(void)
  2978. {
  2979. int res = 0;
  2980. #ifdef WIN32
  2981. evdns_config_windows_nameservers();
  2982. #else
  2983. res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  2984. #endif
  2985. return (res);
  2986. }
  2987. const char *
  2988. evdns_err_to_string(int err)
  2989. {
  2990. switch (err) {
  2991. case DNS_ERR_NONE: return "no error";
  2992. case DNS_ERR_FORMAT: return "misformatted query";
  2993. case DNS_ERR_SERVERFAILED: return "server failed";
  2994. case DNS_ERR_NOTEXIST: return "name does not exist";
  2995. case DNS_ERR_NOTIMPL: return "query not implemented";
  2996. case DNS_ERR_REFUSED: return "refused";
  2997. case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
  2998. case DNS_ERR_UNKNOWN: return "unknown";
  2999. case DNS_ERR_TIMEOUT: return "request timed out";
  3000. case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
  3001. default: return "[Unknown error code]";
  3002. }
  3003. }
  3004. void
  3005. evdns_shutdown(int fail_requests)
  3006. {
  3007. struct nameserver *server, *server_next;
  3008. struct search_domain *dom, *dom_next;
  3009. while (req_head) {
  3010. if (fail_requests)
  3011. reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
  3012. request_finished(req_head, &req_head);
  3013. }
  3014. while (req_waiting_head) {
  3015. if (fail_requests)
  3016. reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
  3017. request_finished(req_waiting_head, &req_waiting_head);
  3018. }
  3019. global_requests_inflight = global_requests_waiting = 0;
  3020. for (server = server_head; server; server = server_next) {
  3021. server_next = server->next;
  3022. if (server->socket >= 0)
  3023. CLOSE_SOCKET(server->socket);
  3024. (void) event_del(&server->event);
  3025. if (server->state == 0)
  3026. del_timeout_event(server);
  3027. CLEAR(server);
  3028. mm_free(server);
  3029. if (server_next == server_head)
  3030. break;
  3031. }
  3032. server_head = NULL;
  3033. global_good_nameservers = 0;
  3034. if (global_search_state) {
  3035. for (dom = global_search_state->head; dom; dom = dom_next) {
  3036. dom_next = dom->next;
  3037. CLEAR(dom);
  3038. mm_free(dom);
  3039. }
  3040. CLEAR(global_search_state);
  3041. mm_free(global_search_state);
  3042. global_search_state = NULL;
  3043. }
  3044. evdns_log_fn = NULL;
  3045. }
  3046. #ifdef EVDNS_MAIN
  3047. void
  3048. main_callback(int result, char type, int count, int ttl,
  3049. void *addrs, void *orig) {
  3050. char *n = (char*)orig;
  3051. int i;
  3052. for (i = 0; i < count; ++i) {
  3053. if (type == DNS_IPv4_A) {
  3054. printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
  3055. } else if (type == DNS_PTR) {
  3056. printf("%s: %s\n", n, ((char**)addrs)[i]);
  3057. }
  3058. }
  3059. if (!count) {
  3060. printf("%s: No answer (%d)\n", n, result);
  3061. }
  3062. fflush(stdout);
  3063. }
  3064. void
  3065. evdns_server_callback(struct evdns_server_request *req, void *data)
  3066. {
  3067. int i, r;
  3068. (void)data;
  3069. /* dummy; give 192.168.11.11 as an answer for all A questions,
  3070. * give foo.bar.example.com as an answer for all PTR questions. */
  3071. for (i = 0; i < req->nquestions; ++i) {
  3072. u32 ans = htonl(0xc0a80b0bUL);
  3073. if (req->questions[i]->type == EVDNS_TYPE_A &&
  3074. req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
  3075. printf(" -- replying for %s (A)\n", req->questions[i]->name);
  3076. r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
  3077. 1, &ans, 10);
  3078. if (r<0)
  3079. printf("eeep, didn't work.\n");
  3080. } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
  3081. req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
  3082. printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
  3083. r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
  3084. "foo.bar.example.com", 10);
  3085. } else {
  3086. printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
  3087. req->questions[i]->type, req->questions[i]->dns_question_class);
  3088. }
  3089. }
  3090. r = evdns_server_request_respond(req, 0);
  3091. if (r<0)
  3092. printf("eeek, couldn't send reply.\n");
  3093. }
  3094. void
  3095. logfn(int is_warn, const char *msg) {
  3096. (void) is_warn;
  3097. fprintf(stderr, "%s\n", msg);
  3098. }
  3099. int
  3100. main(int c, char **v) {
  3101. int idx;
  3102. int reverse = 0, verbose = 1, servertest = 0;
  3103. if (c<2) {
  3104. fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
  3105. fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
  3106. return 1;
  3107. }
  3108. idx = 1;
  3109. while (idx < c && v[idx][0] == '-') {
  3110. if (!strcmp(v[idx], "-x"))
  3111. reverse = 1;
  3112. else if (!strcmp(v[idx], "-v"))
  3113. verbose = 1;
  3114. else if (!strcmp(v[idx], "-servertest"))
  3115. servertest = 1;
  3116. else
  3117. fprintf(stderr, "Unknown option %s\n", v[idx]);
  3118. ++idx;
  3119. }
  3120. event_init();
  3121. if (verbose)
  3122. evdns_set_log_fn(logfn);
  3123. evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
  3124. if (servertest) {
  3125. int sock;
  3126. struct sockaddr_in my_addr;
  3127. sock = socket(PF_INET, SOCK_DGRAM, 0);
  3128. fcntl(sock, F_SETFL, O_NONBLOCK);
  3129. my_addr.sin_family = AF_INET;
  3130. my_addr.sin_port = htons(10053);
  3131. my_addr.sin_addr.s_addr = INADDR_ANY;
  3132. if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
  3133. perror("bind");
  3134. exit(1);
  3135. }
  3136. evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
  3137. }
  3138. for (; idx < c; ++idx) {
  3139. if (reverse) {
  3140. struct in_addr addr;
  3141. if (!inet_aton(v[idx], &addr)) {
  3142. fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
  3143. continue;
  3144. }
  3145. fprintf(stderr, "resolving %s...\n",v[idx]);
  3146. evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
  3147. } else {
  3148. fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
  3149. evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
  3150. }
  3151. }
  3152. fflush(stdout);
  3153. event_dispatch();
  3154. return 0;
  3155. }
  3156. #endif
  3157. /* Local Variables: */
  3158. /* tab-width: 4 */
  3159. /* c-basic-offset: 4 */
  3160. /* indent-tabs-mode: t */
  3161. /* End: */