eventdns.c 78 KB

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