1 /*
2  * Copyright (c) 2007-2011 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 
27 /** @file event2/util.h
28 
29   Common convenience functions for cross-platform portability and
30   related socket manipulations.
31 
32  */
33 module deimos.event2.util;
34 
35 extern (C):
36 nothrow:
37 
38 import deimos.event2._d_util;
39 
40 import core.stdc.errno;
41 import core.stdc.string;
42 import core.stdc.stdint;
43 version (Posix) {
44   public import core.sys.posix.sys.time : timeval;
45   public import core.sys.posix.sys.socket;
46 } else version (Windows) {
47   static if (__VERSION__ >= 2070)
48     public import core.sys.windows.winsock2;
49   else
50     public import std.c.windows.winsock;
51 } else static assert(false, "Don't know timeval on this platform.");
52 version (Posix) {
53   import core.sys.posix.sys.types;
54 }
55 import core.stdc.stddef;
56 import core.stdc.stdarg;
57 version (Posix) {
58   import core.sys.posix.netdb;
59 }
60 
61 version (Windows) {
62   extern(Windows) void WSASetLastError(int iError);
63 } else {
64   import core.sys.posix.sys.socket;
65 }
66 
67 /**
68 * @name Standard integer types.
69 *
70 * Integer type definitions for types that are supposed to be defined in the
71 * C99-specified stdint.h.  Shamefully, some platforms do not include
72 * stdint.h, so we need to replace it.  (If you are on a platform like this,
73 * your C headers are now over 10 years out of date.  You should bug them to
74 * do something about this.)
75 *
76 * We define:
77 *
78 * <dl>
79 *   <dt>ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t</dt>
80 *      <dd>uinteger types of exactly 64, 32, 16, and 8 bits
81 *          respectively.</dd>
82 *    <dt>ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t</dt>
83 *      <dd>signed integer types of exactly 64, 32, 16, and 8 bits
84 *          respectively.</dd>
85 *    <dt>ev_uintptr_t, ev_intptr_t</dt>
86 *      <dd>unsigned/signed integers large enough
87 *      to hold a pointer without loss of bits.</dd>
88 *    <dt>ev_ssize_t</dt>
89 *      <dd>A signed type of the same size as size_t</dd>
90 *    <dt>ev_off_t</dt>
91 *      <dd>A signed type typically used to represent offsets within a
92 *      (potentially large) file</dd>
93 *
94 * @{
95  */
96 alias ulong ev_uint64_t;
97 alias long ev_int64_t;
98 
99 alias uint ev_uint32_t;
100 alias int ev_int32_t;
101 
102 alias ushort ev_uint16_t;
103 alias short ev_int16_t;
104 
105 alias ubyte ev_uint8_t;
106 alias byte ev_int8_t;
107 
108 alias uintptr_t ev_uintptr_t;
109 alias intptr_t ev_intptr_t;
110 
111 alias ptrdiff_t ev_ssize_t;
112 
113 version (Windows) {
114   alias ev_int64_t ev_off_t;
115 } else {
116   alias off_t ev_off_t;
117 }
118 /**@}*/
119 
120 /* Limits for integer types.
121 
122    We're making two assumptions here:
123      - The compiler does constant folding properly.
124      - The platform does signed arithmetic in two's complement.
125 */
126 
127 /**
128    @name Limits for integer types
129 
130    These macros hold the largest or smallest values possible for the
131    ev_[u]int*_t types.
132 
133    @{
134 */
135 enum EV_UINT64_MAX = ulong.max;
136 enum EV_INT64_MAX  = long.max;
137 enum EV_INT64_MIN  = long.min;
138 enum EV_UINT32_MAX = uint.max;
139 enum EV_INT32_MAX  = int.max;
140 enum EV_INT32_MIN  = int.min;
141 enum EV_UINT16_MAX = ushort.max;
142 enum EV_INT16_MAX  = short.max;
143 enum EV_INT16_MIN  = short.min;
144 enum EV_UINT8_MAX  = ubyte.max;
145 enum EV_INT8_MAX   = byte.max;
146 enum EV_INT8_MIN   = byte.min;
147 /** @} */
148 
149 /**
150    @name Limits for SIZE_T and SSIZE_T
151 
152    @{
153 */
154 enum EV_SIZE_MAX = size_t.max;
155 enum EV_SSIZE_MAX = ev_ssize_t.max;
156 enum EV_SSIZE_MIN = ev_ssize_t.min;
157 /**@}*/
158 
159 version (Win32) {
160   alias int ev_socklen_t;
161 } else {
162   alias socklen_t ev_socklen_t;
163 }
164 
165 /**
166  * A type wide enough to hold the output of "socket()" or "accept()".  On
167  * Windows, this is an intptr_t; elsewhere, it is an int. */
168 version (Win32) {
169   alias intptr_t evutil_socket_t;
170 } else {
171   alias int evutil_socket_t;
172 }
173 
174 /** Create two new sockets that are connected to each other.
175 
176     On Unix, this simply calls socketpair().  On Windows, it uses the
177     loopback network interface on 127.0.0.1, and only
178     AF_INET,SOCK_STREAM are supported.
179 
180     (This may fail on some Windows hosts where firewall software has cleverly
181     decided to keep 127.0.0.1 from talking to itself.)
182 
183     Parameters and return values are as for socketpair()
184 */
185 int evutil_socketpair(int d, int type, int protocol, ref evutil_socket_t[2] sv);
186 /** Do platform-specific operations as needed to make a socket nonblocking.
187 
188     @param sock The socket to make nonblocking
189     @return 0 on success, -1 on failure
190  */
191 int evutil_make_socket_nonblocking(evutil_socket_t sock);
192 
193 /** Do platform-specific operations to make a listener socket reusable.
194 
195     Specifically, we want to make sure that another program will be able
196     to bind this address right after we've closed the listener.
197 
198     This differs from Windows's interpretation of "reusable", which
199     allows multiple listeners to bind the same address at the same time.
200 
201     @param sock The socket to make reusable
202     @return 0 on success, -1 on failure
203  */
204 int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
205 
206 /** Do platform-specific operations as needed to close a socket upon a
207     successful execution of one of the exec*() functions.
208 
209     @param sock The socket to be closed
210     @return 0 on success, -1 on failure
211  */
212 int evutil_make_socket_closeonexec(evutil_socket_t sock);
213 
214 /** Do the platform-specific call needed to close a socket returned from
215     socket() or accept().
216 
217     @param sock The socket to be closed
218     @return 0 on success, -1 on failure
219  */
220 int evutil_closesocket(evutil_socket_t sock);
221 alias evutil_closesocket EVUTIL_CLOSESOCKET;
222 
223 
224 version (Windows) {
225   /** Return the most recent socket error.  Not idempotent on all platforms. */
226   alias WSAGetLastError EVUTIL_SOCKET_ERROR;
227   /** Replace the most recent socket error with errcode */
228   alias WSASetLastError EVUTIL_SET_SOCKET_ERROR;
229 
230   /** Return the most recent socket error to occur on sock. */
231   int evutil_socket_geterror(evutil_socket_t sock);
232   /** Convert a socket error to a string. */
233   const(char)* evutil_socket_error_to_string(int errcode);
234 } else {
235   alias errno EVUTIL_SOCKET_ERROR;
236   void EVUTIL_SET_SOCKET_ERROR()(int errcode) { errno = errcode; }
237   auto EVUTIL_SET_SOCKET_ERROR()(evutil_socket_t sock) { return errno; }
238   alias strerror evutil_socket_error_to_string;
239 }
240 
241 
242 /**
243  * @name Manipulation macros for struct timeval.
244  *
245  * We define replacements
246  * for timeradd, timersub, timerclear, timercmp, and timerisset.
247  *
248  * @{
249  */
250 void evutil_timeradd()(timeval* tvp, timeval* uvp, timeval* vvp) {
251 	vvp.tv_sec = tvp.tv_sec + uvp.tv_sec;
252 	vvp.tv_usec = tvp.tv_usec + uvp.tv_usec;
253 	if (vvp.tv_usec >= 1000000) {
254 		vvp.tv_sec++;
255 		vvp.tv_usec -= 1000000;
256 	}
257 }
258 
259 void evutil_timersub()(timeval* tvp, timeval* uvp, timeval* vvp) {
260 	vvp.tv_sec = tvp.tv_sec - uvp.tv_sec;
261 	vvp.tv_usec = tvp.tv_usec - uvp.tv_usec;
262 	if (vvp.tv_usec < 0) {
263 		vvp.tv_sec--;
264 		vvp.tv_usec += 1000000;
265 	}
266 }
267 
268 void evutil_timerclear()(timeval* tvp) {
269 	tvp.tv_sec = tvp.tv_usec = 0;
270 }
271 /**@}*/
272 
273 /** Return true iff the tvp is related to uvp according to the relational
274 * operator cmp.  Recognized values for cmp are ==, <=, <, >=, and >. */
275 // TODO: Port?
276 //#define	evutil_timercmp(tvp, uvp, cmp)					\
277 //	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
278 //	 ((tvp)->tv_usec cmp (uvp)->tv_usec) :				\
279 //	 ((tvp)->tv_sec cmp (uvp)->tv_sec))
280 
281 bool evutil_timerisset()(timeval* tvp) {
282   return tvp.tv_sec || tvp.tv_usec;
283 }
284 
285 /** Replacement for offsetof on platforms that don't define it. */
286 template evutil_offsetof(type, string field) {
287   enum evutil_offsetof = mixin("type." ~ field ~ ".offsetof");
288 }
289 
290 /* big-int related functions */
291 /** Parse a 64-bit value from a string.  Arguments are as for strtol. */
292 ev_int64_t evutil_strtoll(const(char)* s, char* *endptr, int base);
293 
294 /** Replacement for gettimeofday on platforms that lack it. */
295 static if (is(typeof(gettimeofday))) {
296   alias gettimeofday evutil_gettimeofday;
297 } else {
298   alias void timezone;
299   int evutil_gettimeofday(timeval* tv, timezone* tz);
300 }
301 
302 /** Replacement for snprintf to get consistent behavior on platforms for
303     which the return value of snprintf does not conform to C99.
304  */
305 int evutil_snprintf(char* buf, size_t buflen, const(char)* format, ...);
306 /** Replacement for vsnprintf to get consistent behavior on platforms for
307     which the return value of snprintf does not conform to C99.
308  */
309 int evutil_vsnprintf(char* buf, size_t buflen, const(char)* format, va_list ap);
310 
311 /** Replacement for inet_ntop for platforms which lack it. */
312 const(char)* evutil_inet_ntop(int af, const(void)* src, char* dst, size_t len);
313 /** Replacement for inet_pton for platforms which lack it. */
314 int evutil_inet_pton(int af, const(char)* src, void* dst);
315 
316 /** Parse an IPv4 or IPv6 address, with optional port, from a string.
317 
318     Recognized formats are:
319     - [IPv6Address]:port
320     - [IPv6Address]
321     - IPv6Address
322     - IPv4Address:port
323     - IPv4Address
324 
325     If no port is specified, the port in the output is set to 0.
326 
327     @param str The string to parse.
328     @param out A sockaddr to hold the result.  This should probably be
329        a struct sockaddr_storage.
330     @param outlen A pointer to the number of bytes that that 'out' can safely
331        hold.  Set to the number of bytes used in 'out' on success.
332     @return -1 if the address is not well-formed, if the port is out of range,
333        or if out is not large enough to hold the result.  Otherwise returns
334        0 on success.
335 */
336 int evutil_parse_sockaddr_port(const(char)* str, sockaddr* out_, int* outlen);
337 
338 /** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
339  * preceeds sa2, or greater than 0 if sa1 follows sa2.  If include_port is
340  * true, consider the port as well as the address.  Only implemented for
341  * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
342  * the same between Libevent versions. */
343 int evutil_sockaddr_cmp(const(sockaddr)* sa1, const(sockaddr)* sa2,
344     int include_port);
345 
346 /** As strcasecmp, but always compares the characters in locale-independent
347     ASCII.  That's useful if you're handling data in ASCII-based protocols.
348  */
349 int evutil_ascii_strcasecmp(const(char)* str1, const(char)* str2);
350 /** As strncasecmp, but always compares the characters in locale-independent
351     ASCII.  That's useful if you're handling data in ASCII-based protocols.
352  */
353 int evutil_ascii_strncasecmp(const(char)* str1, const(char)* str2, size_t n);
354 
355 /* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
356  * if this system has no getaddrinfo(). */
357 static if (is(addrinfo)) {
358   alias addrinfo evutil_addrinfo;
359 } else {
360   /** A definition of addrinfo for systems that lack it.
361 
362       (This is just an alias for addrinfo if the system defines
363       struct addrinfo.)
364   */
365   struct evutil_addrinfo {
366   	int     ai_flags;     /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
367   	int     ai_family;    /* PF_xxx */
368   	int     ai_socktype;  /* SOCK_xxx */
369   	int     ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
370   	size_t  ai_addrlen;   /* length of ai_addr */
371   	char   *ai_canonname; /* canonical name for nodename */
372   	sockaddr  *ai_addr; /* binary address */
373   	evutil_addrinfo  *ai_next; /* next structure in linked list */
374   }
375 }
376 /** @name evutil_getaddrinfo() error codes
377 
378     These values are possible error codes for evutil_getaddrinfo() and
379     related functions.
380 
381     @{
382 */
383 static if (is(typeof(EAI_ADDRFAMILY))) {
384   enum EVUTIL_EAI_ADDRFAMILY = EAI_ADDRFAMILY;
385 } else {
386   enum EVUTIL_EAI_ADDRFAMILY = -901;
387 }
388 static if (is(typeof(EAI_AGAIN))) {
389   enum EVUTIL_EAI_AGAIN = EAI_AGAIN;
390 } else {
391   enum EVUTIL_EAI_AGAIN = -902;
392 }
393 static if (is(typeof(EAI_BADFLAGS))) {
394   enum EVUTIL_EAI_BADFLAGS = EAI_BADFLAGS;
395 } else {
396   enum EVUTIL_EAI_BADFLAGS = -903;
397 }
398 static if (is(typeof(EAI_FAIL))) {
399   enum EVUTIL_EAI_FAIL = EAI_FAIL;
400 } else {
401   enum EVUTIL_EAI_FAIL = -904;
402 }
403 static if (is(typeof(EAI_FAMILY))) {
404   enum EVUTIL_EAI_FAMILY = EAI_FAMILY;
405 } else {
406   enum EVUTIL_EAI_FAMILY = -905;
407 }
408 static if (is(typeof(EAI_MEMORY))) {
409   enum EVUTIL_EAI_MEMORY = EAI_MEMORY;
410 } else {
411   enum EVUTIL_EAI_MEMORY = -906;
412 }
413 /* This test is a bit complicated, since some MS SDKs decide to
414  * remove NODATA or redefine it to be the same as NONAME, in a
415  * fun interpretation of RFC 2553 and RFC 3493. */
416 static if (is(typeof(EAI_NODATA)) && (!is(typeof(EAI_NONAME)) || EAI_NODATA != EAI_NONAME)) {
417   enum EVUTIL_EAI_NODATA = EAI_NODATA;
418 } else {
419   enum EVUTIL_EAI_NODATA = -907;
420 }
421 static if (is(typeof(EAI_NONAME))) {
422   enum EVUTIL_EAI_NONAME = EAI_NONAME;
423 } else {
424   enum EVUTIL_EAI_NONAME = -908;
425 }
426 static if (is(typeof(EAI_SERVICE))) {
427   enum EVUTIL_EAI_SERVICE = EAI_SERVICE;
428 } else {
429   enum EVUTIL_EAI_SERVICE = -909;
430 }
431 static if (is(typeof(EAI_SOCKTYPE))) {
432   enum EVUTIL_EAI_SOCKTYPE = EAI_SOCKTYPE;
433 } else {
434   enum EVUTIL_EAI_SOCKTYPE = -910;
435 }
436 static if (is(typeof(EAI_SYSTEM))) {
437   enum EVUTIL_EAI_SYSTEM = EAI_SYSTEM;
438 } else {
439   enum EVUTIL_EAI_SYSTEM = -911;
440 }
441 
442 enum EVUTIL_EAI_CANCEL = -90001;
443 
444 static if (is(typeof(AI_PASSIVE))) {
445   enum EVUTIL_AI_PASSIVE = AI_PASSIVE;
446 } else {
447   enum EVUTIL_AI_PASSIVE = 0x1000;
448 }
449 static if (is(typeof(AI_CANONNAME))) {
450   enum EVUTIL_AI_CANONNAME = AI_CANONNAME;
451 } else {
452   enum EVUTIL_AI_CANONNAME = 0x2000;
453 }
454 static if (is(typeof(AI_NUMERICHOST))) {
455   enum EVUTIL_AI_NUMERICHOST = AI_NUMERICHOST;
456 } else {
457   enum EVUTIL_AI_NUMERICHOST = 0x4000;
458 }
459 static if (is(typeof(AI_NUMERICSERV))) {
460   enum EVUTIL_AI_NUMERICSERV = AI_NUMERICSERV;
461 } else {
462   enum EVUTIL_AI_NUMERICSERV = 0x8000;
463 }
464 static if (is(typeof(AI_V4MAPPED))) {
465   enum EVUTIL_AI_V4MAPPED = AI_V4MAPPED;
466 } else {
467   enum EVUTIL_AI_V4MAPPED = 0x10000;
468 }
469 static if (is(typeof(AI_ALL))) {
470   enum EVUTIL_AI_ALL = AI_ALL;
471 } else {
472   enum EVUTIL_AI_ALL = 0x20000;
473 }
474 static if (is(typeof(AI_ADDRCONFIG))) {
475   enum EVUTIL_AI_ADDRCONFIG = AI_ADDRCONFIG;
476 } else {
477   enum EVUTIL_AI_ADDRCONFIG = 0x40000;
478 }
479 /**@}*/
480 
481 /**
482  * This function clones getaddrinfo for systems that don't have it.  For full
483  * details, see RFC 3493, section 6.1.
484  *
485  * Limitations:
486  * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
487  *  gethostbyname, with their attendant issues.
488  * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
489  *
490  * For a nonblocking variant, see evdns_getaddrinfo.
491  */
492 int evutil_getaddrinfo(const(char)* nodename, const(char)* servname,
493     const(evutil_addrinfo)* hints_in_, evutil_addrinfo* *res);
494 
495 /** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
496 void evutil_freeaddrinfo(evutil_addrinfo* ai);
497 
498 const(char)* evutil_gai_strerror(int err);
499 
500 /** Generate n bytes of secure pseudorandom data, and store them in buf.
501  *
502  * By default, Libevent uses an ARC4-based random number generator, seeded
503  * using the platform's entropy source (/dev/urandom on Unix-like systems;
504  * CryptGenRandom on Windows).
505  */
506 void evutil_secure_rng_get_bytes(void* buf, size_t n);
507 
508 /**
509  * Seed the secure random number generator if needed, and return 0 on
510  * success or -1 on failure.
511  *
512  * It is okay to call this function more than once; it will still return
513  * 0 if the RNG has been successfully seeded and -1 if it can't be
514  * seeded.
515  *
516  * Ordinarily you don't need to call this function from your own code;
517  * Libevent will seed the RNG itself the first time it needs good random
518  * numbers.  You only need to call it if (a) you want to double-check
519  * that one of the seeding methods did succeed, or (b) you plan to drop
520  * the capability to seed (by chrooting, or dropping capabilities, or
521  * whatever), and you want to make sure that seeding happens before your
522  * program loses the ability to do it.
523  */
524 int evutil_secure_rng_init();
525 
526 /** Seed the random number generator with extra random bytes.
527 
528     You should almost never need to call this function; it should be
529     sufficient to invoke evutil_secure_rng_init(), or let Libevent take
530     care of calling evutil_secure_rng_init() on its own.
531 
532     If you call this function as a _replacement_ for the regular
533     entropy sources, then you need to be sure that your input
534     contains a fairly large amount of strong entropy.  Doing so is
535     notoriously hard: most people who try get it wrong.  Watch out!
536 
537     @param dat a buffer full of a strong source of random numbers
538     @param datlen the number of bytes to read from datlen
539  */
540 void evutil_secure_rng_add_bytes(const(char)* dat, size_t datlen);