evutil.c 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768
  1. /*
  2. * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * 3. The name of the author may not be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  16. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  24. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "event2/event-config.h"
  27. #include "evconfig-private.h"
  28. #ifdef _WIN32
  29. #include <winsock2.h>
  30. #include <winerror.h>
  31. #include <ws2tcpip.h>
  32. #define WIN32_LEAN_AND_MEAN
  33. #include <windows.h>
  34. #undef WIN32_LEAN_AND_MEAN
  35. #include <io.h>
  36. #include <tchar.h>
  37. #include <process.h>
  38. #undef _WIN32_WINNT
  39. /* For structs needed by GetAdaptersAddresses */
  40. #define _WIN32_WINNT 0x0501
  41. #include <iphlpapi.h>
  42. #include <netioapi.h>
  43. #endif
  44. #include <sys/types.h>
  45. #ifdef EVENT__HAVE_SYS_SOCKET_H
  46. #include <sys/socket.h>
  47. #endif
  48. #ifdef EVENT__HAVE_UNISTD_H
  49. #include <unistd.h>
  50. #endif
  51. #ifdef EVENT__HAVE_FCNTL_H
  52. #include <fcntl.h>
  53. #endif
  54. #ifdef EVENT__HAVE_STDLIB_H
  55. #include <stdlib.h>
  56. #endif
  57. #include <errno.h>
  58. #include <limits.h>
  59. #include <stdio.h>
  60. #include <string.h>
  61. #ifdef EVENT__HAVE_NETINET_IN_H
  62. #include <netinet/in.h>
  63. #endif
  64. #ifdef EVENT__HAVE_NETINET_IN6_H
  65. #error #include <netinet/in6.h>
  66. #endif
  67. #ifdef EVENT__HAVE_NETINET_TCP_H
  68. #include <netinet/tcp.h>
  69. #endif
  70. #ifdef EVENT__HAVE_ARPA_INET_H
  71. #include <arpa/inet.h>
  72. #endif
  73. #include <time.h>
  74. #include <sys/stat.h>
  75. #ifndef _WIN32
  76. #include <net/if.h>
  77. #endif
  78. #ifdef EVENT__HAVE_IFADDRS_H
  79. #include <ifaddrs.h>
  80. #endif
  81. #include "event2/util.h"
  82. #include "util-internal.h"
  83. #include "log-internal.h"
  84. #include "mm-internal.h"
  85. #include "evthread-internal.h"
  86. #include "strlcpy-internal.h"
  87. #include "ipv6-internal.h"
  88. #ifdef _WIN32
  89. #define HT_NO_CACHE_HASH_VALUES
  90. #include "ht-internal.h"
  91. #define open _open
  92. #define read _read
  93. #define close _close
  94. #ifndef fstat
  95. #define fstat _fstati64
  96. #endif
  97. #ifndef stat
  98. #define stat _stati64
  99. #endif
  100. #define mode_t int
  101. #endif
  102. int
  103. evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
  104. {
  105. int fd;
  106. #ifdef O_CLOEXEC
  107. fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
  108. if (fd >= 0 || errno == EINVAL)
  109. return fd;
  110. /* If we got an EINVAL, fall through and try without O_CLOEXEC */
  111. #endif
  112. fd = open(pathname, flags, (mode_t)mode);
  113. if (fd < 0)
  114. return -1;
  115. #if defined(FD_CLOEXEC)
  116. if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
  117. close(fd);
  118. return -1;
  119. }
  120. #endif
  121. return fd;
  122. }
  123. /**
  124. Read the contents of 'filename' into a newly allocated NUL-terminated
  125. string. Set *content_out to hold this string, and *len_out to hold its
  126. length (not including the appended NUL). If 'is_binary', open the file in
  127. binary mode.
  128. Returns 0 on success, -1 if the open fails, and -2 for all other failures.
  129. Used internally only; may go away in a future version.
  130. */
  131. int
  132. evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
  133. int is_binary)
  134. {
  135. int fd, r;
  136. struct stat st;
  137. char *mem;
  138. size_t read_so_far=0;
  139. int mode = O_RDONLY;
  140. EVUTIL_ASSERT(content_out);
  141. EVUTIL_ASSERT(len_out);
  142. *content_out = NULL;
  143. *len_out = 0;
  144. #ifdef O_BINARY
  145. if (is_binary)
  146. mode |= O_BINARY;
  147. #endif
  148. fd = evutil_open_closeonexec_(filename, mode, 0);
  149. if (fd < 0)
  150. return -1;
  151. if (fstat(fd, &st) || st.st_size < 0 ||
  152. st.st_size > EV_SSIZE_MAX-1 ) {
  153. close(fd);
  154. return -2;
  155. }
  156. mem = mm_malloc((size_t)st.st_size + 1);
  157. if (!mem) {
  158. close(fd);
  159. return -2;
  160. }
  161. read_so_far = 0;
  162. #ifdef _WIN32
  163. #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
  164. #else
  165. #define N_TO_READ(x) (x)
  166. #endif
  167. while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
  168. read_so_far += r;
  169. if (read_so_far >= (size_t)st.st_size)
  170. break;
  171. EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
  172. }
  173. close(fd);
  174. if (r < 0) {
  175. mm_free(mem);
  176. return -2;
  177. }
  178. mem[read_so_far] = 0;
  179. *len_out = read_so_far;
  180. *content_out = mem;
  181. return 0;
  182. }
  183. int
  184. evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
  185. {
  186. #ifndef _WIN32
  187. return socketpair(family, type, protocol, fd);
  188. #else
  189. return evutil_ersatz_socketpair_(family, type, protocol, fd);
  190. #endif
  191. }
  192. int
  193. evutil_ersatz_socketpair_(int family, int type, int protocol,
  194. evutil_socket_t fd[2])
  195. {
  196. /* This code is originally from Tor. Used with permission. */
  197. /* This socketpair does not work when localhost is down. So
  198. * it's really not the same thing at all. But it's close enough
  199. * for now, and really, when localhost is down sometimes, we
  200. * have other problems too.
  201. */
  202. #ifdef _WIN32
  203. #define ERR(e) WSA##e
  204. #else
  205. #define ERR(e) e
  206. #endif
  207. evutil_socket_t listener = -1;
  208. evutil_socket_t connector = -1;
  209. evutil_socket_t acceptor = -1;
  210. struct sockaddr_in listen_addr;
  211. struct sockaddr_in connect_addr;
  212. ev_socklen_t size;
  213. int saved_errno = -1;
  214. int family_test;
  215. family_test = family != AF_INET;
  216. #ifdef AF_UNIX
  217. family_test = family_test && (family != AF_UNIX);
  218. #endif
  219. if (protocol || family_test) {
  220. EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
  221. return -1;
  222. }
  223. if (!fd) {
  224. EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
  225. return -1;
  226. }
  227. listener = socket(AF_INET, type, 0);
  228. if (listener < 0)
  229. return -1;
  230. memset(&listen_addr, 0, sizeof(listen_addr));
  231. listen_addr.sin_family = AF_INET;
  232. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  233. listen_addr.sin_port = 0; /* kernel chooses port. */
  234. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  235. == -1)
  236. goto tidy_up_and_fail;
  237. if (listen(listener, 1) == -1)
  238. goto tidy_up_and_fail;
  239. connector = socket(AF_INET, type, 0);
  240. if (connector < 0)
  241. goto tidy_up_and_fail;
  242. memset(&connect_addr, 0, sizeof(connect_addr));
  243. /* We want to find out the port number to connect to. */
  244. size = sizeof(connect_addr);
  245. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  246. goto tidy_up_and_fail;
  247. if (size != sizeof (connect_addr))
  248. goto abort_tidy_up_and_fail;
  249. if (connect(connector, (struct sockaddr *) &connect_addr,
  250. sizeof(connect_addr)) == -1)
  251. goto tidy_up_and_fail;
  252. size = sizeof(listen_addr);
  253. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  254. if (acceptor < 0)
  255. goto tidy_up_and_fail;
  256. if (size != sizeof(listen_addr))
  257. goto abort_tidy_up_and_fail;
  258. /* Now check we are talking to ourself by matching port and host on the
  259. two sockets. */
  260. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  261. goto tidy_up_and_fail;
  262. if (size != sizeof (connect_addr)
  263. || listen_addr.sin_family != connect_addr.sin_family
  264. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  265. || listen_addr.sin_port != connect_addr.sin_port)
  266. goto abort_tidy_up_and_fail;
  267. evutil_closesocket(listener);
  268. fd[0] = connector;
  269. fd[1] = acceptor;
  270. return 0;
  271. abort_tidy_up_and_fail:
  272. saved_errno = ERR(ECONNABORTED);
  273. tidy_up_and_fail:
  274. if (saved_errno < 0)
  275. saved_errno = EVUTIL_SOCKET_ERROR();
  276. if (listener != -1)
  277. evutil_closesocket(listener);
  278. if (connector != -1)
  279. evutil_closesocket(connector);
  280. if (acceptor != -1)
  281. evutil_closesocket(acceptor);
  282. EVUTIL_SET_SOCKET_ERROR(saved_errno);
  283. return -1;
  284. #undef ERR
  285. }
  286. int
  287. evutil_make_socket_nonblocking(evutil_socket_t fd)
  288. {
  289. #ifdef _WIN32
  290. {
  291. unsigned long nonblocking = 1;
  292. if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
  293. event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
  294. return -1;
  295. }
  296. }
  297. #else
  298. {
  299. int flags;
  300. if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
  301. event_warn("fcntl(%d, F_GETFL)", fd);
  302. return -1;
  303. }
  304. if (!(flags & O_NONBLOCK)) {
  305. if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
  306. event_warn("fcntl(%d, F_SETFL)", fd);
  307. return -1;
  308. }
  309. }
  310. }
  311. #endif
  312. return 0;
  313. }
  314. /* Faster version of evutil_make_socket_nonblocking for internal use.
  315. *
  316. * Requires that no F_SETFL flags were previously set on the fd.
  317. */
  318. static int
  319. evutil_fast_socket_nonblocking(evutil_socket_t fd)
  320. {
  321. #ifdef _WIN32
  322. return evutil_make_socket_nonblocking(fd);
  323. #else
  324. if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
  325. event_warn("fcntl(%d, F_SETFL)", fd);
  326. return -1;
  327. }
  328. return 0;
  329. #endif
  330. }
  331. int
  332. evutil_make_listen_socket_reuseable(evutil_socket_t sock)
  333. {
  334. #if defined(SO_REUSEADDR) && !defined(_WIN32)
  335. int one = 1;
  336. /* REUSEADDR on Unix means, "don't hang on to this address after the
  337. * listener is closed." On Windows, though, it means "don't keep other
  338. * processes from binding to this address while we're using it. */
  339. return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
  340. (ev_socklen_t)sizeof(one));
  341. #else
  342. return 0;
  343. #endif
  344. }
  345. int
  346. evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
  347. {
  348. #if defined __linux__ && defined(SO_REUSEPORT)
  349. int one = 1;
  350. /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
  351. * threads) can bind to the same port if they each set the option. */
  352. return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
  353. (ev_socklen_t)sizeof(one));
  354. #else
  355. return 0;
  356. #endif
  357. }
  358. int
  359. evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
  360. {
  361. #if defined(IPV6_V6ONLY)
  362. int one = 1;
  363. return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
  364. (ev_socklen_t)sizeof(one));
  365. #endif
  366. return 0;
  367. }
  368. int
  369. evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
  370. {
  371. #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
  372. int one = 1;
  373. /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
  374. * has arrived and ready to read */
  375. return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
  376. (ev_socklen_t)sizeof(one));
  377. #endif
  378. return 0;
  379. }
  380. int
  381. evutil_make_socket_closeonexec(evutil_socket_t fd)
  382. {
  383. #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
  384. int flags;
  385. if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
  386. event_warn("fcntl(%d, F_GETFD)", fd);
  387. return -1;
  388. }
  389. if (!(flags & FD_CLOEXEC)) {
  390. if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
  391. event_warn("fcntl(%d, F_SETFD)", fd);
  392. return -1;
  393. }
  394. }
  395. #endif
  396. return 0;
  397. }
  398. /* Faster version of evutil_make_socket_closeonexec for internal use.
  399. *
  400. * Requires that no F_SETFD flags were previously set on the fd.
  401. */
  402. static int
  403. evutil_fast_socket_closeonexec(evutil_socket_t fd)
  404. {
  405. #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
  406. if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
  407. event_warn("fcntl(%d, F_SETFD)", fd);
  408. return -1;
  409. }
  410. #endif
  411. return 0;
  412. }
  413. int
  414. evutil_closesocket(evutil_socket_t sock)
  415. {
  416. #ifndef _WIN32
  417. return close(sock);
  418. #else
  419. return closesocket(sock);
  420. #endif
  421. }
  422. ev_int64_t
  423. evutil_strtoll(const char *s, char **endptr, int base)
  424. {
  425. #ifdef EVENT__HAVE_STRTOLL
  426. return (ev_int64_t)strtoll(s, endptr, base);
  427. #elif EVENT__SIZEOF_LONG == 8
  428. return (ev_int64_t)strtol(s, endptr, base);
  429. #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
  430. /* XXXX on old versions of MS APIs, we only support base
  431. * 10. */
  432. ev_int64_t r;
  433. if (base != 10)
  434. return 0;
  435. r = (ev_int64_t) _atoi64(s);
  436. while (isspace(*s))
  437. ++s;
  438. if (*s == '-')
  439. ++s;
  440. while (isdigit(*s))
  441. ++s;
  442. if (endptr)
  443. *endptr = (char*) s;
  444. return r;
  445. #elif defined(_WIN32)
  446. return (ev_int64_t) _strtoi64(s, endptr, base);
  447. #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
  448. long long r;
  449. int n;
  450. if (base != 10 && base != 16)
  451. return 0;
  452. if (base == 10) {
  453. n = sscanf(s, "%lld", &r);
  454. } else {
  455. unsigned long long ru=0;
  456. n = sscanf(s, "%llx", &ru);
  457. if (ru > EV_INT64_MAX)
  458. return 0;
  459. r = (long long) ru;
  460. }
  461. if (n != 1)
  462. return 0;
  463. while (EVUTIL_ISSPACE_(*s))
  464. ++s;
  465. if (*s == '-')
  466. ++s;
  467. if (base == 10) {
  468. while (EVUTIL_ISDIGIT_(*s))
  469. ++s;
  470. } else {
  471. while (EVUTIL_ISXDIGIT_(*s))
  472. ++s;
  473. }
  474. if (endptr)
  475. *endptr = (char*) s;
  476. return r;
  477. #else
  478. #error "I don't know how to parse 64-bit integers."
  479. #endif
  480. }
  481. #ifdef _WIN32
  482. int
  483. evutil_socket_geterror(evutil_socket_t sock)
  484. {
  485. int optval, optvallen=sizeof(optval);
  486. int err = WSAGetLastError();
  487. if (err == WSAEWOULDBLOCK && sock >= 0) {
  488. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
  489. &optvallen))
  490. return err;
  491. if (optval)
  492. return optval;
  493. }
  494. return err;
  495. }
  496. #endif
  497. /* XXX we should use an enum here. */
  498. /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
  499. int
  500. evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
  501. {
  502. int made_fd = 0;
  503. if (*fd_ptr < 0) {
  504. if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
  505. goto err;
  506. made_fd = 1;
  507. if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
  508. goto err;
  509. }
  510. }
  511. if (connect(*fd_ptr, sa, socklen) < 0) {
  512. int e = evutil_socket_geterror(*fd_ptr);
  513. if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
  514. return 0;
  515. if (EVUTIL_ERR_CONNECT_REFUSED(e))
  516. return 2;
  517. goto err;
  518. } else {
  519. return 1;
  520. }
  521. err:
  522. if (made_fd) {
  523. evutil_closesocket(*fd_ptr);
  524. *fd_ptr = -1;
  525. }
  526. return -1;
  527. }
  528. /* Check whether a socket on which we called connect() is done
  529. connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
  530. error case, set the current socket errno to the error that happened during
  531. the connect operation. */
  532. int
  533. evutil_socket_finished_connecting_(evutil_socket_t fd)
  534. {
  535. int e;
  536. ev_socklen_t elen = sizeof(e);
  537. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
  538. return -1;
  539. if (e) {
  540. if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
  541. return 0;
  542. EVUTIL_SET_SOCKET_ERROR(e);
  543. return -1;
  544. }
  545. return 1;
  546. }
  547. #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
  548. EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
  549. EVUTIL_AI_ADDRCONFIG) != \
  550. (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
  551. EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
  552. EVUTIL_AI_ADDRCONFIG)
  553. #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
  554. #endif
  555. /* We sometimes need to know whether we have an ipv4 address and whether we
  556. have an ipv6 address. If 'have_checked_interfaces', then we've already done
  557. the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
  558. If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
  559. set by evutil_check_interfaces. */
  560. static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
  561. /* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
  562. static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
  563. { return addr>>24 == 127; }
  564. /* True iff the IPv4 address 'addr', in host order, is link-local
  565. * 169.254.0.0/16 (RFC3927) */
  566. static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
  567. { return ((addr & 0xffff0000U) == 0xa9fe0000U); }
  568. /* True iff the IPv4 address 'addr', in host order, is a class D
  569. * (multiclass) address. */
  570. static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
  571. { return ((addr>>24) & 0xf0) == 0xe0; }
  572. int
  573. evutil_v4addr_is_local_(const struct in_addr *in)
  574. {
  575. const ev_uint32_t addr = ntohl(in->s_addr);
  576. return addr == INADDR_ANY ||
  577. evutil_v4addr_is_localhost(addr) ||
  578. evutil_v4addr_is_linklocal(addr) ||
  579. evutil_v4addr_is_classd(addr);
  580. }
  581. int
  582. evutil_v6addr_is_local_(const struct in6_addr *in)
  583. {
  584. static const char ZEROES[] =
  585. "\x00\x00\x00\x00\x00\x00\x00\x00"
  586. "\x00\x00\x00\x00\x00\x00\x00\x00";
  587. const unsigned char *addr = (const unsigned char *)in->s6_addr;
  588. return !memcmp(addr, ZEROES, 8) ||
  589. ((addr[0] & 0xfe) == 0xfc) ||
  590. (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
  591. (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
  592. (addr[0] == 0xff);
  593. }
  594. static void
  595. evutil_found_ifaddr(const struct sockaddr *sa)
  596. {
  597. if (sa->sa_family == AF_INET) {
  598. const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
  599. if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
  600. event_debug(("Detected an IPv4 interface"));
  601. had_ipv4_address = 1;
  602. }
  603. } else if (sa->sa_family == AF_INET6) {
  604. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
  605. if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
  606. event_debug(("Detected an IPv6 interface"));
  607. had_ipv6_address = 1;
  608. }
  609. }
  610. }
  611. #ifdef _WIN32
  612. typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
  613. ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
  614. #endif
  615. static int
  616. evutil_check_ifaddrs(void)
  617. {
  618. #if defined(EVENT__HAVE_GETIFADDRS)
  619. /* Most free Unixy systems provide getifaddrs, which gives us a linked list
  620. * of struct ifaddrs. */
  621. struct ifaddrs *ifa = NULL;
  622. const struct ifaddrs *i;
  623. if (getifaddrs(&ifa) < 0) {
  624. event_warn("Unable to call getifaddrs()");
  625. return -1;
  626. }
  627. for (i = ifa; i; i = i->ifa_next) {
  628. if (!i->ifa_addr)
  629. continue;
  630. evutil_found_ifaddr(i->ifa_addr);
  631. }
  632. freeifaddrs(ifa);
  633. return 0;
  634. #elif defined(_WIN32)
  635. /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
  636. "GetAdaptersInfo", but that's deprecated; let's just try
  637. GetAdaptersAddresses and fall back to connect+getsockname.
  638. */
  639. HMODULE lib = evutil_load_windows_system_library_(TEXT("iphlpapi.dll"));
  640. GetAdaptersAddresses_fn_t fn;
  641. ULONG size, res;
  642. IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
  643. int result = -1;
  644. #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
  645. GAA_FLAG_SKIP_MULTICAST | \
  646. GAA_FLAG_SKIP_DNS_SERVER)
  647. if (!lib)
  648. goto done;
  649. if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
  650. goto done;
  651. /* Guess how much space we need. */
  652. size = 15*1024;
  653. addresses = mm_malloc(size);
  654. if (!addresses)
  655. goto done;
  656. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  657. if (res == ERROR_BUFFER_OVERFLOW) {
  658. /* we didn't guess that we needed enough space; try again */
  659. mm_free(addresses);
  660. addresses = mm_malloc(size);
  661. if (!addresses)
  662. goto done;
  663. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  664. }
  665. if (res != NO_ERROR)
  666. goto done;
  667. for (address = addresses; address; address = address->Next) {
  668. IP_ADAPTER_UNICAST_ADDRESS *a;
  669. for (a = address->FirstUnicastAddress; a; a = a->Next) {
  670. /* Yes, it's a linked list inside a linked list */
  671. struct sockaddr *sa = a->Address.lpSockaddr;
  672. evutil_found_ifaddr(sa);
  673. }
  674. }
  675. result = 0;
  676. done:
  677. if (lib)
  678. FreeLibrary(lib);
  679. if (addresses)
  680. mm_free(addresses);
  681. return result;
  682. #else
  683. return -1;
  684. #endif
  685. }
  686. /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
  687. * the test seemed successful. */
  688. static int
  689. evutil_check_interfaces(void)
  690. {
  691. evutil_socket_t fd = -1;
  692. struct sockaddr_in sin, sin_out;
  693. struct sockaddr_in6 sin6, sin6_out;
  694. ev_socklen_t sin_out_len = sizeof(sin_out);
  695. ev_socklen_t sin6_out_len = sizeof(sin6_out);
  696. int r;
  697. if (have_checked_interfaces)
  698. return 0;
  699. /* From this point on we have done the ipv4/ipv6 interface check */
  700. have_checked_interfaces = 1;
  701. if (evutil_check_ifaddrs() == 0) {
  702. /* Use a nice sane interface, if this system has one. */
  703. return 0;
  704. }
  705. /* Ugh. There was no nice sane interface. So to check whether we have
  706. * an interface open for a given protocol, will try to make a UDP
  707. * 'connection' to a remote host on the internet. We don't actually
  708. * use it, so the address doesn't matter, but we want to pick one that
  709. * keep us from using a host- or link-local interface. */
  710. memset(&sin, 0, sizeof(sin));
  711. sin.sin_family = AF_INET;
  712. sin.sin_port = htons(53);
  713. r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
  714. EVUTIL_ASSERT(r);
  715. memset(&sin6, 0, sizeof(sin6));
  716. sin6.sin6_family = AF_INET6;
  717. sin6.sin6_port = htons(53);
  718. r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
  719. EVUTIL_ASSERT(r);
  720. memset(&sin_out, 0, sizeof(sin_out));
  721. memset(&sin6_out, 0, sizeof(sin6_out));
  722. /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
  723. if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
  724. connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
  725. getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
  726. /* We might have an IPv4 interface. */
  727. evutil_found_ifaddr((struct sockaddr*) &sin_out);
  728. }
  729. if (fd >= 0)
  730. evutil_closesocket(fd);
  731. if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
  732. connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
  733. getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
  734. /* We might have an IPv6 interface. */
  735. evutil_found_ifaddr((struct sockaddr*) &sin6_out);
  736. }
  737. if (fd >= 0)
  738. evutil_closesocket(fd);
  739. return 0;
  740. }
  741. /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
  742. * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
  743. * it, and we should trust what they said.
  744. **/
  745. #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
  746. /* Helper: construct a new addrinfo containing the socket address in
  747. * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
  748. * socktype and protocol info from hints. If they weren't set, then
  749. * allocate both a TCP and a UDP addrinfo.
  750. */
  751. struct evutil_addrinfo *
  752. evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
  753. const struct evutil_addrinfo *hints)
  754. {
  755. struct evutil_addrinfo *res;
  756. EVUTIL_ASSERT(hints);
  757. if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
  758. /* Indecisive user! Give them a UDP and a TCP. */
  759. struct evutil_addrinfo *r1, *r2;
  760. struct evutil_addrinfo tmp;
  761. memcpy(&tmp, hints, sizeof(tmp));
  762. tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
  763. r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
  764. if (!r1)
  765. return NULL;
  766. tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
  767. r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
  768. if (!r2) {
  769. evutil_freeaddrinfo(r1);
  770. return NULL;
  771. }
  772. r1->ai_next = r2;
  773. return r1;
  774. }
  775. /* We're going to allocate extra space to hold the sockaddr. */
  776. res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
  777. if (!res)
  778. return NULL;
  779. res->ai_addr = (struct sockaddr*)
  780. (((char*)res) + sizeof(struct evutil_addrinfo));
  781. memcpy(res->ai_addr, sa, socklen);
  782. res->ai_addrlen = socklen;
  783. res->ai_family = sa->sa_family; /* Same or not? XXX */
  784. res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
  785. res->ai_socktype = hints->ai_socktype;
  786. res->ai_protocol = hints->ai_protocol;
  787. return res;
  788. }
  789. /* Append the addrinfo 'append' to the end of 'first', and return the start of
  790. * the list. Either element can be NULL, in which case we return the element
  791. * that is not NULL. */
  792. struct evutil_addrinfo *
  793. evutil_addrinfo_append_(struct evutil_addrinfo *first,
  794. struct evutil_addrinfo *append)
  795. {
  796. struct evutil_addrinfo *ai = first;
  797. if (!ai)
  798. return append;
  799. while (ai->ai_next)
  800. ai = ai->ai_next;
  801. ai->ai_next = append;
  802. return first;
  803. }
  804. static int
  805. parse_numeric_servname(const char *servname)
  806. {
  807. int n;
  808. char *endptr=NULL;
  809. n = (int) strtol(servname, &endptr, 10);
  810. if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
  811. return n;
  812. else
  813. return -1;
  814. }
  815. /** Parse a service name in 'servname', which can be a decimal port.
  816. * Return the port number, or -1 on error.
  817. */
  818. static int
  819. evutil_parse_servname(const char *servname, const char *protocol,
  820. const struct evutil_addrinfo *hints)
  821. {
  822. int n = parse_numeric_servname(servname);
  823. if (n>=0)
  824. return n;
  825. #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
  826. if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
  827. struct servent *ent = getservbyname(servname, protocol);
  828. if (ent) {
  829. return ntohs(ent->s_port);
  830. }
  831. }
  832. #endif
  833. return -1;
  834. }
  835. /* Return a string corresponding to a protocol number that we can pass to
  836. * getservyname. */
  837. static const char *
  838. evutil_unparse_protoname(int proto)
  839. {
  840. switch (proto) {
  841. case 0:
  842. return NULL;
  843. case IPPROTO_TCP:
  844. return "tcp";
  845. case IPPROTO_UDP:
  846. return "udp";
  847. #ifdef IPPROTO_SCTP
  848. case IPPROTO_SCTP:
  849. return "sctp";
  850. #endif
  851. default:
  852. #ifdef EVENT__HAVE_GETPROTOBYNUMBER
  853. {
  854. struct protoent *ent = getprotobynumber(proto);
  855. if (ent)
  856. return ent->p_name;
  857. }
  858. #endif
  859. return NULL;
  860. }
  861. }
  862. static void
  863. evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
  864. {
  865. /* If we can guess the protocol from the socktype, do so. */
  866. if (!hints->ai_protocol && hints->ai_socktype) {
  867. if (hints->ai_socktype == SOCK_DGRAM)
  868. hints->ai_protocol = IPPROTO_UDP;
  869. else if (hints->ai_socktype == SOCK_STREAM)
  870. hints->ai_protocol = IPPROTO_TCP;
  871. }
  872. /* Set the socktype if it isn't set. */
  873. if (!hints->ai_socktype && hints->ai_protocol) {
  874. if (hints->ai_protocol == IPPROTO_UDP)
  875. hints->ai_socktype = SOCK_DGRAM;
  876. else if (hints->ai_protocol == IPPROTO_TCP)
  877. hints->ai_socktype = SOCK_STREAM;
  878. #ifdef IPPROTO_SCTP
  879. else if (hints->ai_protocol == IPPROTO_SCTP)
  880. hints->ai_socktype = SOCK_STREAM;
  881. #endif
  882. }
  883. }
  884. #if AF_UNSPEC != PF_UNSPEC
  885. #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
  886. #endif
  887. /** Implements the part of looking up hosts by name that's common to both
  888. * the blocking and nonblocking resolver:
  889. * - Adjust 'hints' to have a reasonable socktype and protocol.
  890. * - Look up the port based on 'servname', and store it in *portnum,
  891. * - Handle the nodename==NULL case
  892. * - Handle some invalid arguments cases.
  893. * - Handle the cases where nodename is an IPv4 or IPv6 address.
  894. *
  895. * If we need the resolver to look up the hostname, we return
  896. * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
  897. * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
  898. * set *res as getaddrinfo would.
  899. */
  900. int
  901. evutil_getaddrinfo_common_(const char *nodename, const char *servname,
  902. struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
  903. {
  904. int port = 0;
  905. unsigned int if_index;
  906. const char *pname;
  907. if (nodename == NULL && servname == NULL)
  908. return EVUTIL_EAI_NONAME;
  909. /* We only understand 3 families */
  910. if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
  911. hints->ai_family != PF_INET6)
  912. return EVUTIL_EAI_FAMILY;
  913. evutil_getaddrinfo_infer_protocols(hints);
  914. /* Look up the port number and protocol, if possible. */
  915. pname = evutil_unparse_protoname(hints->ai_protocol);
  916. if (servname) {
  917. /* XXXX We could look at the protocol we got back from
  918. * getservbyname, but it doesn't seem too useful. */
  919. port = evutil_parse_servname(servname, pname, hints);
  920. if (port < 0) {
  921. return EVUTIL_EAI_NONAME;
  922. }
  923. }
  924. /* If we have no node name, then we're supposed to bind to 'any' and
  925. * connect to localhost. */
  926. if (nodename == NULL) {
  927. struct evutil_addrinfo *res4=NULL, *res6=NULL;
  928. if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
  929. struct sockaddr_in6 sin6;
  930. memset(&sin6, 0, sizeof(sin6));
  931. sin6.sin6_family = AF_INET6;
  932. sin6.sin6_port = htons(port);
  933. if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
  934. /* Bind to :: */
  935. } else {
  936. /* connect to ::1 */
  937. sin6.sin6_addr.s6_addr[15] = 1;
  938. }
  939. res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
  940. sizeof(sin6), hints);
  941. if (!res6)
  942. return EVUTIL_EAI_MEMORY;
  943. }
  944. if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
  945. struct sockaddr_in sin;
  946. memset(&sin, 0, sizeof(sin));
  947. sin.sin_family = AF_INET;
  948. sin.sin_port = htons(port);
  949. if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
  950. /* Bind to 0.0.0.0 */
  951. } else {
  952. /* connect to 127.0.0.1 */
  953. sin.sin_addr.s_addr = htonl(0x7f000001);
  954. }
  955. res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
  956. sizeof(sin), hints);
  957. if (!res4) {
  958. if (res6)
  959. evutil_freeaddrinfo(res6);
  960. return EVUTIL_EAI_MEMORY;
  961. }
  962. }
  963. *res = evutil_addrinfo_append_(res4, res6);
  964. return 0;
  965. }
  966. /* If we can, we should try to parse the hostname without resolving
  967. * it. */
  968. /* Try ipv6. */
  969. if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
  970. struct sockaddr_in6 sin6;
  971. memset(&sin6, 0, sizeof(sin6));
  972. if (1 == evutil_inet_pton_scope(
  973. AF_INET6, nodename, &sin6.sin6_addr, &if_index)) {
  974. /* Got an ipv6 address. */
  975. sin6.sin6_family = AF_INET6;
  976. sin6.sin6_port = htons(port);
  977. sin6.sin6_scope_id = if_index;
  978. *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
  979. sizeof(sin6), hints);
  980. if (!*res)
  981. return EVUTIL_EAI_MEMORY;
  982. return 0;
  983. }
  984. }
  985. /* Try ipv4. */
  986. if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
  987. struct sockaddr_in sin;
  988. memset(&sin, 0, sizeof(sin));
  989. if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
  990. /* Got an ipv4 address. */
  991. sin.sin_family = AF_INET;
  992. sin.sin_port = htons(port);
  993. *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
  994. sizeof(sin), hints);
  995. if (!*res)
  996. return EVUTIL_EAI_MEMORY;
  997. return 0;
  998. }
  999. }
  1000. /* If we have reached this point, we definitely need to do a DNS
  1001. * lookup. */
  1002. if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
  1003. /* If we're not allowed to do one, then say so. */
  1004. return EVUTIL_EAI_NONAME;
  1005. }
  1006. *portnum = port;
  1007. return EVUTIL_EAI_NEED_RESOLVE;
  1008. }
  1009. #ifdef EVENT__HAVE_GETADDRINFO
  1010. #define USE_NATIVE_GETADDRINFO
  1011. #endif
  1012. #ifdef USE_NATIVE_GETADDRINFO
  1013. /* A mask of all the flags that we declare, so we can clear them before calling
  1014. * the native getaddrinfo */
  1015. static const unsigned int ALL_NONNATIVE_AI_FLAGS =
  1016. #ifndef AI_PASSIVE
  1017. EVUTIL_AI_PASSIVE |
  1018. #endif
  1019. #ifndef AI_CANONNAME
  1020. EVUTIL_AI_CANONNAME |
  1021. #endif
  1022. #ifndef AI_NUMERICHOST
  1023. EVUTIL_AI_NUMERICHOST |
  1024. #endif
  1025. #ifndef AI_NUMERICSERV
  1026. EVUTIL_AI_NUMERICSERV |
  1027. #endif
  1028. #ifndef AI_ADDRCONFIG
  1029. EVUTIL_AI_ADDRCONFIG |
  1030. #endif
  1031. #ifndef AI_ALL
  1032. EVUTIL_AI_ALL |
  1033. #endif
  1034. #ifndef AI_V4MAPPED
  1035. EVUTIL_AI_V4MAPPED |
  1036. #endif
  1037. EVUTIL_AI_LIBEVENT_ALLOCATED;
  1038. static const unsigned int ALL_NATIVE_AI_FLAGS =
  1039. #ifdef AI_PASSIVE
  1040. AI_PASSIVE |
  1041. #endif
  1042. #ifdef AI_CANONNAME
  1043. AI_CANONNAME |
  1044. #endif
  1045. #ifdef AI_NUMERICHOST
  1046. AI_NUMERICHOST |
  1047. #endif
  1048. #ifdef AI_NUMERICSERV
  1049. AI_NUMERICSERV |
  1050. #endif
  1051. #ifdef AI_ADDRCONFIG
  1052. AI_ADDRCONFIG |
  1053. #endif
  1054. #ifdef AI_ALL
  1055. AI_ALL |
  1056. #endif
  1057. #ifdef AI_V4MAPPED
  1058. AI_V4MAPPED |
  1059. #endif
  1060. 0;
  1061. #endif
  1062. #ifndef USE_NATIVE_GETADDRINFO
  1063. /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
  1064. * a struct hostent.
  1065. */
  1066. static struct evutil_addrinfo *
  1067. addrinfo_from_hostent(const struct hostent *ent,
  1068. int port, const struct evutil_addrinfo *hints)
  1069. {
  1070. int i;
  1071. struct sockaddr_in sin;
  1072. struct sockaddr_in6 sin6;
  1073. struct sockaddr *sa;
  1074. int socklen;
  1075. struct evutil_addrinfo *res=NULL, *ai;
  1076. void *addrp;
  1077. if (ent->h_addrtype == PF_INET) {
  1078. memset(&sin, 0, sizeof(sin));
  1079. sin.sin_family = AF_INET;
  1080. sin.sin_port = htons(port);
  1081. sa = (struct sockaddr *)&sin;
  1082. socklen = sizeof(struct sockaddr_in);
  1083. addrp = &sin.sin_addr;
  1084. if (ent->h_length != sizeof(sin.sin_addr)) {
  1085. event_warnx("Weird h_length from gethostbyname");
  1086. return NULL;
  1087. }
  1088. } else if (ent->h_addrtype == PF_INET6) {
  1089. memset(&sin6, 0, sizeof(sin6));
  1090. sin6.sin6_family = AF_INET6;
  1091. sin6.sin6_port = htons(port);
  1092. sa = (struct sockaddr *)&sin6;
  1093. socklen = sizeof(struct sockaddr_in6);
  1094. addrp = &sin6.sin6_addr;
  1095. if (ent->h_length != sizeof(sin6.sin6_addr)) {
  1096. event_warnx("Weird h_length from gethostbyname");
  1097. return NULL;
  1098. }
  1099. } else
  1100. return NULL;
  1101. for (i = 0; ent->h_addr_list[i]; ++i) {
  1102. memcpy(addrp, ent->h_addr_list[i], ent->h_length);
  1103. ai = evutil_new_addrinfo_(sa, socklen, hints);
  1104. if (!ai) {
  1105. evutil_freeaddrinfo(res);
  1106. return NULL;
  1107. }
  1108. res = evutil_addrinfo_append_(res, ai);
  1109. }
  1110. if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
  1111. res->ai_canonname = mm_strdup(ent->h_name);
  1112. if (res->ai_canonname == NULL) {
  1113. evutil_freeaddrinfo(res);
  1114. return NULL;
  1115. }
  1116. }
  1117. return res;
  1118. }
  1119. #endif
  1120. /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
  1121. * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
  1122. * that we'll only get addresses we could maybe connect to.
  1123. */
  1124. void
  1125. evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
  1126. {
  1127. if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
  1128. return;
  1129. if (hints->ai_family != PF_UNSPEC)
  1130. return;
  1131. evutil_check_interfaces();
  1132. if (had_ipv4_address && !had_ipv6_address) {
  1133. hints->ai_family = PF_INET;
  1134. } else if (!had_ipv4_address && had_ipv6_address) {
  1135. hints->ai_family = PF_INET6;
  1136. }
  1137. }
  1138. #ifdef USE_NATIVE_GETADDRINFO
  1139. static int need_numeric_port_hack_=0;
  1140. static int need_socktype_protocol_hack_=0;
  1141. #ifdef WIN32
  1142. static int tested_for_getaddrinfo_hacks=1;
  1143. #else
  1144. static int tested_for_getaddrinfo_hacks=0;
  1145. #endif
  1146. /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
  1147. giving a numeric port without giving an ai_socktype was verboten.
  1148. We test for this so we can apply an appropriate workaround. If it
  1149. turns out that the bug is present, then:
  1150. - If nodename==NULL and servname is numeric, we build an answer
  1151. ourselves using evutil_getaddrinfo_common_().
  1152. - If nodename!=NULL and servname is numeric, then we set
  1153. servname=NULL when calling getaddrinfo, and post-process the
  1154. result to set the ports on it.
  1155. We test for this bug at runtime, since otherwise we can't have the
  1156. same binary run on multiple BSD versions.
  1157. - Some versions of Solaris believe that it's nice to leave to protocol
  1158. field set to 0. We test for this so we can apply an appropriate
  1159. workaround.
  1160. */
  1161. static struct evutil_addrinfo *ai_find_protocol(struct evutil_addrinfo *ai)
  1162. {
  1163. while (ai) {
  1164. if (ai->ai_protocol)
  1165. return ai;
  1166. ai = ai->ai_next;
  1167. }
  1168. return NULL;
  1169. }
  1170. static void
  1171. test_for_getaddrinfo_hacks(void)
  1172. {
  1173. int r, r2;
  1174. struct evutil_addrinfo *ai=NULL, *ai2=NULL, *ai3=NULL;
  1175. struct evutil_addrinfo hints;
  1176. memset(&hints,0,sizeof(hints));
  1177. hints.ai_family = PF_UNSPEC;
  1178. hints.ai_flags =
  1179. #ifdef AI_NUMERICHOST
  1180. AI_NUMERICHOST |
  1181. #endif
  1182. #ifdef AI_NUMERICSERV
  1183. AI_NUMERICSERV |
  1184. #endif
  1185. 0;
  1186. r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
  1187. getaddrinfo("1.2.3.4", NULL, &hints, &ai3);
  1188. hints.ai_socktype = SOCK_STREAM;
  1189. r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
  1190. if (r2 == 0 && r != 0) {
  1191. need_numeric_port_hack_=1;
  1192. }
  1193. if (!ai_find_protocol(ai2) || !ai_find_protocol(ai3)) {
  1194. need_socktype_protocol_hack_=1;
  1195. }
  1196. if (ai)
  1197. freeaddrinfo(ai);
  1198. if (ai2)
  1199. freeaddrinfo(ai2);
  1200. if (ai3)
  1201. freeaddrinfo(ai3);
  1202. tested_for_getaddrinfo_hacks=1;
  1203. }
  1204. static inline int
  1205. need_numeric_port_hack(void)
  1206. {
  1207. if (!tested_for_getaddrinfo_hacks)
  1208. test_for_getaddrinfo_hacks();
  1209. return need_numeric_port_hack_;
  1210. }
  1211. static inline int
  1212. need_socktype_protocol_hack(void)
  1213. {
  1214. if (!tested_for_getaddrinfo_hacks)
  1215. test_for_getaddrinfo_hacks();
  1216. return need_socktype_protocol_hack_;
  1217. }
  1218. static void
  1219. apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
  1220. {
  1221. /* Now we run through the list and set the ports on all of the
  1222. * results where ports would make sense. */
  1223. for ( ; *ai; ai = &(*ai)->ai_next) {
  1224. struct sockaddr *sa = (*ai)->ai_addr;
  1225. if (sa && sa->sa_family == AF_INET) {
  1226. struct sockaddr_in *sin = (struct sockaddr_in*)sa;
  1227. sin->sin_port = htons(port);
  1228. } else if (sa && sa->sa_family == AF_INET6) {
  1229. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
  1230. sin6->sin6_port = htons(port);
  1231. } else {
  1232. /* A numeric port makes no sense here; remove this one
  1233. * from the list. */
  1234. struct evutil_addrinfo *victim = *ai;
  1235. *ai = victim->ai_next;
  1236. victim->ai_next = NULL;
  1237. freeaddrinfo(victim);
  1238. }
  1239. }
  1240. }
  1241. static int
  1242. apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
  1243. {
  1244. struct evutil_addrinfo *ai_new;
  1245. for (; ai; ai = ai->ai_next) {
  1246. evutil_getaddrinfo_infer_protocols(ai);
  1247. if (ai->ai_socktype || ai->ai_protocol)
  1248. continue;
  1249. ai_new = mm_malloc(sizeof(*ai_new));
  1250. if (!ai_new)
  1251. return -1;
  1252. memcpy(ai_new, ai, sizeof(*ai_new));
  1253. ai->ai_socktype = SOCK_STREAM;
  1254. ai->ai_protocol = IPPROTO_TCP;
  1255. ai_new->ai_socktype = SOCK_DGRAM;
  1256. ai_new->ai_protocol = IPPROTO_UDP;
  1257. ai_new->ai_next = ai->ai_next;
  1258. ai->ai_next = ai_new;
  1259. }
  1260. return 0;
  1261. }
  1262. #endif
  1263. int
  1264. evutil_getaddrinfo(const char *nodename, const char *servname,
  1265. const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
  1266. {
  1267. #ifdef USE_NATIVE_GETADDRINFO
  1268. struct evutil_addrinfo hints;
  1269. int portnum=-1, need_np_hack, err;
  1270. if (hints_in) {
  1271. memcpy(&hints, hints_in, sizeof(hints));
  1272. } else {
  1273. memset(&hints, 0, sizeof(hints));
  1274. hints.ai_family = PF_UNSPEC;
  1275. }
  1276. #ifndef AI_ADDRCONFIG
  1277. /* Not every system has AI_ADDRCONFIG, so fake it. */
  1278. if (hints.ai_family == PF_UNSPEC &&
  1279. (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
  1280. evutil_adjust_hints_for_addrconfig_(&hints);
  1281. }
  1282. #endif
  1283. #ifndef AI_NUMERICSERV
  1284. /* Not every system has AI_NUMERICSERV, so fake it. */
  1285. if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
  1286. if (servname && parse_numeric_servname(servname)<0)
  1287. return EVUTIL_EAI_NONAME;
  1288. }
  1289. #endif
  1290. /* Enough operating systems handle enough common non-resolve
  1291. * cases here weirdly enough that we are better off just
  1292. * overriding them. For example:
  1293. *
  1294. * - Windows doesn't like to infer the protocol from the
  1295. * socket type, or fill in socket or protocol types much at
  1296. * all. It also seems to do its own broken implicit
  1297. * always-on version of AI_ADDRCONFIG that keeps it from
  1298. * ever resolving even a literal IPv6 address when
  1299. * ai_addrtype is PF_UNSPEC.
  1300. */
  1301. #ifdef _WIN32
  1302. {
  1303. int tmp_port;
  1304. err = evutil_getaddrinfo_common_(nodename,servname,&hints,
  1305. res, &tmp_port);
  1306. if (err == 0 ||
  1307. err == EVUTIL_EAI_MEMORY ||
  1308. err == EVUTIL_EAI_NONAME)
  1309. return err;
  1310. /* If we make it here, the system getaddrinfo can
  1311. * have a crack at it. */
  1312. }
  1313. #endif
  1314. /* See documentation for need_numeric_port_hack above.*/
  1315. need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
  1316. && ((portnum=parse_numeric_servname(servname)) >= 0);
  1317. if (need_np_hack) {
  1318. if (!nodename)
  1319. return evutil_getaddrinfo_common_(
  1320. NULL,servname,&hints, res, &portnum);
  1321. servname = NULL;
  1322. }
  1323. if (need_socktype_protocol_hack()) {
  1324. evutil_getaddrinfo_infer_protocols(&hints);
  1325. }
  1326. /* Make sure that we didn't actually steal any AI_FLAGS values that
  1327. * the system is using. (This is a constant expression, and should ge
  1328. * optimized out.)
  1329. *
  1330. * XXXX Turn this into a compile-time failure rather than a run-time
  1331. * failure.
  1332. */
  1333. EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
  1334. /* Clear any flags that only libevent understands. */
  1335. hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
  1336. err = getaddrinfo(nodename, servname, &hints, res);
  1337. if (need_np_hack)
  1338. apply_numeric_port_hack(portnum, res);
  1339. if (need_socktype_protocol_hack()) {
  1340. if (apply_socktype_protocol_hack(*res) < 0) {
  1341. evutil_freeaddrinfo(*res);
  1342. *res = NULL;
  1343. return EVUTIL_EAI_MEMORY;
  1344. }
  1345. }
  1346. return err;
  1347. #else
  1348. int port=0, err;
  1349. struct hostent *ent = NULL;
  1350. struct evutil_addrinfo hints;
  1351. if (hints_in) {
  1352. memcpy(&hints, hints_in, sizeof(hints));
  1353. } else {
  1354. memset(&hints, 0, sizeof(hints));
  1355. hints.ai_family = PF_UNSPEC;
  1356. }
  1357. evutil_adjust_hints_for_addrconfig_(&hints);
  1358. err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
  1359. if (err != EVUTIL_EAI_NEED_RESOLVE) {
  1360. /* We either succeeded or failed. No need to continue */
  1361. return err;
  1362. }
  1363. err = 0;
  1364. /* Use any of the various gethostbyname_r variants as available. */
  1365. {
  1366. #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
  1367. /* This one is what glibc provides. */
  1368. char buf[2048];
  1369. struct hostent hostent;
  1370. int r;
  1371. r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
  1372. &err);
  1373. #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
  1374. char buf[2048];
  1375. struct hostent hostent;
  1376. ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
  1377. &err);
  1378. #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
  1379. struct hostent_data data;
  1380. struct hostent hostent;
  1381. memset(&data, 0, sizeof(data));
  1382. err = gethostbyname_r(nodename, &hostent, &data);
  1383. ent = err ? NULL : &hostent;
  1384. #else
  1385. /* fall back to gethostbyname. */
  1386. /* XXXX This needs a lock everywhere but Windows. */
  1387. ent = gethostbyname(nodename);
  1388. #ifdef _WIN32
  1389. err = WSAGetLastError();
  1390. #else
  1391. err = h_errno;
  1392. #endif
  1393. #endif
  1394. /* Now we have either ent or err set. */
  1395. if (!ent) {
  1396. /* XXX is this right for windows ? */
  1397. switch (err) {
  1398. case TRY_AGAIN:
  1399. return EVUTIL_EAI_AGAIN;
  1400. case NO_RECOVERY:
  1401. default:
  1402. return EVUTIL_EAI_FAIL;
  1403. case HOST_NOT_FOUND:
  1404. return EVUTIL_EAI_NONAME;
  1405. case NO_ADDRESS:
  1406. #if NO_DATA != NO_ADDRESS
  1407. case NO_DATA:
  1408. #endif
  1409. return EVUTIL_EAI_NODATA;
  1410. }
  1411. }
  1412. if (ent->h_addrtype != hints.ai_family &&
  1413. hints.ai_family != PF_UNSPEC) {
  1414. /* This wasn't the type we were hoping for. Too bad
  1415. * we never had a chance to ask gethostbyname for what
  1416. * we wanted. */
  1417. return EVUTIL_EAI_NONAME;
  1418. }
  1419. /* Make sure we got _some_ answers. */
  1420. if (ent->h_length == 0)
  1421. return EVUTIL_EAI_NODATA;
  1422. /* If we got an address type we don't know how to make a
  1423. sockaddr for, give up. */
  1424. if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
  1425. return EVUTIL_EAI_FAMILY;
  1426. *res = addrinfo_from_hostent(ent, port, &hints);
  1427. if (! *res)
  1428. return EVUTIL_EAI_MEMORY;
  1429. }
  1430. return 0;
  1431. #endif
  1432. }
  1433. void
  1434. evutil_freeaddrinfo(struct evutil_addrinfo *ai)
  1435. {
  1436. #ifdef EVENT__HAVE_GETADDRINFO
  1437. if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
  1438. freeaddrinfo(ai);
  1439. return;
  1440. }
  1441. #endif
  1442. while (ai) {
  1443. struct evutil_addrinfo *next = ai->ai_next;
  1444. if (ai->ai_canonname)
  1445. mm_free(ai->ai_canonname);
  1446. mm_free(ai);
  1447. ai = next;
  1448. }
  1449. }
  1450. static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
  1451. static evdns_getaddrinfo_cancel_fn evdns_getaddrinfo_cancel_impl = NULL;
  1452. void
  1453. evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
  1454. {
  1455. if (!evdns_getaddrinfo_impl)
  1456. evdns_getaddrinfo_impl = fn;
  1457. }
  1458. void
  1459. evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn)
  1460. {
  1461. if (!evdns_getaddrinfo_cancel_impl)
  1462. evdns_getaddrinfo_cancel_impl = fn;
  1463. }
  1464. /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
  1465. * otherwise do a blocking resolve and pass the result to the callback in the
  1466. * way that evdns_getaddrinfo would.
  1467. */
  1468. struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
  1469. struct evdns_base *dns_base,
  1470. const char *nodename, const char *servname,
  1471. const struct evutil_addrinfo *hints_in,
  1472. void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
  1473. {
  1474. if (dns_base && evdns_getaddrinfo_impl) {
  1475. return evdns_getaddrinfo_impl(
  1476. dns_base, nodename, servname, hints_in, cb, arg);
  1477. } else {
  1478. struct evutil_addrinfo *ai=NULL;
  1479. int err;
  1480. err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
  1481. cb(err, ai, arg);
  1482. return NULL;
  1483. }
  1484. }
  1485. void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data)
  1486. {
  1487. if (evdns_getaddrinfo_cancel_impl && data) {
  1488. evdns_getaddrinfo_cancel_impl(data);
  1489. }
  1490. }
  1491. const char *
  1492. evutil_gai_strerror(int err)
  1493. {
  1494. /* As a sneaky side-benefit, this case statement will get most
  1495. * compilers to tell us if any of the error codes we defined
  1496. * conflict with the platform's native error codes. */
  1497. switch (err) {
  1498. case EVUTIL_EAI_CANCEL:
  1499. return "Request canceled";
  1500. case 0:
  1501. return "No error";
  1502. case EVUTIL_EAI_ADDRFAMILY:
  1503. return "address family for nodename not supported";
  1504. case EVUTIL_EAI_AGAIN:
  1505. return "temporary failure in name resolution";
  1506. case EVUTIL_EAI_BADFLAGS:
  1507. return "invalid value for ai_flags";
  1508. case EVUTIL_EAI_FAIL:
  1509. return "non-recoverable failure in name resolution";
  1510. case EVUTIL_EAI_FAMILY:
  1511. return "ai_family not supported";
  1512. case EVUTIL_EAI_MEMORY:
  1513. return "memory allocation failure";
  1514. case EVUTIL_EAI_NODATA:
  1515. return "no address associated with nodename";
  1516. case EVUTIL_EAI_NONAME:
  1517. return "nodename nor servname provided, or not known";
  1518. case EVUTIL_EAI_SERVICE:
  1519. return "servname not supported for ai_socktype";
  1520. case EVUTIL_EAI_SOCKTYPE:
  1521. return "ai_socktype not supported";
  1522. case EVUTIL_EAI_SYSTEM:
  1523. return "system error";
  1524. default:
  1525. #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
  1526. return gai_strerrorA(err);
  1527. #elif defined(USE_NATIVE_GETADDRINFO)
  1528. return gai_strerror(err);
  1529. #else
  1530. return "Unknown error code";
  1531. #endif
  1532. }
  1533. }
  1534. #ifdef _WIN32
  1535. /* destructively remove a trailing line terminator from s */
  1536. static void
  1537. chomp (char *s)
  1538. {
  1539. size_t len;
  1540. if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
  1541. s[--len] = 0;
  1542. if (len > 0 && s[len - 1] == '\r')
  1543. s[--len] = 0;
  1544. }
  1545. }
  1546. /* FormatMessage returns allocated strings, but evutil_socket_error_to_string
  1547. * is supposed to return a string which is good indefinitely without having
  1548. * to be freed. To make this work without leaking memory, we cache the
  1549. * string the first time FormatMessage is called on a particular error
  1550. * code, and then return the cached string on subsequent calls with the
  1551. * same code. The strings aren't freed until libevent_global_shutdown
  1552. * (or never). We use a linked list to cache the errors, because we
  1553. * only expect there to be a few dozen, and that should be fast enough.
  1554. */
  1555. struct cached_sock_errs_entry {
  1556. HT_ENTRY(cached_sock_errs_entry) node;
  1557. DWORD code;
  1558. char *msg; /* allocated with LocalAlloc; free with LocalFree */
  1559. };
  1560. static inline unsigned
  1561. hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
  1562. {
  1563. /* Use Murmur3's 32-bit finalizer as an integer hash function */
  1564. DWORD h = e->code;
  1565. h ^= h >> 16;
  1566. h *= 0x85ebca6b;
  1567. h ^= h >> 13;
  1568. h *= 0xc2b2ae35;
  1569. h ^= h >> 16;
  1570. return h;
  1571. }
  1572. static inline int
  1573. eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
  1574. const struct cached_sock_errs_entry *b)
  1575. {
  1576. return a->code == b->code;
  1577. }
  1578. #ifndef EVENT__DISABLE_THREAD_SUPPORT
  1579. static void *windows_socket_errors_lock_ = NULL;
  1580. #endif
  1581. static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
  1582. windows_socket_errors = HT_INITIALIZER();
  1583. HT_PROTOTYPE(cached_sock_errs_map,
  1584. cached_sock_errs_entry,
  1585. node,
  1586. hash_cached_sock_errs,
  1587. eq_cached_sock_errs);
  1588. HT_GENERATE(cached_sock_errs_map,
  1589. cached_sock_errs_entry,
  1590. node,
  1591. hash_cached_sock_errs,
  1592. eq_cached_sock_errs,
  1593. 0.5,
  1594. mm_malloc,
  1595. mm_realloc,
  1596. mm_free);
  1597. /** Equivalent to strerror, but for windows socket errors. */
  1598. const char *
  1599. evutil_socket_error_to_string(int errcode)
  1600. {
  1601. struct cached_sock_errs_entry *errs, *newerr, find;
  1602. char *msg = NULL;
  1603. EVLOCK_LOCK(windows_socket_errors_lock_, 0);
  1604. find.code = errcode;
  1605. errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
  1606. if (errs) {
  1607. msg = errs->msg;
  1608. goto done;
  1609. }
  1610. if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
  1611. FORMAT_MESSAGE_IGNORE_INSERTS |
  1612. FORMAT_MESSAGE_ALLOCATE_BUFFER,
  1613. NULL, errcode, 0, (char *)&msg, 0, NULL))
  1614. chomp (msg); /* because message has trailing newline */
  1615. else {
  1616. size_t len = 50;
  1617. /* use LocalAlloc because FormatMessage does */
  1618. msg = LocalAlloc(LMEM_FIXED, len);
  1619. if (!msg) {
  1620. msg = (char *)"LocalAlloc failed during Winsock error";
  1621. goto done;
  1622. }
  1623. evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
  1624. }
  1625. newerr = (struct cached_sock_errs_entry *)
  1626. mm_malloc(sizeof (struct cached_sock_errs_entry));
  1627. if (!newerr) {
  1628. LocalFree(msg);
  1629. msg = (char *)"malloc failed during Winsock error";
  1630. goto done;
  1631. }
  1632. newerr->code = errcode;
  1633. newerr->msg = msg;
  1634. HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
  1635. done:
  1636. EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
  1637. return msg;
  1638. }
  1639. #ifndef EVENT__DISABLE_THREAD_SUPPORT
  1640. int
  1641. evutil_global_setup_locks_(const int enable_locks)
  1642. {
  1643. EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
  1644. return 0;
  1645. }
  1646. #endif
  1647. static void
  1648. evutil_free_sock_err_globals(void)
  1649. {
  1650. struct cached_sock_errs_entry **errs, *tofree;
  1651. for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
  1652. ; errs; ) {
  1653. tofree = *errs;
  1654. errs = HT_NEXT_RMV(cached_sock_errs_map,
  1655. &windows_socket_errors,
  1656. errs);
  1657. LocalFree(tofree->msg);
  1658. mm_free(tofree);
  1659. }
  1660. HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
  1661. #ifndef EVENT__DISABLE_THREAD_SUPPORT
  1662. if (windows_socket_errors_lock_ != NULL) {
  1663. EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
  1664. windows_socket_errors_lock_ = NULL;
  1665. }
  1666. #endif
  1667. }
  1668. #else
  1669. #ifndef EVENT__DISABLE_THREAD_SUPPORT
  1670. int
  1671. evutil_global_setup_locks_(const int enable_locks)
  1672. {
  1673. return 0;
  1674. }
  1675. #endif
  1676. static void
  1677. evutil_free_sock_err_globals(void)
  1678. {
  1679. }
  1680. #endif
  1681. int
  1682. evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
  1683. {
  1684. int r;
  1685. va_list ap;
  1686. va_start(ap, format);
  1687. r = evutil_vsnprintf(buf, buflen, format, ap);
  1688. va_end(ap);
  1689. return r;
  1690. }
  1691. int
  1692. evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
  1693. {
  1694. int r;
  1695. if (!buflen)
  1696. return 0;
  1697. #if defined(_MSC_VER) || defined(_WIN32)
  1698. r = _vsnprintf(buf, buflen, format, ap);
  1699. if (r < 0)
  1700. r = _vscprintf(format, ap);
  1701. #elif defined(sgi)
  1702. /* Make sure we always use the correct vsnprintf on IRIX */
  1703. extern int _xpg5_vsnprintf(char * __restrict,
  1704. __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
  1705. const char * __restrict, /* va_list */ char *);
  1706. r = _xpg5_vsnprintf(buf, buflen, format, ap);
  1707. #else
  1708. r = vsnprintf(buf, buflen, format, ap);
  1709. #endif
  1710. buf[buflen-1] = '\0';
  1711. return r;
  1712. }
  1713. #define USE_INTERNAL_NTOP
  1714. #define USE_INTERNAL_PTON
  1715. const char *
  1716. evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
  1717. {
  1718. #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
  1719. return inet_ntop(af, src, dst, len);
  1720. #else
  1721. if (af == AF_INET) {
  1722. const struct in_addr *in = src;
  1723. const ev_uint32_t a = ntohl(in->s_addr);
  1724. int r;
  1725. r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
  1726. (int)(ev_uint8_t)((a>>24)&0xff),
  1727. (int)(ev_uint8_t)((a>>16)&0xff),
  1728. (int)(ev_uint8_t)((a>>8 )&0xff),
  1729. (int)(ev_uint8_t)((a )&0xff));
  1730. if (r<0||(size_t)r>=len)
  1731. return NULL;
  1732. else
  1733. return dst;
  1734. #ifdef AF_INET6
  1735. } else if (af == AF_INET6) {
  1736. const struct in6_addr *addr = src;
  1737. char buf[64], *cp;
  1738. int longestGapLen = 0, longestGapPos = -1, i,
  1739. curGapPos = -1, curGapLen = 0;
  1740. ev_uint16_t words[8];
  1741. for (i = 0; i < 8; ++i) {
  1742. words[i] =
  1743. (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  1744. }
  1745. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  1746. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  1747. (words[5] == 0xffff))) {
  1748. /* This is an IPv4 address. */
  1749. if (words[5] == 0) {
  1750. evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  1751. addr->s6_addr[12], addr->s6_addr[13],
  1752. addr->s6_addr[14], addr->s6_addr[15]);
  1753. } else {
  1754. evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  1755. addr->s6_addr[12], addr->s6_addr[13],
  1756. addr->s6_addr[14], addr->s6_addr[15]);
  1757. }
  1758. if (strlen(buf) > len)
  1759. return NULL;
  1760. strlcpy(dst, buf, len);
  1761. return dst;
  1762. }
  1763. i = 0;
  1764. while (i < 8) {
  1765. if (words[i] == 0) {
  1766. curGapPos = i++;
  1767. curGapLen = 1;
  1768. while (i<8 && words[i] == 0) {
  1769. ++i; ++curGapLen;
  1770. }
  1771. if (curGapLen > longestGapLen) {
  1772. longestGapPos = curGapPos;
  1773. longestGapLen = curGapLen;
  1774. }
  1775. } else {
  1776. ++i;
  1777. }
  1778. }
  1779. if (longestGapLen<=1)
  1780. longestGapPos = -1;
  1781. cp = buf;
  1782. for (i = 0; i < 8; ++i) {
  1783. if (words[i] == 0 && longestGapPos == i) {
  1784. if (i == 0)
  1785. *cp++ = ':';
  1786. *cp++ = ':';
  1787. while (i < 8 && words[i] == 0)
  1788. ++i;
  1789. --i; /* to compensate for loop increment. */
  1790. } else {
  1791. evutil_snprintf(cp,
  1792. sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  1793. cp += strlen(cp);
  1794. if (i != 7)
  1795. *cp++ = ':';
  1796. }
  1797. }
  1798. *cp = '\0';
  1799. if (strlen(buf) > len)
  1800. return NULL;
  1801. strlcpy(dst, buf, len);
  1802. return dst;
  1803. #endif
  1804. } else {
  1805. return NULL;
  1806. }
  1807. #endif
  1808. }
  1809. int
  1810. evutil_inet_pton_scope(int af, const char *src, void *dst, unsigned *indexp)
  1811. {
  1812. int r;
  1813. unsigned if_index;
  1814. char *check, *cp, *tmp_src;
  1815. *indexp = 0; /* Reasonable default */
  1816. /* Bail out if not IPv6 */
  1817. if (af != AF_INET6)
  1818. return evutil_inet_pton(af, src, dst);
  1819. cp = strchr(src, '%');
  1820. /* Bail out if no zone ID */
  1821. if (cp == NULL)
  1822. return evutil_inet_pton(af, src, dst);
  1823. if_index = if_nametoindex(cp + 1);
  1824. if (if_index == 0) {
  1825. /* Could be numeric */
  1826. if_index = strtoul(cp + 1, &check, 10);
  1827. if (check[0] != '\0')
  1828. return 0;
  1829. }
  1830. *indexp = if_index;
  1831. tmp_src = mm_strdup(src);
  1832. cp = strchr(tmp_src, '%');
  1833. *cp = '\0';
  1834. r = evutil_inet_pton(af, tmp_src, dst);
  1835. free(tmp_src);
  1836. return r;
  1837. }
  1838. int
  1839. evutil_inet_pton(int af, const char *src, void *dst)
  1840. {
  1841. #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
  1842. return inet_pton(af, src, dst);
  1843. #else
  1844. if (af == AF_INET) {
  1845. unsigned a,b,c,d;
  1846. char more;
  1847. struct in_addr *addr = dst;
  1848. if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
  1849. return 0;
  1850. if (a > 255) return 0;
  1851. if (b > 255) return 0;
  1852. if (c > 255) return 0;
  1853. if (d > 255) return 0;
  1854. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  1855. return 1;
  1856. #ifdef AF_INET6
  1857. } else if (af == AF_INET6) {
  1858. struct in6_addr *out = dst;
  1859. ev_uint16_t words[8];
  1860. int gapPos = -1, i, setWords=0;
  1861. const char *dot = strchr(src, '.');
  1862. const char *eow; /* end of words. */
  1863. if (dot == src)
  1864. return 0;
  1865. else if (!dot)
  1866. eow = src+strlen(src);
  1867. else {
  1868. unsigned byte1,byte2,byte3,byte4;
  1869. char more;
  1870. for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
  1871. ;
  1872. ++eow;
  1873. /* We use "scanf" because some platform inet_aton()s are too lax
  1874. * about IPv4 addresses of the form "1.2.3" */
  1875. if (sscanf(eow, "%u.%u.%u.%u%c",
  1876. &byte1,&byte2,&byte3,&byte4,&more) != 4)
  1877. return 0;
  1878. if (byte1 > 255 ||
  1879. byte2 > 255 ||
  1880. byte3 > 255 ||
  1881. byte4 > 255)
  1882. return 0;
  1883. words[6] = (byte1<<8) | byte2;
  1884. words[7] = (byte3<<8) | byte4;
  1885. setWords += 2;
  1886. }
  1887. i = 0;
  1888. while (src < eow) {
  1889. if (i > 7)
  1890. return 0;
  1891. if (EVUTIL_ISXDIGIT_(*src)) {
  1892. char *next;
  1893. long r = strtol(src, &next, 16);
  1894. if (next > 4+src)
  1895. return 0;
  1896. if (next == src)
  1897. return 0;
  1898. if (r<0 || r>65536)
  1899. return 0;
  1900. words[i++] = (ev_uint16_t)r;
  1901. setWords++;
  1902. src = next;
  1903. if (*src != ':' && src != eow)
  1904. return 0;
  1905. ++src;
  1906. } else if (*src == ':' && i > 0 && gapPos==-1) {
  1907. gapPos = i;
  1908. ++src;
  1909. } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
  1910. gapPos = i;
  1911. src += 2;
  1912. } else {
  1913. return 0;
  1914. }
  1915. }
  1916. if (setWords > 8 ||
  1917. (setWords == 8 && gapPos != -1) ||
  1918. (setWords < 8 && gapPos == -1))
  1919. return 0;
  1920. if (gapPos >= 0) {
  1921. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  1922. int gapLen = 8 - setWords;
  1923. /* assert(nToMove >= 0); */
  1924. if (nToMove < 0)
  1925. return -1; /* should be impossible */
  1926. memmove(&words[gapPos+gapLen], &words[gapPos],
  1927. sizeof(ev_uint16_t)*nToMove);
  1928. memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
  1929. }
  1930. for (i = 0; i < 8; ++i) {
  1931. out->s6_addr[2*i ] = words[i] >> 8;
  1932. out->s6_addr[2*i+1] = words[i] & 0xff;
  1933. }
  1934. return 1;
  1935. #endif
  1936. } else {
  1937. return -1;
  1938. }
  1939. #endif
  1940. }
  1941. int
  1942. evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
  1943. {
  1944. int port;
  1945. unsigned int if_index;
  1946. char buf[128];
  1947. const char *cp, *addr_part, *port_part;
  1948. int is_ipv6;
  1949. /* recognized formats are:
  1950. * [ipv6]:port
  1951. * ipv6
  1952. * [ipv6]
  1953. * ipv4:port
  1954. * ipv4
  1955. */
  1956. cp = strchr(ip_as_string, ':');
  1957. if (*ip_as_string == '[') {
  1958. size_t len;
  1959. if (!(cp = strchr(ip_as_string, ']'))) {
  1960. return -1;
  1961. }
  1962. len = ( cp-(ip_as_string + 1) );
  1963. if (len > sizeof(buf)-1) {
  1964. return -1;
  1965. }
  1966. memcpy(buf, ip_as_string+1, len);
  1967. buf[len] = '\0';
  1968. addr_part = buf;
  1969. if (cp[1] == ':')
  1970. port_part = cp+2;
  1971. else
  1972. port_part = NULL;
  1973. is_ipv6 = 1;
  1974. } else if (cp && strchr(cp+1, ':')) {
  1975. is_ipv6 = 1;
  1976. addr_part = ip_as_string;
  1977. port_part = NULL;
  1978. } else if (cp) {
  1979. is_ipv6 = 0;
  1980. if (cp - ip_as_string > (int)sizeof(buf)-1) {
  1981. return -1;
  1982. }
  1983. memcpy(buf, ip_as_string, cp-ip_as_string);
  1984. buf[cp-ip_as_string] = '\0';
  1985. addr_part = buf;
  1986. port_part = cp+1;
  1987. } else {
  1988. addr_part = ip_as_string;
  1989. port_part = NULL;
  1990. is_ipv6 = 0;
  1991. }
  1992. if (port_part == NULL) {
  1993. port = 0;
  1994. } else {
  1995. port = atoi(port_part);
  1996. if (port <= 0 || port > 65535) {
  1997. return -1;
  1998. }
  1999. }
  2000. if (!addr_part)
  2001. return -1; /* Should be impossible. */
  2002. #ifdef AF_INET6
  2003. if (is_ipv6)
  2004. {
  2005. struct sockaddr_in6 sin6;
  2006. memset(&sin6, 0, sizeof(sin6));
  2007. #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
  2008. sin6.sin6_len = sizeof(sin6);
  2009. #endif
  2010. sin6.sin6_family = AF_INET6;
  2011. sin6.sin6_port = htons(port);
  2012. if (1 != evutil_inet_pton_scope(
  2013. AF_INET6, addr_part, &sin6.sin6_addr, &if_index)) {
  2014. return -1;
  2015. }
  2016. if ((int)sizeof(sin6) > *outlen)
  2017. return -1;
  2018. sin6.sin6_scope_id = if_index;
  2019. memset(out, 0, *outlen);
  2020. memcpy(out, &sin6, sizeof(sin6));
  2021. *outlen = sizeof(sin6);
  2022. return 0;
  2023. }
  2024. else
  2025. #endif
  2026. {
  2027. struct sockaddr_in sin;
  2028. memset(&sin, 0, sizeof(sin));
  2029. #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  2030. sin.sin_len = sizeof(sin);
  2031. #endif
  2032. sin.sin_family = AF_INET;
  2033. sin.sin_port = htons(port);
  2034. if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
  2035. return -1;
  2036. if ((int)sizeof(sin) > *outlen)
  2037. return -1;
  2038. memset(out, 0, *outlen);
  2039. memcpy(out, &sin, sizeof(sin));
  2040. *outlen = sizeof(sin);
  2041. return 0;
  2042. }
  2043. }
  2044. const char *
  2045. evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
  2046. {
  2047. char b[128];
  2048. const char *res=NULL;
  2049. int port;
  2050. if (sa->sa_family == AF_INET) {
  2051. const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
  2052. res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
  2053. port = ntohs(sin->sin_port);
  2054. if (res) {
  2055. evutil_snprintf(out, outlen, "%s:%d", b, port);
  2056. return out;
  2057. }
  2058. } else if (sa->sa_family == AF_INET6) {
  2059. const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
  2060. res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
  2061. port = ntohs(sin6->sin6_port);
  2062. if (res) {
  2063. evutil_snprintf(out, outlen, "[%s]:%d", b, port);
  2064. return out;
  2065. }
  2066. }
  2067. evutil_snprintf(out, outlen, "<addr with socktype %d>",
  2068. (int)sa->sa_family);
  2069. return out;
  2070. }
  2071. int
  2072. evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
  2073. int include_port)
  2074. {
  2075. int r;
  2076. if (0 != (r = (sa1->sa_family - sa2->sa_family)))
  2077. return r;
  2078. if (sa1->sa_family == AF_INET) {
  2079. const struct sockaddr_in *sin1, *sin2;
  2080. sin1 = (const struct sockaddr_in *)sa1;
  2081. sin2 = (const struct sockaddr_in *)sa2;
  2082. if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
  2083. return -1;
  2084. else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
  2085. return 1;
  2086. else if (include_port &&
  2087. (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
  2088. return r;
  2089. else
  2090. return 0;
  2091. }
  2092. #ifdef AF_INET6
  2093. else if (sa1->sa_family == AF_INET6) {
  2094. const struct sockaddr_in6 *sin1, *sin2;
  2095. sin1 = (const struct sockaddr_in6 *)sa1;
  2096. sin2 = (const struct sockaddr_in6 *)sa2;
  2097. if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
  2098. return r;
  2099. else if (include_port &&
  2100. (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
  2101. return r;
  2102. else
  2103. return 0;
  2104. }
  2105. #endif
  2106. return 1;
  2107. }
  2108. /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
  2109. * has 256 bits to look up whether a character is in some set or not. This
  2110. * fails on non-ASCII platforms, but so does every other place where we
  2111. * take a char and write it onto the network.
  2112. **/
  2113. static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
  2114. { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
  2115. static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
  2116. { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
  2117. static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
  2118. static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
  2119. { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
  2120. static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
  2121. static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
  2122. { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
  2123. static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
  2124. static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
  2125. /* Upper-casing and lowercasing tables to map characters to upper/lowercase
  2126. * equivalents. */
  2127. static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
  2128. 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  2129. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  2130. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  2131. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  2132. 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  2133. 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
  2134. 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  2135. 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
  2136. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  2137. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  2138. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  2139. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  2140. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  2141. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  2142. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  2143. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  2144. };
  2145. static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
  2146. 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  2147. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  2148. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  2149. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  2150. 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  2151. 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
  2152. 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  2153. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
  2154. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  2155. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  2156. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  2157. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  2158. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  2159. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  2160. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  2161. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  2162. };
  2163. #define IMPL_CTYPE_FN(name) \
  2164. int EVUTIL_##name##_(char c) { \
  2165. ev_uint8_t u = c; \
  2166. return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1U << (u & 31))); \
  2167. }
  2168. IMPL_CTYPE_FN(ISALPHA)
  2169. IMPL_CTYPE_FN(ISALNUM)
  2170. IMPL_CTYPE_FN(ISSPACE)
  2171. IMPL_CTYPE_FN(ISDIGIT)
  2172. IMPL_CTYPE_FN(ISXDIGIT)
  2173. IMPL_CTYPE_FN(ISPRINT)
  2174. IMPL_CTYPE_FN(ISLOWER)
  2175. IMPL_CTYPE_FN(ISUPPER)
  2176. char EVUTIL_TOLOWER_(char c)
  2177. {
  2178. return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
  2179. }
  2180. char EVUTIL_TOUPPER_(char c)
  2181. {
  2182. return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
  2183. }
  2184. int
  2185. evutil_ascii_strcasecmp(const char *s1, const char *s2)
  2186. {
  2187. char c1, c2;
  2188. while (1) {
  2189. c1 = EVUTIL_TOLOWER_(*s1++);
  2190. c2 = EVUTIL_TOLOWER_(*s2++);
  2191. if (c1 < c2)
  2192. return -1;
  2193. else if (c1 > c2)
  2194. return 1;
  2195. else if (c1 == 0)
  2196. return 0;
  2197. }
  2198. }
  2199. int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
  2200. {
  2201. char c1, c2;
  2202. while (n--) {
  2203. c1 = EVUTIL_TOLOWER_(*s1++);
  2204. c2 = EVUTIL_TOLOWER_(*s2++);
  2205. if (c1 < c2)
  2206. return -1;
  2207. else if (c1 > c2)
  2208. return 1;
  2209. else if (c1 == 0)
  2210. return 0;
  2211. }
  2212. return 0;
  2213. }
  2214. void
  2215. evutil_rtrim_lws_(char *str)
  2216. {
  2217. char *cp;
  2218. if (str == NULL)
  2219. return;
  2220. if ((cp = strchr(str, '\0')) == NULL || (cp == str))
  2221. return;
  2222. --cp;
  2223. while (*cp == ' ' || *cp == '\t') {
  2224. *cp = '\0';
  2225. if (cp == str)
  2226. break;
  2227. --cp;
  2228. }
  2229. }
  2230. static int
  2231. evutil_issetugid(void)
  2232. {
  2233. #ifdef EVENT__HAVE_ISSETUGID
  2234. return issetugid();
  2235. #else
  2236. #ifdef EVENT__HAVE_GETEUID
  2237. if (getuid() != geteuid())
  2238. return 1;
  2239. #endif
  2240. #ifdef EVENT__HAVE_GETEGID
  2241. if (getgid() != getegid())
  2242. return 1;
  2243. #endif
  2244. return 0;
  2245. #endif
  2246. }
  2247. const char *
  2248. evutil_getenv_(const char *varname)
  2249. {
  2250. if (evutil_issetugid())
  2251. return NULL;
  2252. return getenv(varname);
  2253. }
  2254. ev_uint32_t
  2255. evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
  2256. {
  2257. if (seed == 0) {
  2258. struct timeval tv;
  2259. evutil_gettimeofday(&tv, NULL);
  2260. seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
  2261. #ifdef _WIN32
  2262. seed += (ev_uint32_t) _getpid();
  2263. #else
  2264. seed += (ev_uint32_t) getpid();
  2265. #endif
  2266. }
  2267. state->seed = seed;
  2268. return seed;
  2269. }
  2270. ev_int32_t
  2271. evutil_weakrand_(struct evutil_weakrand_state *state)
  2272. {
  2273. /* This RNG implementation is a linear congruential generator, with
  2274. * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
  2275. * used by OpenBSD, and by Glibc's TYPE_0 RNG.
  2276. *
  2277. * The linear congruential generator is not an industrial-strength
  2278. * RNG! It's fast, but it can have higher-order patterns. Notably,
  2279. * the low bits tend to have periodicity.
  2280. */
  2281. state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
  2282. return (ev_int32_t)(state->seed);
  2283. }
  2284. ev_int32_t
  2285. evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
  2286. {
  2287. ev_int32_t divisor, result;
  2288. /* We can't just do weakrand() % top, since the low bits of the LCG
  2289. * are less random than the high ones. (Specifically, since the LCG
  2290. * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
  2291. * therefore the low m bits of the LCG will have period 2^m.) */
  2292. divisor = EVUTIL_WEAKRAND_MAX / top;
  2293. do {
  2294. result = evutil_weakrand_(state) / divisor;
  2295. } while (result >= top);
  2296. return result;
  2297. }
  2298. /**
  2299. * Volatile pointer to memset: we use this to keep the compiler from
  2300. * eliminating our call to memset.
  2301. */
  2302. void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
  2303. void
  2304. evutil_memclear_(void *mem, size_t len)
  2305. {
  2306. evutil_memset_volatile_(mem, 0, len);
  2307. }
  2308. int
  2309. evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
  2310. {
  2311. static const char LOOPBACK_S6[16] =
  2312. "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
  2313. if (addr->sa_family == AF_INET) {
  2314. struct sockaddr_in *sin = (struct sockaddr_in *)addr;
  2315. return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
  2316. } else if (addr->sa_family == AF_INET6) {
  2317. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
  2318. return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
  2319. }
  2320. return 0;
  2321. }
  2322. int
  2323. evutil_hex_char_to_int_(char c)
  2324. {
  2325. switch(c)
  2326. {
  2327. case '0': return 0;
  2328. case '1': return 1;
  2329. case '2': return 2;
  2330. case '3': return 3;
  2331. case '4': return 4;
  2332. case '5': return 5;
  2333. case '6': return 6;
  2334. case '7': return 7;
  2335. case '8': return 8;
  2336. case '9': return 9;
  2337. case 'A': case 'a': return 10;
  2338. case 'B': case 'b': return 11;
  2339. case 'C': case 'c': return 12;
  2340. case 'D': case 'd': return 13;
  2341. case 'E': case 'e': return 14;
  2342. case 'F': case 'f': return 15;
  2343. }
  2344. return -1;
  2345. }
  2346. #ifdef _WIN32
  2347. HMODULE
  2348. evutil_load_windows_system_library_(const TCHAR *library_name)
  2349. {
  2350. TCHAR path[MAX_PATH];
  2351. unsigned n;
  2352. n = GetSystemDirectory(path, MAX_PATH);
  2353. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2354. return 0;
  2355. _tcscat(path, TEXT("\\"));
  2356. _tcscat(path, library_name);
  2357. return LoadLibrary(path);
  2358. }
  2359. #endif
  2360. /* Internal wrapper around 'socket' to provide Linux-style support for
  2361. * syscall-saving methods where available.
  2362. *
  2363. * In addition to regular socket behavior, you can use a bitwise or to set the
  2364. * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
  2365. * to make the socket nonblocking or close-on-exec with as few syscalls as
  2366. * possible.
  2367. */
  2368. evutil_socket_t
  2369. evutil_socket_(int domain, int type, int protocol)
  2370. {
  2371. evutil_socket_t r;
  2372. #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
  2373. r = socket(domain, type, protocol);
  2374. if (r >= 0)
  2375. return r;
  2376. else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
  2377. return -1;
  2378. #endif
  2379. #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
  2380. r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
  2381. if (r < 0)
  2382. return -1;
  2383. if (type & EVUTIL_SOCK_NONBLOCK) {
  2384. if (evutil_fast_socket_nonblocking(r) < 0) {
  2385. evutil_closesocket(r);
  2386. return -1;
  2387. }
  2388. }
  2389. if (type & EVUTIL_SOCK_CLOEXEC) {
  2390. if (evutil_fast_socket_closeonexec(r) < 0) {
  2391. evutil_closesocket(r);
  2392. return -1;
  2393. }
  2394. }
  2395. return r;
  2396. }
  2397. /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
  2398. * support for syscall-saving methods where available.
  2399. *
  2400. * In addition to regular accept behavior, you can set one or more of flags
  2401. * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
  2402. * make the socket nonblocking or close-on-exec with as few syscalls as
  2403. * possible.
  2404. */
  2405. evutil_socket_t
  2406. evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
  2407. ev_socklen_t *addrlen, int flags)
  2408. {
  2409. evutil_socket_t result;
  2410. #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
  2411. result = accept4(sockfd, addr, addrlen, flags);
  2412. if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
  2413. /* A nonnegative result means that we succeeded, so return.
  2414. * Failing with EINVAL means that an option wasn't supported,
  2415. * and failing with ENOSYS means that the syscall wasn't
  2416. * there: in those cases we want to fall back. Otherwise, we
  2417. * got a real error, and we should return. */
  2418. return result;
  2419. }
  2420. #endif
  2421. result = accept(sockfd, addr, addrlen);
  2422. if (result < 0)
  2423. return result;
  2424. if (flags & EVUTIL_SOCK_CLOEXEC) {
  2425. if (evutil_fast_socket_closeonexec(result) < 0) {
  2426. evutil_closesocket(result);
  2427. return -1;
  2428. }
  2429. }
  2430. if (flags & EVUTIL_SOCK_NONBLOCK) {
  2431. if (evutil_fast_socket_nonblocking(result) < 0) {
  2432. evutil_closesocket(result);
  2433. return -1;
  2434. }
  2435. }
  2436. return result;
  2437. }
  2438. /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
  2439. * fd[1] get read from fd[0]. Make both fds nonblocking and close-on-exec.
  2440. * Return 0 on success, -1 on failure.
  2441. */
  2442. int
  2443. evutil_make_internal_pipe_(evutil_socket_t fd[2])
  2444. {
  2445. /*
  2446. Making the second socket nonblocking is a bit subtle, given that we
  2447. ignore any EAGAIN returns when writing to it, and you don't usally
  2448. do that for a nonblocking socket. But if the kernel gives us EAGAIN,
  2449. then there's no need to add any more data to the buffer, since
  2450. the main thread is already either about to wake up and drain it,
  2451. or woken up and in the process of draining it.
  2452. */
  2453. #if defined(EVENT__HAVE_PIPE2)
  2454. if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
  2455. return 0;
  2456. #endif
  2457. #if defined(EVENT__HAVE_PIPE)
  2458. if (pipe(fd) == 0) {
  2459. if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
  2460. evutil_fast_socket_nonblocking(fd[1]) < 0 ||
  2461. evutil_fast_socket_closeonexec(fd[0]) < 0 ||
  2462. evutil_fast_socket_closeonexec(fd[1]) < 0) {
  2463. close(fd[0]);
  2464. close(fd[1]);
  2465. fd[0] = fd[1] = -1;
  2466. return -1;
  2467. }
  2468. return 0;
  2469. } else {
  2470. event_warn("%s: pipe", __func__);
  2471. }
  2472. #endif
  2473. #ifdef _WIN32
  2474. #define LOCAL_SOCKETPAIR_AF AF_INET
  2475. #else
  2476. #define LOCAL_SOCKETPAIR_AF AF_UNIX
  2477. #endif
  2478. if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
  2479. if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
  2480. evutil_fast_socket_nonblocking(fd[1]) < 0 ||
  2481. evutil_fast_socket_closeonexec(fd[0]) < 0 ||
  2482. evutil_fast_socket_closeonexec(fd[1]) < 0) {
  2483. evutil_closesocket(fd[0]);
  2484. evutil_closesocket(fd[1]);
  2485. fd[0] = fd[1] = -1;
  2486. return -1;
  2487. }
  2488. return 0;
  2489. }
  2490. fd[0] = fd[1] = -1;
  2491. return -1;
  2492. }
  2493. /* Wrapper around eventfd on systems that provide it. Unlike the system
  2494. * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
  2495. * flags. Returns -1 on error or if eventfd is not supported.
  2496. */
  2497. evutil_socket_t
  2498. evutil_eventfd_(unsigned initval, int flags)
  2499. {
  2500. #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
  2501. int r;
  2502. #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
  2503. r = eventfd(initval, flags);
  2504. if (r >= 0 || flags == 0)
  2505. return r;
  2506. #endif
  2507. r = eventfd(initval, 0);
  2508. if (r < 0)
  2509. return r;
  2510. if (flags & EVUTIL_EFD_CLOEXEC) {
  2511. if (evutil_fast_socket_closeonexec(r) < 0) {
  2512. evutil_closesocket(r);
  2513. return -1;
  2514. }
  2515. }
  2516. if (flags & EVUTIL_EFD_NONBLOCK) {
  2517. if (evutil_fast_socket_nonblocking(r) < 0) {
  2518. evutil_closesocket(r);
  2519. return -1;
  2520. }
  2521. }
  2522. return r;
  2523. #else
  2524. return -1;
  2525. #endif
  2526. }
  2527. void
  2528. evutil_free_globals_(void)
  2529. {
  2530. evutil_free_secure_rng_globals_();
  2531. evutil_free_sock_err_globals();
  2532. }