eventdns.c 94 KB

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