eventdns.c 81 KB

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