eventdns.c 81 KB

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