eventdns.c 83 KB

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