1 /*
2  * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016, 2019, 2020,
4  *               2021
5  *      Inferno Nettverk A/S, Norway.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. The above copyright notice, this list of conditions and the following
11  *    disclaimer must appear in all copies of the software, derivative works
12  *    or modified versions, and any portions thereof, aswell as in all
13  *    supporting documentation.
14  * 2. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by
17  *      Inferno Nettverk A/S, Norway.
18  * 3. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * Inferno Nettverk A/S requests users of this software to return to
33  *
34  *  Software Distribution Coordinator  or  sdc@inet.no
35  *  Inferno Nettverk A/S
36  *  Oslo Research Park
37  *  Gaustadall�en 21
38  *  NO-0349 Oslo
39  *  Norway
40  *
41  * any improvements or extensions that they make and grant Inferno Nettverk A/S
42  * the rights to redistribute these changes.
43  *
44  */
45 
46 /* $Id: sockd.h,v 1.945.4.14.2.3.4.18 2021/02/02 19:34:14 karls Exp $ */
47 
48 #ifndef _SOCKD_H_
49 #define _SOCKD_H_
50 
51 #if HAVE_SCHED_H
52 #include <sched.h>
53 #endif /* HAVE_SCHED_H */
54 
55 #if HAVE_SOLARIS_PRIVS
56 #include <priv.h>
57 #endif /* HAVE_SOLARIS_PRIVS */
58 
59 #include <sys/types.h>
60 #include <sys/ipc.h>
61 #if HAVE_SYS_SHM_H
62 #include <sys/shm.h>
63 #endif /* HAVE_SYS_SHM_H */
64 
65 #include <regex.h>
66 
67 /*
68  * Throttling for objects we send to the monitor process for testing.
69  * Each process can send objects to the monitor at the rate of one
70  * object per <seconds given below>.
71  */
72 #define SOCKD_ALARMTESTS_DELAY (60)
73 
74 /*
75  * number of seconds a to wait for a connect initiated on behalf of a
76  * client to complete.  Can be changed in the config file.
77  */
78 #define SOCKD_CONNECTTIMEOUT   (30)
79 
80 
81 /*
82  * number of seconds a client can negotiate with server.
83  * Can be changed in the config file.
84  */
85 #define SOCKD_NEGOTIATETIMEOUT   (30)
86 
87 /*
88  * number of seconds a client can be connected after negotiation is completed
89  * without sending/receiving any data.  Can be changed in the config file.
90  */
91 #define SOCKD_IOTIMEOUT_TCP          (0) /* no timeout. */
92 
93 #if SOCKS_SERVER
94 #define SOCKD_IOTIMEOUT_UDP          (86400) /* 24h */
95 #else /* BAREFOOTD */
96 #define SOCKD_IOTIMEOUT_UDP          (3600)  /* one hour */
97 #endif
98 
99 /*
100  * This is to handle a potential resource issue that can occur
101  * in TCP when side 'A' of the TCP session closes it's end, but
102  * the other end, side 'B', does not close it's end.  In this
103  * situation, TCP will be forced to keep state for the TCP session
104  * until side B closes it's end, or "never" if side B never closes.
105  *
106  * Some kernels have added kernel support for tuning this on a global
107  * basis, but implementations may vary.
108  *
109  * If this value is set, it gives the number of seconds to wait
110  * for B to close it's side.  Note that this may break the application
111  * protocol, as there may be nothing wrong with B using a long time,
112  * days even, to close it's end.  It may however produce an unfortunate
113  * resource problem with both the Dante server and the kernels TCP having to
114  * keep state for these sessions, which in 99.999% of the cases could
115  * probably be closed as B will not send anything more.
116  *
117  * The default therefor is to not enable this "feature".
118  */
119 #define SOCKD_FIN_WAIT_2_TIMEOUT  (0) /* Seconds.  Set to 0 to disable. */
120 
121 /*
122  * Prefer to not remove idle processes, even if possible, without
123  * waiting for them to have handled at least this many clients, or
124  * lived at least this long.
125  * Nothing very special behind these numbers, just seems like reasonable
126  * defaults at the time.  Note that they do not affect removal of idle
127  * processes when we are running short of resources, then we do remove what
128  * we can, regardless of these numbers.
129  */
130 
131 #define SOCKD_MIN_CLIENTS_HANDLED_NEGOTIATE (MAX(SOCKD_NEGOTIATEMAX * 10, 5000))
132 #define SOCKD_MIN_CLIENTS_HANDLED_REQUEST   (MAX(SOCKD_REQUESTMAX   * 10, 5000))
133 #define SOCKD_MIN_CLIENTS_HANDLED_IO        (MAX(SOCKD_IOMAX        * 10, 5000))
134 
135 #define SOCKD_MIN_LIFETIME_SECONDS          (60 * 1)
136 
137 
138 
139 #define SOCKD_SINGLEAUTH_LINGERTIMEOUT (60)  /* one minute */
140 
141 #define SOCKD_CACHESTAT    (1000) /* how often to print info.     */
142 
143 #define SOCKD_EXPLICIT_LDAP_PORT     (389)
144 #define SOCKD_EXPLICIT_LDAPS_PORT    (636)
145 
146 #ifndef SOCKD_LDAP_DEADTIME
147 #define SOCKD_LDAP_DEADTIME          (30) /* server down cache timeout */
148 #endif /* SOCKD_LDAP_DEADTIME */
149 #define SOCKD_LDAP_SEARCHTIME        (30)
150 #define SOCKD_LDAP_TIMEOUT           (2)
151 
152 /*
153  * -1 is a valid value, so special-case.
154  */
155  #define LDAP_UNSET_DEBUG_VALUE   (-2)
156 
157 
158 /*
159  * Depending on what kind of server we are, we will have different
160  * phases to go through before we get to the i/o part.  This is
161  * where we try to define the name of some generic phases, to reduce
162  * the number of product-specific defines in the code.
163  *
164  * Also we provide wrappers to avoid linkage errors for functions that
165  * are not used in different servers, to limit the amount of #ifdef's
166  * in the code itself.
167  */
168 
169 #if BAREFOOTD
170 #define HAVE_NEGOTIATE_PHASE              (0)
171 /* XXX same as HAVE_NEGOTIATE_PHASE? */
172 #define HAVE_CONTROL_CONNECTION           (0)
173 #define HAVE_SOCKS_RULES                  (0)
174 #define HAVE_TCP_SUPPORT                  (1)
175 #define HAVE_UDP_SUPPORT                  (1)
176 
177 #elif SOCKS_SERVER
178 #define HAVE_NEGOTIATE_PHASE              (1)
179 #define HAVE_CONTROL_CONNECTION           (1)
180 #define HAVE_SOCKS_RULES                  (1)
181 #define HAVE_TCP_SUPPORT                  (1)
182 #define HAVE_UDP_SUPPORT                  (1)
183 
184 #elif COVENANT
185 #define HAVE_NEGOTIATE_PHASE              (1)
186 #define HAVE_CONTROL_CONNECTION           (0)
187 #define HAVE_SOCKS_RULES                  (1)
188 #define HAVE_TCP_SUPPORT                  (1)
189 #define HAVE_UDP_SUPPORT                  (0)
190 
191 #else
192 
193 #error "No product defined.  Who am I?"
194 
195 #endif
196 
197 
198 /*
199  * use caching versions, avoiding a lot of overhead.
200  */
201 #ifndef DISABLE_GETHOSTBYNAME_CACHE
202 
203 #undef gethostbyname
204 #define gethostbyname(name)            (cgethostbyname((name)))
205 
206 #undef gethostbyaddr
207 #define gethostbyaddr(addr, len, type) (cgethostbyaddr((addr), (len), (type)))
208 
209 #undef getnameinfo
210 #define getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)  \
211        cgetnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
212 
213 #endif /* DISABLE_GETHOSTBYNAME_CACHE */
214 
215 /* Search for POSIX groups */
216 #define DEFAULT_LDAP_FILTER_GROUP "(&(memberuid=%s)(objectclass=posixgroup))"
217 /* Search for Active Directory groups */
218 #define DEFAULT_LDAP_FILTER_GROUP_AD "(&(cn=%s)(objectclass=group))"
219 
220 
221 /*
222  * This is a bunch of macros that are part of the implementation that
223  * makes the negotiate children able to handle reading an unlimited
224  * number of concurrent requests from the clients, without blocking
225  * in any read call.
226  * We treat blocking on write as a fatal error as there is no normal
227  * reason that should happen during the negotiation.
228  */
229 
230 #define INIT(length)                                                           \
231    const size_t start   = state->start;      /* start of next block in mem. */ \
232    const size_t end     = start + (length);  /* end of next block in mem.   */ \
233    errno = 0
234 
235 /*
236  * Checks whether "object" has been filled with all data requested and
237  * if so calls "function", if function is not NULL.
238  * If "object" has not been filled it returns the number of bytes
239  * that was added to object on this call, or error.
240 */
241 
242 #define CHECK(object, auth, nextfunction)                      \
243 do {                                                           \
244    SASSERTX(state->reqread <= end);                            \
245                                                                \
246    errno = 0;                                                  \
247                                                                \
248    if (LEFT()) {                                               \
249       ssize_t p;                                               \
250                                                                \
251       SASSERT(LEFT() > 0);                                     \
252                                                                \
253       if (LEFT() > MEMLEFT())                                  \
254           OUTOFMEM();                                          \
255                                                                \
256       p = READ(s, LEFT(), auth);                               \
257                                                                \
258       if (p >= 0)                                              \
259          errno = 0; /* remove any old cruft. */                \
260                                                                \
261       if (p <= 0) {                                            \
262          if (ERRNOISTMP(errno))                                \
263             return NEGOTIATE_CONTINUE;                         \
264          else if (p == 0)                                      \
265             return NEGOTIATE_EOF;                              \
266          else                                                  \
267             return NEGOTIATE_ERROR;                            \
268       }                                                        \
269                                                                \
270       state->reqread += p;                                     \
271                                                                \
272       if (LEFT()) { /* read something, but not all. */         \
273          errno = EWOULDBLOCK;                                  \
274          return NEGOTIATE_CONTINUE;                            \
275       }                                                        \
276    }                                                           \
277                                                                \
278    OBJECTFILL((object));                                       \
279                                                                \
280    state->start    = end;                                      \
281    state->rcurrent = nextfunction;                             \
282                                                                \
283    if (state->rcurrent != NULL)                                \
284       return state->rcurrent(s, request, state);               \
285 } while (/*CONSTCOND*/0)
286 
287 #define MEMLEFT()      (sizeof(state->mem) - state->reqread)
288 
289 #define LEFT()   ((end) - state->reqread)
290 /*
291  * Returns the number of bytes left to read.
292  */
293 
294 #define READ(s, length, auth)                    \
295    (socks_recvfromn((s),                         \
296                     &state->mem[state->reqread], \
297                     (length),                    \
298                     0,                           \
299                     0,                           \
300                     NULL,                        \
301                     NULL,                        \
302                     NULL,                        \
303                     (auth)))                      \
304 /*
305  * "s" is the descriptor to read from.
306  * "length" is how much to read.
307  * Returns the number of bytes read, -1 on error.
308  */
309 
310 
311 
312 #define OBJECTFILL(object)  (memmove((object), &state->mem[start], end - start))
313 /*
314  * Fills "object" with data.
315  */
316 
317 /*
318  * Handle out of memory error (i.e., no more space in our inbuffer).
319  * In the socks case, the max length is known, so we should never
320  * experience that error.
321  * In the http proxy case, there is no limit, so we have to make sure
322  * the size of our buffer, as set at compile time, is big enough.
323  */
324 #if SOCKS_SERVER
325 #define OUTOFMEM()                                                             \
326 do {                                                                           \
327    SERRX(LEFT());                                                              \
328 } while (/*CONSTCOND*/0)
329 #else /* COVENANT */
330 #define OUTOFMEM() \
331 do {                                                                           \
332    snprintf(state->emsg, sizeof(state->emsg),                                  \
333            "http request is too long (more than %lu bytes)."                   \
334            "Either our compiled-in limit is too low, or the client is "        \
335            "attempting something fishy",                                       \
336            (unsigned long)state->reqread);                                     \
337                                                                                \
338    return NEGOTIATE_ERROR;                                                     \
339 } while (/*CONSTCOND*/0)
340 #endif /* COVENANT */
341 
342 
343 
344 /*
345  * computing the values to send to io_update() indicating how much
346  * was read/written to/where in relation to the i/o object "_io".
347  * "_io" contains the value now, while the other objects contain the
348  * value before we read/wrote anything.
349  */
350 #define DO_IOCOUNT(_src_read, _src_written, _dst_read, _dst_written, _io)     \
351 do {                                                                           \
352    SASSERTX((_src_read)->bytes      <= (_io)->src.read.bytes);                 \
353    SASSERTX((_src_read)->packets    <= (_io)->src.read.packets);               \
354                                                                                \
355    SASSERTX((_src_written)->bytes   <= (_io)->src.written.bytes);              \
356    SASSERTX((_src_written)->packets <= (_io)->src.written.packets);            \
357                                                                                \
358    SASSERTX((_dst_read)->bytes      <= (_io)->dst.read.bytes);                 \
359    SASSERTX((_dst_read)->packets    <= (_io)->dst.read.packets);               \
360                                                                                \
361    SASSERTX((_dst_written)->bytes   <= (_io)->dst.written.bytes);              \
362    SASSERTX((_dst_written)->packets <= (_io)->dst.written.packets);            \
363                                                                                \
364    (_src_read)->bytes   = (_io)->src.read.bytes   - (_src_read)->bytes;        \
365    (_src_read)->packets = (_io)->src.read.packets - (_src_read)->packets;      \
366                                                                                \
367    (_src_written)->bytes = (_io)->src.written.bytes - (_src_written)->bytes;   \
368    (_src_written)->packets                                                     \
369    = (_io)->src.written.packets - (_src_written)->packets;                     \
370                                                                                \
371    (_dst_read)->bytes   = (_io)->dst.read.bytes   - (_dst_read)->bytes;        \
372    (_dst_read)->packets = (_io)->dst.read.packets - (_dst_read)->packets;      \
373                                                                                \
374    (_dst_written)->bytes = (_io)->dst.written.bytes - (_dst_written)->bytes;   \
375    (_dst_written)->packets                                                     \
376    = (_io)->dst.written.packets - (_dst_written)->packets;                     \
377 } while (/* CONSTCOND */ 0)
378 
379 /* reset a throttle object. */
380 #define RESET_THROTTLE(object, timenow)                                        \
381 do {                                                                           \
382    (object)->starttime  = (timenow);                                           \
383    (object)->newclients = (0);                                                 \
384 } while (/*CONSTCOND*/ 0)
385 
386 
387 /* copies all monitor-related fields. */
388 #define COPY_MONITORFIELDS(from, to)                                           \
389 do {                                                                           \
390    (to)->mstats               = (from)->mstats;                                \
391    (to)->mstats_shmid         = (from)->mstats_shmid;                          \
392    (to)->mstats_isinheritable = (from)->mstats_isinheritable;                  \
393    (to)->alarmsconfigured     = (from)->alarmsconfigured;                      \
394 } while (/* CONSTCOND */ 0)
395 
396 
397 /* clears monitor-related fields that should be cleared. */
398 #define CLEAR_MONITORFIELDS(object)                                            \
399 do {                                                                           \
400    (object)->mstats               = NULL;                                      \
401    (object)->mstats_shmid         = 0;                                         \
402    (object)->mstats_isinheritable = 1; /* always */                            \
403    /* not this one: (object)->alarmsconfigured     = 0; */                     \
404 } while (/* CONSTCOND */ 0)
405 
406 
407 /*
408  *
409  * Macros related to shmem handling.
410  *
411  */
412 
413 /*
414  * Mostly used for asserts.  Check if something is set when nothing should
415  * be set.
416  */
417 
418 #define SHMID_ISSET(object) \
419    ((object)->bw_shmid || (object)->mstats_shmid || (object)->ss_shmid)
420 
421 #define SHMID_ISATTACHED(object) \
422    ((object)->bw != NULL || (object)->mstats != NULL || (object)->ss != NULL)
423 
424 #define INIT_MSTATES(object, _type, _number)                                   \
425 do {                                                                           \
426    if ((object)->bw != NULL)                                                   \
427       INIT_MSTATE(&((object)->bw->mstate), (_type), (_number));                \
428                                                                                \
429    if ((object)->ss != NULL)                                                   \
430       INIT_MSTATE(&((object)->ss->mstate), (_type), (_number));                \
431                                                                                \
432    if ((object)->mstats != NULL)                                               \
433       INIT_MSTATE(&((object)->mstats->mstate), (_type), (_number));            \
434 } while (/* CONSTCOND */ 0)
435 
436 #define INIT_MSTATE(mstate, _parenttype, _number)                              \
437 do {                                                                           \
438    (mstate)->number     = (_number);                                           \
439    (mstate)->parenttype = (_parenttype);                                       \
440 } while (/* CONSTCOND */ 0)
441 
442 
443 #if DO_SHMEMCHECK
444 
445 #define MPROTECT_SHMEMHEADER(shmemobject)                                      \
446 do {                                                                           \
447    SASSERTX((shmemobject)->mstate.shmid != 0);                                 \
448                                                                                \
449    slog(LOG_DEBUG,                                                             \
450         "%s: doing mprotect on address %p",  function, (shmemobject));         \
451                                                                                \
452    SASSERT(mprotect((shmemobject),                                             \
453            sizeof(shmemobject)->mstate,                                        \
454            PROT_READ) == 0);                                                   \
455                                                                                \
456    SASSERTX((shmemobject)->mstate.shmid != 0);                                 \
457 } while (/* CONSTCOND */ 0)
458 
459 #define MUNPROTECT_SHMEMHEADER(shmemobject)                                    \
460 do {                                                                           \
461    SASSERTX((shmemobject)->mstate.shmid != 0);                                 \
462                                                                                \
463    slog(LOG_DEBUG,                                                             \
464         "%s: doing munprotect on address %p",  function, (shmemobject));       \
465                                                                                \
466    SASSERT(mprotect((shmemobject),                                             \
467                     sizeof(shmemobject)->mstate,                               \
468                     PROT_READ | PROT_WRITE) == 0);                             \
469                                                                                \
470    SASSERTX((shmemobject)->mstate.shmid != 0);                                 \
471 } while (/* CONSTCOND */ 0)
472 
473 
474 #else  /* !DO_SHMEMCHECK */
475 
476 #define MPROTECT_SHMEMHEADER(shmemobject)   do { } while (/* CONSTCOND */ 0)
477 #define MUNPROTECT_SHMEMHEADER(shmemobject) do { } while (/* CONSTCOND */ 0)
478 
479 #endif /* !DO_SHMEMCHECK */
480 
481 #if DEBUG || DIAGNOSTIC
482 /*
483  * memory-mapped file contents may not be saved in coredumps.
484  */
485 #define SHMEM_COPYOBJECT(src, dst) shmem_object_t (dst) = (*src)
486 
487 #else
488 
489 #define SHMEM_COPYOBJECT(src, dst)                                             \
490 do {                                                                           \
491    SASSERTX(src != NULL);                                                      \
492 } while (/*CONSTCOND*/ 0)
493 
494 
495 #endif /* DEBUG */
496 
497 /*
498  * copies shmem stuff from rule "src" to rule "dst".
499  */
500 #define SHMEM_MOVE(src, dst, objects)                                          \
501 do {                                                                           \
502    SHMEM_COPY(src, dst, objects);                                              \
503    SHMEM_CLEAR(src, objects, 1);                                               \
504 } while (/*CONSTCOND*/ 0)
505 
506 /*
507  * copies shmem stuff from rule "src" to rule "dst".
508  */
509 #define SHMEM_COPY(src, dst, objects)                                          \
510 do {                                                                           \
511    if (objects & SHMEM_BW) {                                                   \
512       (dst)->bw       = (src)->bw;                                             \
513       (dst)->bw_shmid = (src)->bw_shmid;                                       \
514    }                                                                           \
515                                                                                \
516    if (objects & SHMEM_MONITOR) {                                              \
517       COPY_MONITORFIELDS((src), (dst));                                        \
518    }                                                                           \
519                                                                                \
520    if (objects & SHMEM_SS) {                                                   \
521       (dst)->ss       = (src)->ss;                                             \
522       (dst)->ss_shmid = (src)->ss_shmid;                                       \
523    }                                                                           \
524 } while (/*CONSTCOND*/ 0)
525 
526 
527 
528 #define HANDLE_SHMAT(object, memfield, idfield)                                \
529 do {                                                                           \
530    char *fname;                                                                \
531    int fd;                                                                     \
532                                                                                \
533    SASSERTX((object)->memfield == NULL);                                       \
534                                                                                \
535    if ((object)->idfield == 0)                                                 \
536       break;                                                                   \
537                                                                                \
538    fname = sockd_getshmemname((object)->idfield, key_unset);                   \
539    if ((fd = open(fname, O_RDWR)) == -1) {                                     \
540       int failureisok;                                                         \
541                                                                                \
542       if (sockscf.state.mother.s == -1 || sockd_motherexists() == 0)           \
543          failureisok = 1; /* presumably mother exited and deleted shmemfiles */\
544       else                                                                     \
545          failureisok = 0;                                                      \
546                                                                                \
547       slog(failureisok ? LOG_DEBUG: LOG_WARNING,                               \
548            "%s: failed to open %s for attaching to " #idfield " %ld: %s",      \
549            function, fname, (object)->idfield, strerror(errno));               \
550                                                                                \
551       (object)->memfield = NULL;                                               \
552       (object)->idfield  = 0;                                                  \
553       break;                                                                   \
554    }                                                                           \
555                                                                                \
556    (object)->memfield = sockd_mmap(NULL,                                       \
557                                    sizeof(*(object)->memfield),                \
558                                    PROT_READ | PROT_WRITE,                     \
559                                    MAP_SHARED,                                 \
560                                    fd,                                         \
561                                    0);                                         \
562                                                                                \
563    close(fd);                                                                  \
564                                                                                \
565    if ((object)->memfield == MAP_FAILED) {                                     \
566       swarn("%s: failed to mmap " #idfield " shmem segment %ld of size %ld "   \
567             "from file %s",                                                    \
568             function,                                                          \
569             (object)->idfield,                                                 \
570             (unsigned long)sizeof(*(object)->memfield),                        \
571             fname);                                                            \
572                                                                                \
573       (object)->memfield = NULL;                                               \
574       (object)->idfield  = 0;                                                  \
575       break;                                                                   \
576    }                                                                           \
577                                                                                \
578    MPROTECT_SHMEMHEADER((object)->memfield);                                   \
579                                                                                \
580    SHMEM_COPYOBJECT((object)->memfield, _shmem);                               \
581                                                                                \
582    slog(LOG_DEBUG,                                                             \
583         "%s: attached to " #idfield " %ld of size %lu at %p, %lu clients, "    \
584         "filename %s",                                                         \
585         function,                                                              \
586         (object)->idfield,                                                     \
587         (unsigned long)sizeof(*(object)->memfield),                            \
588         (object)->memfield,                                                    \
589         (unsigned long)(object)->memfield->mstate.clients, fname);             \
590                                                                                \
591    SASSERTX((object)->idfield == (object)->memfield->mstate.shmid);            \
592 } while (/* CONSTCOND */ 0)
593 
594 #define HANDLE_SHMDT(object, memfield, idfield)                                \
595 do {                                                                           \
596    SASSERTX((object)->idfield  != 0);                                          \
597    SASSERTX((object)->memfield != NULL);                                       \
598                                                                                \
599    SHMEM_COPYOBJECT((object)->memfield, _shmem);                               \
600                                                                                \
601    SASSERTX((object)->idfield == (object)->memfield->mstate.shmid);            \
602                                                                                \
603    slog(LOG_DEBUG,                                                             \
604         "%s: detaching from " #idfield " %ld at %p with %lu clients",          \
605         function,                                                              \
606         (object)->idfield,                                                     \
607         (object)->memfield,                                                    \
608         (unsigned long)(object)->memfield->mstate.clients);                    \
609                                                                                \
610    if (munmap((object)->memfield, sizeof(*(object)->memfield)) != 0)           \
611       swarn("%s: munmap of " #idfield " shmem segment %ld (%p) failed",        \
612             function, (object)->idfield, (object)->memfield);                  \
613                                                                                \
614    (object)->memfield = NULL;                                                  \
615 } while (/* CONSTCOND */ 0)
616 
617 
618 /*
619  * Unuses (decrements by one) any shared memory in use by "rule" for the
620  * client address "addr", indicating one client-session has been closed.
621  * If necessary, temporarily attaches to the shmem segments to do it,
622  * before always detaching before returning.
623  *
624  */
625 #define SHMEM_UNUSE(rule, cinfo, lock, objects)                                \
626 do {                                                                           \
627    int need_attach = SHMEM_NONE, detach_from = SHMEM_NONE;                     \
628                                                                                \
629    /*                                                                          \
630     * First attach to everything we need to attach to ...                      \
631     */                                                                         \
632                                                                                \
633    if (((objects) & SHMEM_BW) && (rule)->bw_shmid != 0) {                      \
634       if ((rule)->bw == NULL)                                                  \
635          need_attach |= SHMEM_BW;                                              \
636                                                                                \
637       detach_from |= SHMEM_BW;                                                 \
638    }                                                                           \
639                                                                                \
640    if (((objects) & SHMEM_MONITOR) && (rule)->mstats_shmid != 0) {             \
641       if ((rule)->mstats == NULL)                                              \
642          need_attach |= SHMEM_MONITOR;                                         \
643                                                                                \
644       detach_from |= SHMEM_MONITOR;                                            \
645    }                                                                           \
646                                                                                \
647    if (((objects) & SHMEM_SS) && (rule)->ss_shmid != 0) {                      \
648       if ((rule)->ss == NULL)                                                  \
649          need_attach |= SHMEM_SS;                                              \
650                                                                                \
651       detach_from |= SHMEM_SS;                                                 \
652    }                                                                           \
653                                                                                \
654    if (need_attach != SHMEM_NONE)                                              \
655       (void)sockd_shmat((rule), need_attach);                                  \
656                                                                                \
657    /*                                                                          \
658     * ... and then unuse it.                                                   \
659     */                                                                         \
660                                                                                \
661    if (((objects) & SHMEM_BW) && (rule)->bw_shmid != 0) {                      \
662       SASSERTX((rule)->bw != NULL);                                            \
663                                                                                \
664       slog(LOG_DEBUG, "%s: unusing bw_shmid %lu at %p, cinfo %s, clients %lu", \
665            function,                                                           \
666            (unsigned long)(rule)->bw_shmid,                                    \
667            (rule)->bw,                                                         \
668            clientinfo2string(cinfo, NULL, 0),                                  \
669            (unsigned long)(rule)->bw->mstate.clients);                         \
670                                                                                \
671       bw_unuse((rule)->bw, cinfo, lock);                                       \
672    }                                                                           \
673                                                                                \
674    if (((objects) & SHMEM_MONITOR) && (rule)->mstats_shmid != 0) {             \
675       SASSERTX((rule)->mstats != NULL);                                        \
676                                                                                \
677       slog(LOG_DEBUG,                                                          \
678            "%s: unusing mstats_shmid %lu, cinfo %s, clients %lu",              \
679            function,                                                           \
680            (unsigned long)(rule)->mstats_shmid,                                \
681            clientinfo2string(cinfo, NULL, 0),                                  \
682            (unsigned long)(rule)->mstats->mstate.clients);                     \
683                                                                                \
684       monitor_unuse((rule)->mstats, cinfo, lock);                              \
685    }                                                                           \
686                                                                                \
687    if (((objects) & SHMEM_SS) && (rule)->ss_shmid != 0) {                      \
688       SASSERTX((rule)->ss != NULL);                                            \
689                                                                                \
690       slog(LOG_DEBUG, "%s: unusing ss_shmid %lu, cinfo %s, clients %lu",       \
691            function,                                                           \
692            (unsigned long)(rule)->ss_shmid,                                    \
693            clientinfo2string(cinfo, NULL, 0),                                  \
694            (unsigned long)(rule)->ss->mstate.clients);                         \
695                                                                                \
696       session_unuse((rule)->ss, cinfo, lock);                                  \
697    }                                                                           \
698                                                                                \
699    if ((need_attach | detach_from) != SHMEM_NONE)                              \
700       sockd_shmdt((rule), need_attach | detach_from);                          \
701 } while (/*CONSTCOND*/0)
702 
703 /*
704  * clears shmem stuff in "rule".
705  */
706 #define SHMEM_CLEAR(rule, objects, idtoo)                                      \
707 do {                                                                           \
708    if (objects & SHMEM_BW) {                                                   \
709       (rule)->bw = NULL;                                                       \
710                                                                                \
711       if (idtoo)                                                               \
712          (rule)->bw_shmid = 0;                                                 \
713    }                                                                           \
714                                                                                \
715    if (objects & SHMEM_MONITOR) {                                              \
716       const unsigned long shmid     = (rule)->mstats_shmid;                    \
717       const size_t alarmsconfigured = (rule)->alarmsconfigured;                \
718                                                                                \
719       CLEAR_MONITORFIELDS((rule));                                             \
720                                                                                \
721       if (!idtoo) {                                                            \
722          (rule)->mstats_shmid     = shmid;                                     \
723          (rule)->alarmsconfigured = alarmsconfigured;                          \
724       }                                                                        \
725    }                                                                           \
726                                                                                \
727    if (objects & SHMEM_SS) {                                                   \
728       (rule)->ss = NULL;                                                       \
729                                                                                \
730       if (idtoo)                                                               \
731          (rule)->ss_shmid = 0;                                                 \
732    }                                                                           \
733 } while (/*CONSTCOND*/0)
734 
735 #define UNLOCK(lock)                                                           \
736 do {                                                                           \
737    if (lock != -1)                                                             \
738       socks_unlock(lock);                                                      \
739 } while (/*CONSTCOND*/0)
740 
741 #if BAREFOOTD
742 #define ALL_UDP_BOUNCED()                                                      \
743    (  sockscf.state.alludpbounced                                              \
744     || pidismother(sockscf.state.pid) != 1 /* only main mother bounces. */)
745 #endif /* BAREFOOTD */
746 
747 /*
748  * build a string for the source and one for the destination that can
749  * be used in iolog() and similar for logging the address related to
750  * something.
751  */
752 #define MAX_IOLOGADDR                                                          \
753   (MAXSOCKADDRSTRING  + sizeof(" ")                  /* local */               \
754  + MAXAUTHINFOLEN + MAXSOCKSHOSTSTRING + sizeof(" ") /* proxy */               \
755  + MAXSOCKSHOSTSTRING + sizeof(" ")                  /* proxy's ext addr. */   \
756  + MAXAUTHINFOLEN + MAXSOCKSHOSTSTRING + sizeof(" ") /* peer  */               \
757  + (MAXSOCKADDRSTRING + sizeof(" ") * HAVE_MAX_HOSTIDS))
758 
759 #if HAVE_SOCKS_HOSTID
760 #define CRULE_OR_HRULE(object)                                                 \
761    ((object)->hrule_isset ? &((object)->hrule) : &((object)->crule))
762 
763 #if HAVE_MAX_HOSTIDS == 0
764 #error "HAVE_MAX_HOSTIDS is zero"
765 #endif /* HAVE_MAX_HOSTIDS == 0 */
766 
767 #define DEFAULT_HOSTINDEX (1)
768 
769 #define HOSTIDCOPY(src, dst) do {                                              \
770    SASSERTX(ELEMENTS((dst)->hostidv) >= (src)->hostidc);                       \
771                                                                                \
772    (dst)->hostidc = (src)->hostidc;                                            \
773    memcpy((dst)->hostidv,                                                      \
774           (src)->hostidv,                                                      \
775           sizeof(*(src)->hostidv) * (src)->hostidc);                           \
776 } while (/*CONSTCOND*/ 0)
777 
778 #define HOSTIDZERO(cinfo)                                                      \
779 do {                                                                           \
780    (cinfo)->hostidc = 0;                                                       \
781    bzero((cinfo)->hostidv, sizeof((cinfo)->hostidv));                          \
782 } while (/*CONSTCOND*/ 0)
783 
784 
785 #define GET_HOSTIDV(object)                                                    \
786    /* coverity[dead_error_condition] */                                        \
787    (((object) == NULL || (object)->hostidc == 0) ?  NULL : (object)->hostidv)
788 
789 #define GET_HOSTIDC(object)                                                    \
790    /* coverity[dead_error_condition] */                                        \
791    ((object) == NULL ? 0 : (object)->hostidc)
792 
793 #else /* !HAVE_SOCKS_HOSTID */
794 
795 #define CRULE_OR_HRULE(object)  (&((object)->crule))
796 #define GET_HOSTIDV(object) ((struct in_addr *)NULL)
797 #define GET_HOSTIDC(object) (0)
798 #define HOSTIDCOPY(src, dst)
799 #define HOSTIDZERO(cinfo)
800 
801 #endif /* !HAVE_SOCKS_HOSTID */
802 
803 /*
804  * The rule that contains the bandwidth info.
805  * For products with socks rules, the shmem-objects are eventually
806  * inherited by the socks-rule.  For other products, they are eventually
807  * inherited by the hostid-rule, if present, or client-rule, it not present.
808  */
809 
810 
811 #if HAVE_SOCKS_RULES
812 #define SHMEMRULE(io)      (&((io)->srule))
813 
814 #else /* !HAVE_SOCKS_RULES */
815 #define SHMEMRULE(io)      CRULE_OR_HRULE((io))
816 
817 #endif /* !HAVE_SOCKS_RULES */
818 
819 #define IORULE(io) SHMEMRULE(io)
820 
821 /*
822  * Some sessions have a separate control-connection, while others just
823  * have one connection that serves as both the client connection and the
824  * control connection.
825  */
826 #define CONTROLIO(io) ((io)->control.s != -1 ?                                 \
827    &((io)->control)                                                            \
828 :  (((io)->state.command == SOCKS_BINDREPLY) ? &((io)->dst) :  &((io)->src)))
829 
830 #define INTERNALIO(io)                                                         \
831 (((io)->state.command == SOCKS_BINDREPLY) ? &((io)->dst) :  &((io)->src))
832 
833 #define CLIENTIO(io) INTERNALIO(io)
834 
835 #define EXTERNALIO(io)                                                         \
836 (((io)->state.command == SOCKS_BINDREPLY) ? &((io)->src) :  &((io)->dst))
837 
838 #define TARGETIO(io) EXTERNALIO(io)
839 
840 /*
841  * info sent by sockd children to mother.
842  */
843 #define SOCKD_NOP                (0)   /* No command/op.       */
844 #define SOCKD_FREESLOT_TCP       (1)   /* free'd a tcp slot.   */
845 #define SOCKD_FREESLOT_UDP       (2)   /* free'd a udp slot.   */
846 
847 /*
848  * info sent by mother to sockd children.
849  */
850 #define SOCKD_EXITNORMALLY       (1)
851 
852 /*
853  * a request child can currently handle a maximum of one client, so can't
854  * be changed and is therefor #defined here rather than in config.h.
855  */
856 #define SOCKD_REQUESTMAX   1
857 
858 /*
859  * Max number of tests a monitor process can have queued.
860  */
861 #define MAX_TESTS_QUEUED (256)
862 
863 /*
864  * types of child-processes.
865  */
866 #define PROC_MOTHER        (0)    /* 0 so that it's correct pre-init too. */
867 #define PROC_MONITOR       (1)
868 #define PROC_NEGOTIATE     (2)
869 #define PROC_REQUEST       (3)
870 #define PROC_IO            (4)
871 #define PROC_NOTOURS       (255)
872 
873 #if SOCKS_SERVER
874 #define FDPASS_MAX          3   /* max number of descriptors we send/receive. */
875 #else
876 #define FDPASS_MAX          2   /* max number of descriptors we send/receive. */
877 #endif
878 
879 /*
880  * If we are unable to add a new child due to lack of resources, this is the
881  * max time to wait before trying again.
882  */
883 #define MAX_ADDCHILD_SECONDS (10)
884 
885 
886 /* how long the alarm period should last by default. */
887 #define DEFAULT_ALARM_PERIOD     (5)
888 
889 /*
890  * alarmsides.  Bitmask.
891  */
892 #define ALARM_INTERNAL           (1)
893 #define ALARM_INTERNAL_RECV      (2)
894 #define ALARM_INTERNAL_SEND      (4)
895 #define ALARM_EXTERNAL           (8)
896 #define ALARM_EXTERNAL_RECV      (16)
897 #define ALARM_EXTERNAL_SEND      (32)
898 #define ALARM_RECV               (64)
899 #define ALARM_SEND               (128)
900 
901 /* alarmtypes set. Bitmask. */
902 #define ALARM_DATA               (1)
903 #define ALARM_DISCONNECT         (2)
904 #define ALARM_TEST               (4)
905 #define ALARM_PROTOCOL           (8)
906 
907 
908    /*
909     * config stuff
910     */
911 
912 #define VERDICT_BLOCKs     "block"
913 #define VERDICT_PASSs      "pass"
914 
915 /* how to rotate addresses. */
916 #define ROTATION_NOTSET     0	/* illegal value. */
917 #define ROTATION_NONE       1
918 #define ROTATION_ROUTE      2
919 #define ROTATION_SAMESAME   3
920 
921 #define SOCKS_LOG_CONNECTs       "connect"
922 #define SOCKS_LOG_DISCONNECTs    "disconnect"
923 #define SOCKS_LOG_DATAs          "data"
924 #define SOCKS_LOG_ERRORs         "error"
925 #define SOCKS_LOG_IOOPERATIONs   "iooperation"
926 #define SOCKS_LOG_TCPINFOs       "tcpinfo"
927 
928 typedef enum { addrscope_global,
929                addrscope_nodelocal,
930                addrscope_linklocal } ipv6_addrscope_t;
931 
932 
933 /*
934  * privilege stuff.
935  */
936 #if !HAVE_PRIVILEGES
937 typedef enum { PRIV_ON, PRIV_OFF } priv_op_t;
938 #endif /* !HAVE_PRIVILEGES */
939 
940 typedef enum { SOCKD_PRIV_NOTSET = 0,
941                SOCKD_PRIV_FILE_READ,
942                SOCKD_PRIV_FILE_WRITE,
943                SOCKD_PRIV_NET_ADDR,
944                SOCKD_PRIV_NET_ICMPACCESS,
945                SOCKD_PRIV_NET_ROUTESOCKET,
946                SOCKD_PRIV_PRIVILEGED,
947                SOCKD_PRIV_UNPRIVILEGED,
948                SOCKD_PRIV_LIBWRAP,
949                SOCKD_PRIV_PAM,
950                SOCKD_PRIV_BSDAUTH,
951                SOCKD_PRIV_GSSAPI
952 } privilege_t;
953 
954 typedef enum { IO_NOERROR,
955                IO_TMPERROR,          /* temporary error; try again later.     */
956                IO_IOERROR,           /* a network error.                      */
957                IO_ERROR,             /* non-network error.                    */
958                IO_EAGAIN,            /* no data available to read currently.  */
959                IO_TIMEOUT,
960                IO_CLOSE,
961                IO_BLOCK,
962                IO_TMPBLOCK,
963                IO_ADMINTERMINATION
964 } iostatus_t;
965 
966 #define IOSTATUS_FATALERROR(error)       \
967 (!  (  (error) == IO_NOERROR             \
968     || (error) == IO_TMPERROR            \
969     || (error) == IO_TMPBLOCK            \
970     || (error) == IO_EAGAIN))
971 
972 #if SOCKS_SERVER
973 
974 #define IOSTATUS_UDP_SEND_FAILED(e)                                            \
975 (IO_TMPERROR)
976 
977 #else /* !SOCKS_SERVER */
978 
979 #define IOSTATUS_UDP_SEND_FAILED(e)                                            \
980 (((e) == EMSGSIZE || ERRNOISTMP(e)) ? IO_TMPERROR : IO_ERROR)
981 
982 #endif /* !SOCKS_SERVER */
983 
984 typedef enum {
985    OPERATION_ACCEPT,
986    OPERATION_BLOCK,        /* session blocked and closed.             */
987    OPERATION_TMPBLOCK,     /* packet blocked, but session not closed. */
988    OPERATION_CONNECT,
989    OPERATION_DISCONNECT,
990    OPERATION_ERROR,        /* session failed and closed.              */
991    OPERATION_TMPERROR,     /* packet failed but session not closed.   */
992    OPERATION_HOSTID,
993    OPERATION_IO
994 } operation_t;
995 
996 typedef enum { KEY_IPV4 = 1, KEY_IPV6, KEY_MAC, KEY_TIME } keytype_t;
997 typedef enum { ACKPIPE, DATAPIPE } whichpipe_t;
998 typedef enum { NEGOTIATE_EOF,
999                NEGOTIATE_ERROR,     /* fatal error, wrong auth, etc.          */
1000                NEGOTIATE_CONTINUE,  /* have not finished, do continue.        */
1001                NEGOTIATE_FINISHED   /* have finished, read request ok so far. */
1002 } negotiate_result_t;
1003 
1004 #define fakesockaddr2sockshost sockaddr2sockshost/* no fakes in server. */
1005 
1006 /* ok signals, i.e signals that do not indicate an error. */
1007 #if HAVE_SIGNAL_SIGINFO
1008 #define SIGNALISOK(sig) \
1009    (  (sig) == SIGHUP   \
1010    || (sig) == SIGINT   \
1011    || (sig) == SIGUSR1  \
1012    || (sig) == SIGINFO  \
1013    || (sig) == SIGQUIT  \
1014    || (sig) == SIGTERM  \
1015    || (sig) == SIGHUP)
1016 #else /* !HAVE_SIGNAL_SIGINFO */
1017 #define SIGNALISOK(sig) \
1018    (  (sig) == SIGHUP   \
1019    || (sig) == SIGINT   \
1020    || (sig) == SIGUSR1  \
1021    || (sig) == SIGQUIT  \
1022    || (sig) == SIGTERM  \
1023    || (sig) == SIGHUP)
1024 #endif
1025 
1026 /*
1027  * Called at the start of all signalhandlers.
1028  */
1029 
1030 #define SIGNAL_PROLOGUE(sig, si, saved_errno)                                  \
1031 do {                                                                           \
1032    char _b[1][32];                                                             \
1033    const char *_msgv[]                                                         \
1034    = { signal2string(-sig),                                                    \
1035        " [: processing signal ",                                               \
1036        ltoa((-sig), _b[0], sizeof(_b[0])),                                     \
1037        NULL                                                                    \
1038    };                                                                          \
1039                                                                                \
1040    if ((sig) > 0) {                                                            \
1041       const int old_insignal = sockscf.state.insignal;                         \
1042                                                                                \
1043       sockscf.state.insignal = (sig);                                          \
1044       sockd_pushsignal(sig, si);                                               \
1045       sockscf.state.insignal = old_insignal;                                   \
1046                                                                                \
1047       errno = (saved_errno);                                                   \
1048       return;                                                                  \
1049    }                                                                           \
1050                                                                                \
1051    (sig) = -(sig);                                                             \
1052    signalslog(LOG_DEBUG, _msgv);                                               \
1053 } while (/* CONSTCOND */ 0)
1054 
1055 #define SIGNAL_EPILOGUE(sig, si, saved_errno)                                  \
1056 do {                                                                           \
1057    char _b[1][32];                                                             \
1058    const char *_msgv[]                                                         \
1059    = { signal2string(sig),                                                     \
1060        " ]: finished processing signal ",                                      \
1061        ltoa((sig), _b[0], sizeof(_b[0])),                                      \
1062        NULL                                                                    \
1063    };                                                                          \
1064                                                                                \
1065    signalslog(LOG_DEBUG, _msgv);                                               \
1066                                                                                \
1067    errno = (saved_errno);                                                      \
1068 } while (/* CONSTCOND */ 0)
1069 
1070 #if HAVE_UDP_SUPPORT
1071 
1072 #define MIN_IPHLEN  (20)
1073 #define MAX_IPHLEN  (60)
1074 
1075 #define MIN_UDPLEN   (8)
1076 
1077 #define MAX_ICMPUNREACHLEN (8 + MAX_IPHLEN + MIN_UDPLEN)
1078 #define MIN_ICMPUNREACHLEN (8 + MIN_IPHLEN + MIN_UDPLEN)
1079 
1080 #define ICMP_TYPE_TTLEXCEEDED (11)
1081 #define ICMP_CODE_TTLEXCEEDED_TRANSIT      (1)
1082 
1083 #define ICMP_TYPE_UNREACHABLE (3)
1084 #define ICMP_CODE_UNREACHABLE_HOST             (1)
1085 #define ICMP_CODE_UNREACHABLE_PORT             (3)
1086 #define ICMP_CODE_UNREACHABLE_DESTHOSTUNKNOWN  (7)
1087 #define ICMP_CODE_UNREACHABLE_HOSTPROHIBITED   (13)
1088 
1089 #define IOOP(isblocked, iostatus)                                              \
1090    /* coverity[dead_error_begin] */                                            \
1091    ((isblocked) ?                                                              \
1092       (SOCKS_SERVER ? OPERATION_TMPBLOCK : OPERATION_BLOCK)                    \
1093    /* coverity[dead_error_begin] */                                            \
1094   : ((iostatus) == IO_TMPERROR ?  OPERATION_TMPERROR : OPERATION_ERROR))
1095 
1096 
1097 
1098 typedef enum { RAWSOCKET_NOP,          /* nothing to care about.  */
1099                RAWSOCKET_IO_DELETED    /* an io was deleted.      */
1100 } rawsocketstatus_t;
1101 
1102 
1103 #define SOCKD_IO_PACKETSTATS           (128)
1104 typedef struct {
1105    struct timeval latencyv[SOCKD_IO_PACKETSTATS];
1106    size_t         lastlatencyi;   /* index of last ts added.                  */
1107 
1108    size_t         latencyc;       /* current number of ts's in latencyv.      */
1109 
1110    /* min/max/last/etc. observed latency. */
1111    unsigned long   min_us;
1112    unsigned long   max_us;
1113    unsigned long   last_us;
1114    unsigned long   average_us;
1115    unsigned long   median_us;
1116    unsigned long   stddev_us;
1117 } iostat_t;
1118 
1119 #endif /* HAVE_UDP_SUPPORT */
1120 
1121 typedef enum { TEST_MTU__WAITING_FOR_KEEPALIVE_ACK1 = 1,
1122                TEST_MTU__WAITING_FOR_KEEPALIVE_ACK2
1123 } mtu_error_test_state_t;
1124 
1125 typedef struct {
1126    int              tcp_keepalive;
1127    int              tcp_keepidle;
1128 
1129 #if HAVE_TCP_INFO
1130    struct tcp_info  tcpinfo;
1131 #endif /* HAVE_TCP_INFO */
1132 } mtu_test_state_data_t;
1133 
1134 typedef struct {
1135    struct timeval         start;       /* time we started checking.           */
1136 
1137    mtu_error_test_state_t state;       /* current state.                      */
1138    struct timeval         nextcheck;   /* time next check should be done.     */
1139 
1140    mtu_test_state_data_t initial;
1141    mtu_test_state_data_t current;
1142 } mtu_test_state_t;
1143 
1144 typedef struct {
1145    unsigned         dotest;      /* perform mtu test? */
1146    mtu_test_state_t state;       /* ... state if so.                  */
1147 } mtutest_t;
1148 
1149 typedef struct {
1150    mtutest_t   mtu;
1151 } networktest_t;
1152 
1153 /*
1154  * Similar to networktest_t, but without the state object.
1155  */
1156 typedef struct {
1157    struct {
1158       unsigned tested;
1159    } mtu;
1160 } networktest_tested_t;
1161 
1162 
1163 typedef struct {
1164    unsigned char sameport;     /* always try to use same port as client?   */
1165    unsigned char draft_5_05;   /* try to support parts of socks 5.05 draft */
1166 } compat_t;
1167 
1168 typedef struct {
1169    unsigned char connect;
1170    unsigned char disconnect;
1171    unsigned char data;
1172    unsigned char error;
1173    unsigned char iooperation;
1174    unsigned char tcpinfo;
1175 } log_t;
1176 
1177 typedef struct {
1178    struct sockaddr_storage from; /* clients address.                          */
1179 
1180 #if HAVE_SOCKS_HOSTID            /* hostids set on connection from client.    */
1181    struct in_addr          hostidv[HAVE_MAX_HOSTIDS];
1182    unsigned char           hostidc; /* how many hostids are present/set. */
1183 #endif /* HAVE_SOCKS_HOSTID */
1184 } clientinfo_t;
1185 
1186 typedef enum { key_unset = 0, key_from, key_hostid } statekey_t;
1187 
1188 typedef struct {
1189    /*
1190     * These variables are fixed at creation and are after that never to
1191     * be changed.
1192     */
1193    unsigned long      shmid;            /* shmid of this object.              */
1194    size_t             number;           /* rule/monitor # this object is for. */
1195    objecttype_t       parenttype;       /*
1196                                          * type of object this object belongs
1197                                          * to (rule/monitor/etc.).
1198                                          */
1199 
1200    size_t             clients;          /* # of clients using this object.    */
1201 } shmem_header_t;
1202 
1203 typedef struct {
1204    size_t              bytes;             /* bytes transferred since iotime.  */
1205    struct timeval      iotime;
1206 
1207    unsigned char       maxbps_isset;
1208    size_t              maxbps;            /* max  b/s allowed.                */
1209 } bw_t;
1210 
1211 typedef struct {
1212    /* max number of "clients" to accept within "seconds". */
1213    size_t  clients;
1214    time_t  seconds;
1215 } sessionthrottle_t;
1216 
1217 typedef struct {
1218    unsigned char max_isset;
1219    size_t        max;      /*
1220                             * max number of sessions allowed in total.
1221                             * -1 if there is no total limit for
1222                             * this object, only per-state limits.
1223                             */
1224 
1225    unsigned char throttle_isset;
1226    struct {
1227       sessionthrottle_t limit;
1228       struct timeval    starttime; /* time we last reset the client counter.  */
1229       size_t            newclients;/* new clients since we reset the counter. */
1230    } throttle;
1231 
1232    /*
1233     * Same as the above, but on a per-state basis, if key is set.
1234     */
1235 
1236    size_t            max_perstate;
1237    unsigned char     max_perstate_isset;
1238 
1239    unsigned char     throttle_perstate_isset;
1240    struct {
1241       sessionthrottle_t limit;
1242    } throttle_perstate;
1243 } session_t;
1244 
1245 typedef struct {
1246       statekey_t       key;
1247 
1248       /*
1249        * The rest is only applicable if key is not "key_unset".
1250        */
1251 
1252      time_t lastexpirescan;   /* time of last scan for entries to expire.     */
1253 
1254       /* extra info needed for some keys. */
1255       union {
1256          unsigned char hostindex;     /* index of hostid saved/to use.        */
1257       } keyinfo;
1258 
1259       /*
1260        * NOTE: we use a separate memory mapping for this and that must
1261        * always be temporary; we can map it after getting the lock, but
1262        * must release and NULL the pointer before releasing the lock.
1263        * The reason for this is that multiple processes will map this
1264        * object, and if one of the processes also maps they keymap,
1265        * the other processes will see that the keymap pointer is no
1266        * longer NULL, but that other process will not (yet) have mapped
1267        * the keymap.
1268        */
1269       struct {
1270          union { /* data for the key. */
1271             struct {
1272                sa_family_t        safamily; /* which union member is set.     */
1273                union {
1274                   struct in_addr  ipv4;
1275                   struct in6_addr ipv6;
1276                }                 addr;     /* address of this client.         */
1277 
1278                size_t            addrc;    /* # of clients from address.      */
1279             } from;
1280 
1281             struct {
1282                struct in_addr  ipv4;
1283                size_t          addrc;    /* # of clients from address.      */
1284             } hostid;
1285          } data;
1286 
1287          union { /* extra info for some keys/data. */
1288             struct {
1289                struct timeval starttime;
1290                size_t         newclients;
1291             } ss; /* for session-limits. */
1292          } info;
1293 
1294       } *keyv;
1295       size_t keyc;                  /* number of elements in keyv.            */
1296 } keystate_t;
1297 
1298 typedef struct {
1299    /* must transfer at least <bytes> bytes every <seconds> seconds. */
1300    size_t bytes;
1301    time_t seconds;
1302 } alarm_data_limit_t;
1303 
1304 typedef struct {
1305    unsigned char      isconfigured; /* alarm configured for this side?        */
1306 
1307    unsigned char      ison;         /* alarm is currently on?                 */
1308 
1309    struct timeval     alarmchange;  /* last time alarm switched status.       */
1310 
1311    size_t             bytes;        /* bytes transferred since last reset.    */
1312    struct timeval     lastio;       /* time of last i/o.                      */
1313 
1314    struct timeval     lastreset;    /* timestamp of last reset.               */
1315 
1316    alarm_data_limit_t limit;
1317 } alarm_data_side_t;
1318 
1319 typedef struct {
1320    alarm_data_side_t recv;      /* received from interface.                   */
1321    alarm_data_side_t send;      /* sent to interface.                         */
1322 } alarm_data_t;
1323 
1324 typedef struct {
1325    /*
1326     * if <disconnectc> or more clients or targets have disconnected during
1327     * the last <seconds> seconds, and the ratio of disconnects to the
1328     * current number of sessions is equal or higher than the limit set,
1329     * trigger the alarm.
1330     */
1331    size_t sessionc;
1332    size_t disconnectc;
1333    time_t seconds;
1334 } alarm_disconnect_limit_t;
1335 
1336 typedef struct {
1337    unsigned char  isconfigured;  /* disconnect-alarm configured.              */
1338 
1339    struct timeval lastreset;     /* time of last reset.                       */
1340    size_t         sessionc;      /* number of sessions currently established. */
1341 
1342    /*
1343     * number of disconnects done by peer and number of disconnects done by us
1344     * /since last reset/.
1345     */
1346    size_t         peer_disconnectc;
1347    size_t         self_disconnectc;
1348 
1349    alarm_disconnect_limit_t limit;
1350 } alarm_disconnect_t;
1351 
1352 typedef struct {
1353    struct {
1354       alarm_data_t       data;
1355       alarm_disconnect_t disconnect;
1356 
1357       /*
1358        * tests to perform.
1359        */
1360       networktest_t        test;
1361    } alarm;
1362 } monitor_if_t;
1363 
1364 typedef struct {
1365    monitor_if_t   internal;
1366    monitor_if_t   external;
1367 } monitor_stats_t;
1368 
1369 /* which shmem object.  Bitmask. */
1370 #define SHMEM_NONE                   (0x0)
1371 #define SHMEM_BW                     (0x1)
1372 #define SHMEM_MONITOR                (0x2)
1373 #define SHMEM_SS                     (0x4)
1374 #define SHMEM_ALL                    (SHMEM_BW | SHMEM_MONITOR | SHMEM_SS)
1375 
1376 typedef struct {
1377    shmem_header_t     mstate;
1378    keystate_t         keystate;
1379 
1380    size_t             type; /* which object in union this object is for. */
1381    union {
1382       bw_t            bw;
1383       session_t       ss;
1384       monitor_stats_t monitor;
1385    } object;
1386 } shmem_object_t;
1387 
1388 
1389 typedef struct {
1390    keytype_t key;
1391 
1392    union {
1393       struct in_addr   ipv4;
1394       struct in6_addr  ipv6;
1395       unsigned char     macaddr[ETHER_ADDR_LEN];
1396       time_t           time;
1397    } value;
1398 } licensekey_t;
1399 
1400 typedef struct monitor_t {
1401    objecttype_t     type;
1402 
1403    shmem_object_t   *mstats;
1404    unsigned long    mstats_shmid;
1405    unsigned char    mstats_isinheritable;
1406 
1407    /*
1408     * Should we aggregate counters on interface/sides?  Bitmask set if so.
1409     */
1410    size_t           alarm_data_aggregate;
1411    size_t           alarm_disconnect_aggregate;
1412 
1413 
1414    /*
1415     * used as an optimization to avoid needlessly attach/detach to figure out
1416     * the alarm is not relevant to the current action.
1417     */
1418    size_t           alarmsconfigured;           /* bitmask.                   */
1419 
1420    ruleaddr_t       src;
1421    ruleaddr_t       dst;
1422 
1423    unsigned char    hostidoption_isset;   /* any of the values below set?     */
1424 #if HAVE_SOCKS_HOSTID
1425    ruleaddr_t       hostid;         /*
1426                                      * if atype is not SOCKS_ADDR_NOTSET,
1427                                      * this rule requires a matching hostid.
1428                                      */
1429 
1430    unsigned char    hostindex; /*
1431                                 * address index to match hostid against.
1432                                 * 0 means any, 1 means first index, etc.
1433                                 */
1434 #endif /* HAVE_SOCKS_HOSTID */
1435 
1436    size_t                  number;       /* rulenumber.                       */
1437    size_t                  linenumber;   /* linenumber; info/debugging only.  */
1438 
1439    serverstate_t           state;
1440 
1441    struct monitor_t        *next;          /* next monitor in list.           */
1442 } monitor_t;
1443 
1444 typedef struct {
1445    unsigned char              isconfigured;  /* any options here set?    */
1446 
1447    unsigned                   ecn;
1448    int                        ecn_loglevel;
1449 
1450    unsigned                   sack;
1451    int                        sack_loglevel;
1452 
1453    unsigned                   timestamps;
1454    int                        timestamps_loglevel;
1455 
1456    unsigned                   wscale;
1457    int                        wscale_loglevel;
1458 } warn_protocol_tcp_options_t;
1459 
1460 typedef struct {
1461    struct {
1462       warn_protocol_tcp_options_t enabled;
1463       warn_protocol_tcp_options_t disabled;
1464    } tcp;
1465 } warn_protocol_t;
1466 
1467 
1468 
1469 typedef struct {
1470    /*
1471     * Contains list of errno-values that should be logged additionally,
1472     * at loglevel LOG_EMERG (errno_loglevel[0], LOG_ALERT((errno_loglevel[1]),
1473     * etc.
1474     */
1475    int                     errno_loglevelv[MAXLOGLEVELS][UNIQUE_ERRNO_VALUES];
1476    size_t                  errno_loglevelc[MAXLOGLEVELS];
1477 
1478    /*
1479     * Same as above, but for dns-errors (getaddrinfo(3) and family).
1480     */
1481    int                     gaierr_loglevelv[MAXLOGLEVELS][UNIQUE_GAIERR_VALUES];
1482    size_t                  gaierr_loglevelc[MAXLOGLEVELS];
1483 
1484    /*
1485     * Warnings for certain protocol-spesific things.
1486     */
1487    warn_protocol_t         protocol;
1488 } logspecial_t;
1489 
1490 typedef struct rule_t {
1491    objecttype_t            type;         /* what kind of rule this is.        */
1492    int                     verdict;      /* verdict for this rule.            */
1493 
1494    socketoption_t          *socketoptionv;
1495    size_t                  socketoptionc;
1496 
1497 #if COVENANT
1498    /* if block, why.  XXX why not a more general text string? */
1499    struct {
1500       unsigned char        missingproxyauth;
1501    } whyblock;
1502 #endif /* COVENANT */
1503 
1504 
1505    ruleaddr_t       src;
1506    ruleaddr_t       dst;
1507 
1508    ruleaddr_t       rdr_from;
1509    ruleaddr_t       rdr_to;
1510 
1511    unsigned char    hostidoption_isset;   /* any of the values below set?     */
1512 #if HAVE_SOCKS_HOSTID
1513    ruleaddr_t       hostid;         /*
1514                                      * if atype is not SOCKS_ADDR_NOTSET,
1515                                      * this rule requires a matching hostid.
1516                                      */
1517 
1518    unsigned char    hostindex; /*
1519                                 * address index to match hostid against.
1520                                 * 0 means any, 1 means first index, etc.
1521                                 */
1522 #endif /* HAVE_SOCKS_HOSTID */
1523 
1524    /*
1525     * Extra options only present in certain kind of rules.
1526     */
1527 #if BAREFOOTD
1528    unsigned char           bounced;      /*
1529                                           * have we faked a request for the addr
1530                                           * "dst" already?  Only used for udp.
1531                                           */
1532 
1533    struct {
1534       /*
1535        * address packet from src to dst should be bounced to.
1536        * Is a ruleaddr_t and not sockshost_t because bounce-to port may be
1537        * different for tcp and udp clients if specified as a servicename.
1538        */
1539       ruleaddr_t              bounceto;
1540    } extra;
1541 #endif /* BAREFOOTD */
1542 
1543    log_t                   log;          /* type of logging to do.            */
1544 
1545    struct {
1546       logspecial_t         log;          /* certain special logging.          */
1547    } internal;
1548 
1549    struct {
1550       logspecial_t         log;          /* certain special logging.          */
1551    } external;
1552 
1553 
1554    size_t                  number;       /* rulenumber.                       */
1555    size_t                  linenumber;   /* linenumber; info/debugging only.  */
1556 
1557    serverstate_t           state;
1558    timeout_t               timeout;      /* default or specific for this one. */
1559 
1560    linkedname_t            *user;        /* name of users allowed.            */
1561    linkedname_t            *group;       /* name of groups allowed.           */
1562 
1563    struct {
1564       in_port_t            start;
1565       in_port_t            end;
1566       enum operator_t      op;
1567    } udprange;                           /* udprange, if limited.             */
1568 
1569 #if HAVE_LDAP
1570 
1571    linkedname_t            *ldapgroup;   /* name of ldap groups allowed.      */
1572    unsigned char           ldapsettingsfromuser;
1573 
1574 #endif /* HAVE_LDAP */
1575 
1576 #if HAVE_PAC
1577    linkedname_t            *objectsids;  /* name of sids(=AD groups) allowed. */
1578    unsigned                pacoff;       /* flag to use sids(=AD groups) */
1579 #endif /* HAVE_PAC */
1580 
1581 #if HAVE_LIBWRAP
1582    char                    libwrap[LIBWRAPBUF];   /* libwrapline.             */
1583 #endif /* HAVE_LIBWRAP */
1584 
1585    shmem_object_t          *mstats;                /* Matching monitorstats.  */
1586    unsigned long           mstats_shmid;           /* shmid of monitorstats.  */
1587    unsigned char           mstats_isinheritable;
1588    size_t                  alarmsconfigured;       /* bitmask.                */
1589 
1590    shmem_object_t          *bw;            /* pointer, memory will be shared. */
1591    unsigned long           bw_shmid;       /* shmid of bw, if any.            */
1592    unsigned char           bw_isinheritable;/*
1593                                              * object is inheritable by
1594                                              * higher-level ACLs?
1595                                              */
1596 
1597    shmem_object_t          *ss;            /* pointer, memory will be shared. */
1598    unsigned long           ss_shmid;       /* shmid of ss, if any.            */
1599    unsigned char           ss_isinheritable;/*
1600                                              * object is inheritable by
1601                                              * higher-level ACLs?
1602                                              */
1603 
1604    struct rule_t           *next;      /* next rule in list.                  */
1605 } rule_t;
1606 
1607 typedef struct {
1608    int value;                     /* value of SCHED_foo define                */
1609    char *name;                    /* textual representation of scheduler name */
1610 } cpupolicy_t;
1611 
1612 typedef struct {
1613 
1614    /* scheduling configured for this process? */
1615    unsigned char        scheduling_isset;
1616 
1617 #if HAVE_SCHED_SETSCHEDULER
1618    int                  policy;
1619    struct sched_param   param;
1620 #endif /* HAVE_SCHED_SETSCHEDULER */
1621 
1622    /* affinity configured for this process? */
1623    unsigned char        affinity_isset;
1624 
1625 #if HAVE_SCHED_SETAFFINITY
1626    cpu_set_t            mask;
1627 #endif /* HAVE_SCHED_SETAFFINITY */
1628 
1629 } cpusetting_t;
1630 
1631 typedef struct {
1632    unsigned char nodnsmismatch;  /* deny if mismatch between dns claim/fact?  */
1633    unsigned char nodnsunknown;   /* deny if no dns record?                    */
1634    unsigned char checkreplyauth; /* check that method matches for replies?    */
1635 } srchost_t;
1636 
1637 /*
1638  * NOTE: commandline-options that can override config-file options must have
1639  * a matching _isset attribute and be added to the CMDLINE_OVERRIDE() macro.
1640  */
1641 typedef struct {
1642    char              *configfile;     /* name of config file.                 */
1643 
1644    unsigned char     daemon;          /* run as a daemon?                     */
1645 
1646    int               debug;           /* debug level.                         */
1647    unsigned char     debug_isset;
1648 
1649    int               hosts_access;    /* do hosts_access() lookup?            */
1650 
1651    int               directfallback;  /* fallback to direct connections?      */
1652 
1653    unsigned char     keepalive;       /* set SO_KEEPALIVE?                    */
1654 
1655    char              *pidfile;        /* name of pidfile.                     */
1656    unsigned char     pidfilewritten;  /* did we successfully write pidfile?   */
1657 
1658    size_t            serverc;         /* number of servers.                   */
1659 
1660    unsigned char     verifyonly;      /* syntax verification of config only.  */
1661    unsigned char     versiononly;     /* show version info only.              */
1662 } option_t;
1663 
1664 
1665 #if HAVE_PRIVILEGES
1666 typedef struct {
1667    priv_set_t       *unprivileged;
1668    priv_set_t       *privileged;
1669 } privileges_t;
1670 
1671 #else /* !HAVE_PRIVILEGES */
1672 typedef struct {
1673    unsigned char    privileged_isset;
1674    uid_t            privileged_uid;
1675    gid_t            privileged_gid;
1676 
1677    unsigned char    unprivileged_isset;
1678    uid_t            unprivileged_uid;
1679    gid_t            unprivileged_gid;
1680 
1681    unsigned char    libwrap_isset;
1682    uid_t            libwrap_uid;
1683    gid_t            libwrap_gid;
1684 
1685    unsigned :0;
1686 } userid_t;
1687 #endif /* !HAVE_PRIVILEGES */
1688 
1689 typedef struct {
1690    int                  ack;            /* control-pipe to mother.            */
1691    int                  s;              /* data-pipe to mother.               */
1692 } sockd_mother_t;
1693 
1694 
1695 typedef struct {
1696    unsigned char       inited;
1697 
1698    sig_atomic_t        insignal;          /* executing in signal handler?     */
1699    struct {
1700       sig_atomic_t     signal;
1701       siginfo_t        siginfo;
1702    } signalv[SOCKS_NSIG];                 /* stacked signals.                 */
1703    sig_atomic_t        signalc;           /* number of stacked signals.       */
1704 
1705    /*
1706     * For mother processes only.
1707     */
1708    size_t              unexpected_deaths;
1709    time_t              firstdeath_time;
1710    time_t              lastdeath_time;
1711 
1712    /*
1713     * Sum of rusage for various process types.
1714     * For mother processes only.
1715     */
1716    /* struct rusage       rusage_mother; XXX not supported yet. */
1717    struct rusage       rusage_monitor;
1718    struct rusage       rusage_negotiate;
1719    struct rusage       rusage_request;
1720    struct rusage       rusage_io;
1721 
1722    cpusetting_t   cpu;                  /* current cpusettings, if any set.   */
1723 
1724    pid_t          *motherpidv;          /* pid of mothers.                    */
1725    pid_t          pid;                  /* pid of current process.            */
1726 
1727    int            reservedfdv[1];       /*
1728                                          * Dummy fd we reserve and keep around
1729                                          * so we can temporarily close it if we
1730                                          * need to make a library calls and
1731                                          * it failed because there were no
1732                                          * more free fd's.  E.g. getpwuid(3).
1733                                          */
1734 
1735    unsigned char  haveprivs;            /*
1736                                          * some sort of privileges/euid
1737                                          * switching available?
1738                                          */
1739 
1740    uid_t          euid;                 /* current euid.                      */
1741    gid_t          egid;                 /* current egid.                      */
1742 
1743    int            highestfdinuse;
1744    rlim_t         maxopenfiles;
1745    sockd_mother_t mother;               /* if child, mother info.             */
1746    long           pagesize;
1747    int            type;                 /* process type we are.               */
1748 
1749    int            monitor_ack;          /* control-pipe to monitor process.   */
1750    int            monitor_s;            /* data-pipe to monitor process.      */
1751    time_t         monitor_sent;         /*
1752                                          * last time this process sent an
1753                                          * object to the monitor process.
1754                                          */
1755 
1756 #if BAREFOOTD
1757 
1758    unsigned char  alludpbounced;        /* bounced all udp addresses?         */
1759 
1760 #endif /* BAREFOOTD */
1761 
1762    /*
1763     * The next set of objects allows us to optimize a few things based on
1764     * the currently running configuration.
1765     * If a value is unset it means values can vary from rule to rule.
1766     * Otherwise, the value is fixed and these variables contain the fixed
1767     * value.
1768     * We only care about attributes that can affect rulespermit().  I.e.,
1769     * is it possible that the value of a given attribute can change whether
1770     * rulespermit() will pass or block a session?  If not, no need to care
1771     * about that attribute here.
1772     */
1773 
1774 #if HAVE_PAM
1775 
1776    char          pamservicename[MAXNAMELEN];
1777 
1778 #endif /* HAVE_PAM */
1779 
1780 #if HAVE_BSDAUTH
1781 
1782    char          bsdauthstylename[MAXNAMELEN];
1783 
1784 #endif /* HAVE_BSDAUTH */
1785 
1786 #if HAVE_GSSAPI
1787 
1788    char          gssapiservicename[MAXNAMELEN];
1789    char          gssapikeytab[MAXNAMELEN];
1790 
1791 #endif /* HAVE_GSSAPI */
1792 
1793 #if HAVE_LDAP
1794 
1795    ldapauthorisation_t     ldapauthorisation;
1796    ldapauthentication_t    ldapauthentication;
1797 
1798 #endif /* HAVE_LDAP */
1799 
1800 } configstate_t;
1801 
1802 typedef struct {
1803    /*
1804     * Protocols/address-families operator has configured us to *look for*,
1805     * but not necessarily available.
1806     */
1807    unsigned ipv4;
1808    unsigned ipv6;
1809 
1810    /*
1811     * Protocols we have looked for and found to be available.
1812     */
1813    unsigned char              hasipv4;
1814    unsigned char              hasipv6;
1815 
1816    /* at least one of our IPv6 addresses has global scope. */
1817    unsigned char              hasipv6_globalscope;
1818 } interfaceprotocol_t;
1819 
1820 typedef struct {
1821    int                     s;           /* socket we listen on.               */
1822    struct sockaddr_storage addr;        /* address we listen on.              */
1823 
1824    int                     protocol;    /*
1825                                          * Is socket SOCKS_TCP or SOCKS_UDP?
1826                                          * UDP only applicable to barefoot.
1827                                          */
1828 } listenaddress_t;
1829 
1830 typedef struct {
1831    interfaceprotocol_t     protocol;
1832 
1833    listenaddress_t         *addrv;     /* addresses.                          */
1834    size_t                  addrc;
1835 
1836    logspecial_t            log; /* special logging; problems on internal side */
1837 } internaladdress_t;
1838 
1839 typedef struct {
1840    interfaceprotocol_t     protocol;
1841 
1842    ruleaddr_t              *addrv;           /* addresses.                    */
1843    size_t                  addrc;
1844 
1845    int                     rotation;         /* how to rotate, if at all.     */
1846 
1847    logspecial_t            log; /* special logging; problems on external side */
1848 } externaladdress_t;
1849 
1850 typedef struct {
1851    size_t                  accepted;         /* accepts done.                 */
1852    time_t                  boot;             /* time of server start.         */
1853    time_t                  configload;       /* time config was last loaded.  */
1854 
1855    struct {
1856       size_t               sendt;            /* clients sent to children.     */
1857       size_t               received;         /* clients received back.        */
1858    } negotiate;
1859 
1860    struct {
1861       size_t               sendt;            /* clients sent to children.     */
1862       size_t               received;         /* clients received back.        */
1863    } request;
1864 
1865    struct {
1866       size_t               sendt;            /* clients sent to children.     */
1867       size_t               received;         /* acks received back.           */
1868    } io;
1869 } statistic_t;
1870 
1871 typedef struct {
1872 #ifdef HAVE_VOLATILE_SIG_ATOMIC_T
1873    sig_atomic_t            noaddchild;          /* okay to do a addchild()?   */
1874    sig_atomic_t            noaddchild_errno;    /* if not, why not.           */
1875 #else
1876    volatile sig_atomic_t   noaddchild;          /* okay to do a addchild()?   */
1877    volatile sig_atomic_t   noaddchild_errno;    /* if not, why not.           */
1878 #endif /* HAVE_VOLATILE_SIG_ATOMIC_T */
1879    const char              *noaddchild_reason;  /* and our own txt, or NULL.  */
1880 
1881    size_t                  maxrequests;         /*
1882                                                  * max # of requests to handle
1883                                                  * before quitting.
1884                                                  * 0 if unlimited.
1885                                                  */
1886 
1887    size_t                  maxlifetime;         /*
1888                                                  * max seconds to live
1889                                                  * before quitting.
1890                                                  * 0 if forever.
1891                                                  */
1892 } childstate_t;
1893 
1894 typedef struct {
1895    unsigned long  id;
1896    statekey_t     key;
1897    size_t         type; /* type of shmem-object.                              */
1898 } oldshmeminfo_t;
1899 
1900 
1901 /*
1902  * Make sure to keep in sync with resetconfig().
1903  *
1904  * Also try to avoid adding pointers to this object.  Any pointers added
1905  * *MUST* to be synced with the shmem config copy functions in
1906  * sockd_shmemconfig.c, while non-pointers are handled automatically.
1907  */
1908 
1909 struct config {
1910    struct { /* initial/pre-config settings that we want to save. */
1911       option_t           cmdline;   /* original cmdline options. */
1912       cpusetting_t       cpu;
1913 
1914 #if !HAVE_PRIVILEGES
1915       uid_t              euid;
1916       gid_t              egid;
1917 #endif /* !HAVE_PRIVILEGES */
1918 
1919       res_options_type_t res_options;
1920    }                          initial;
1921 
1922    internaladdress_t          internal;   /* internal addresses.              */
1923    externaladdress_t          external;   /* external addresses.              */
1924 
1925    struct {
1926       cpusetting_t mother;
1927       cpusetting_t negotiate;
1928       cpusetting_t request;
1929       cpusetting_t io;
1930       cpusetting_t monitor;
1931    }                          cpu;
1932 
1933    rule_t                     *crule;              /* clientrules, list.      */
1934    rule_t                     *hrule;              /* hostidrules, list.      */
1935    rule_t                     *srule;              /* socksrules, list.       */
1936 
1937    routeoptions_t             routeoptions;        /* global route flags.     */
1938    route_t                    *route;
1939 
1940    monitor_t                  *monitor;            /* monitors, list.         */
1941    struct {
1942       /*
1943        * If a session has been idle this amount of seconds, mark it as
1944        * a candidate for testing MTU-related problems.
1945        */
1946       time_t                  mtu_timeout;
1947    } monitorspec;
1948 
1949    socketoption_t             *socketoptionv;      /* global socket options.  */
1950    size_t                     socketoptionc;
1951 
1952    int                        hostfd;              /*
1953                                                     * shmem file/lock for
1954                                                     * hostcache.
1955                                                     */
1956 
1957 #if HAVE_LDAP
1958 
1959    int                        ldapfd;              /*
1960                                                     * shmem file/lock for
1961                                                     * ldap cache.
1962                                                     */
1963 #endif /* HAVE_LDAP */
1964 
1965    int                        shmemfd;             /*
1966                                                     * shmem file/lock for
1967                                                     * shared memory, *and*
1968                                                     * for holding shmeminfo.
1969                                                     */
1970 
1971    int                        shmemconfigfd;       /*
1972                                                     * For mapping the shmem
1973                                                     * config.
1974                                                     */
1975 
1976    struct {
1977       /*
1978        * address of shmemconfig in mothers process.  Children
1979        * need to know so they can calculate the correct
1980        * offset of pointers in the shmem area they copy from
1981        * mother.
1982        */
1983       struct config *config;
1984 
1985       /* size of config, with all allocated pointer memory. */
1986       size_t        configsize;
1987    } *shmeminfo;
1988    char                       shmem_fnamebase[PATH_MAX];
1989 
1990    oldshmeminfo_t             *oldshmemv; /* old shmem, not yet deleted.      */
1991    size_t                     oldshmemc;
1992 
1993    compat_t                   compat;               /* compatibility options. */
1994    extension_t                extension;            /* extensions set.        */
1995 
1996    logtype_t                  errlog;               /* for errors only.       */
1997    logtype_t                  log;                  /* where to log.          */
1998    int                        loglock;              /* lockfile for logging.  */
1999 
2000    option_t                   option;               /*
2001                                                      * options that can be
2002                                                      * set on the commandline
2003                                                      * also.
2004                                                      */
2005 
2006    int                        resolveprotocol;      /* resolve protocol.      */
2007    srchost_t                  srchost;              /* relevant to srchost.   */
2008    statistic_t                stat;                 /* some statistics.       */
2009    configstate_t              state;
2010    timeout_t                  timeout;
2011 
2012 #if HAVE_PRIVILEGES
2013     privileges_t              privileges;
2014 #else /* !HAVE_PRIVILEGES */
2015    userid_t                   uid;
2016 #endif /* !HAVE_PRIVILEGES */
2017 
2018    childstate_t               child;                   /* childstate.         */
2019 
2020    int                        cmethodv[METHODS_KNOWN]; /* clientmethods.      */
2021    size_t                     cmethodc;                /* methods set in list.*/
2022 
2023    int                        smethodv[METHODS_KNOWN];/* methods by priority. */
2024    size_t                     smethodc;               /* methods set in list. */
2025 
2026    unsigned char              udpconnectdst;          /* connect udp sockets? */
2027 
2028 #if HAVE_LIBWRAP
2029    char                       *hosts_allow_original;/* original libwrap value */
2030    char                       *hosts_deny_original; /* original libwrap value */
2031 #endif /* HAVE_LIBWRAP */
2032 #if COVENANT
2033    char                       realmname[256];
2034 #endif /* COVENANT */
2035 };
2036 
2037 typedef struct {
2038    int                  proxyprotocol; /* proxyprotocol used with this proxy. */
2039    sockshost_t          extaddr; /* external address proxyserver may be using */
2040 } proxychaininfo_t;
2041 
2042 
2043 typedef struct {
2044    int                  command;
2045    int                  protocol;
2046    int                  proxyprotocol;
2047 
2048 #if HAVE_SOCKS_HOSTID
2049    /*
2050     * The hostids on the control connection.
2051     * Assumes hostids can only be set on TCP sessions, which
2052     * is currently the case.
2053     */
2054    struct in_addr hostidv[HAVE_MAX_HOSTIDS];
2055    unsigned char  hostidc; /* how many hostids are present/set. */
2056 #endif /* HAVE_SOCKS_HOSTID */
2057 
2058    proxychaininfo_t     proxychain;    /* only if proxyprotocol is not direct.*/
2059    extension_t          extension;     /* extensions set.                     */
2060 
2061    struct {
2062       struct timeval    accepted;      /* time connection accepted.           */
2063       struct timeval    negotiatestart;/* time negotiation started.           */
2064       struct timeval    negotiateend;  /* time negotiation ended.             */
2065       struct timeval    requestend;    /* time requestprocesssing ended.      */
2066       struct timeval    established;   /* time session was fully established. */
2067       struct timeval    firstio;       /* time of first i/o operation.        */
2068    } time;
2069 
2070    const char           *tcpinfo;      /* tcpinfo, if available/relevant.     */
2071 } connectionstate_t;
2072 
2073 typedef struct {
2074    uint64_t         bytes;        /* byte count.                              */
2075    /*
2076     * packet count.  For UDP this is the number of packets we have
2077     * sent (or at least handed of to the kernel), while for TCP it
2078     * corresponds to the number of i/o operations done.
2079     */
2080    uint64_t         packets;
2081 
2082    struct timeval   lastio;       /* time of last i/o operation.              */
2083 } iocount_t;
2084 
2085 
2086 /* common header for data packets to/from child. */
2087 typedef struct {
2088    unsigned char command;     /*
2089                                * Command from child.  Same as command
2090                                * read over ack-pipe, but if sent here,
2091                                * will not be sent over ack-pipe.
2092                                */
2093 } reqinfo_t;
2094 
2095 typedef struct {
2096    int                     s;     /* socket we use to send/receive to remote. */
2097 
2098    struct sockaddr_storage laddr;     /* address we receive remote replies on.*/
2099    struct sockaddr_storage raddr;     /* target address we forward packets to.*/
2100    struct sockshost_t      raddrhost; /* raddr on sockshost_t form.           */
2101 
2102 #if BAREFOOTD /* Dante has only one client, but Barefoot can have many. */
2103    struct sockaddr_storage client;     /* address of our client.              */
2104    sockshost_t             clienthost; /* client on sockshost_t form.         */
2105 
2106    /*
2107     * client-rule matched for this particular client.
2108     */
2109    rule_t          crule;
2110 #endif /* BAREFOOTD */
2111 
2112    unsigned char   isconnected;    /* socket connected to target?             */
2113 
2114    /*
2115     * read from client in relation with this target.
2116     */
2117    iocount_t       client_read;
2118    iocount_t       client_written; /* written to client.                      */
2119 
2120    /*
2121     * read from target in relation with this client.
2122     */
2123    iocount_t       target_read;
2124    iocount_t       target_written;
2125 
2126    struct timeval  firstio;        /* time of first i/o operation.            */
2127    struct timeval  lastio;         /* time of last i/o operation.             */
2128 } udptarget_t;
2129 
2130 
2131 typedef struct {
2132    int                 s;          /* socket connection.               */
2133    struct sockaddr_storage laddr;  /* local address of s.              */
2134    struct sockaddr_storage raddr;  /* address of s's (last) peer.      */
2135 
2136    authmethod_t        auth;        /* authentication in use on s.     */
2137    sockshost_t         host;
2138    /*
2139     * Varies according to context.
2140     * src    : same as raddr.
2141     *
2142     * dst    : raddr as given by client.  Note that if a serverchain is used,
2143     *          raddr is the remote proxy's address, while host is still the
2144     *          raddr as given by client.  (Don't know what the resolved raddr
2145     *          was).
2146     *
2147     * control: same as raddr
2148    */
2149 
2150    /* these are socket counts, not from/to our internal userspace buffer. */
2151    iocount_t                  read;         /* read from socket s.            */
2152    iocount_t                  written;      /* written to socket s.           */
2153 
2154    int                        flags;        /* misc. flags                    */
2155    unsigned char              isclientside; /* is this the clientside?        */
2156 
2157    struct {
2158       unsigned char alarmdisconnectdone;
2159       unsigned char isconnected;    /* socket is connected?                   */
2160       int           err;            /* current errno.                         */
2161       unsigned char fin_received;   /* received FIN on this socket?           */
2162       unsigned char use_saved_srule;/*
2163                                      * should we try to reuse last rule result
2164                                      * for udp packets _received_ on this
2165                                      * socket?
2166                                      */
2167    } state;
2168 
2169 #if HAVE_UDP_SUPPORT
2170    /*
2171     * For TCP, there is only one peer/target/destination, and that is
2172     * either an ipv4 or an ipv6 peer.
2173     *
2174     * For UDP things can be different.
2175     *
2176     * In Dante's case, if the client sends to both IPv4 and IPv6 targets,
2177     * we want to use a local IPv4 address/socket for sending to IPv4 targets
2178     * and an IPv4 address/socket for sending to IPv6 targets.
2179     * For this reason there are up to two dst objects if it's a udp session;
2180     * one for IPv4 and one for IPv6.  We allocate them as needed, so
2181     * we end up having one of following number of target sockets for a
2182     * client:
2183     *    - zero (no packets forwarded from client).
2184     *    - one (packets forwarded to only one type of address (ipv4 or ipv6,
2185     *      but not both).
2186     *    - two (packets forwarded to both ipv4 and ipv6 addresses).
2187     * This however assumes our external interface has both IPv4 and IPv6
2188     * addresses.  Does it not, at most one target socket will be created.
2189     *
2190     * In Barefoots case, we don't have a TCP control-session, so the scenario
2191     * is one-to-many; we receive all udp packets from different clients on
2192     * the one source socket, and we forward them to various targets based
2193     * what client it was received from.  Since the target is hardcoded in
2194     * the sockd.conf, there can be only one target for packets we receive
2195     * from a client (the same client can however send to us on different
2196     * internal addresses, in which case the target may also differ, but
2197     * that creates a separate session; one session per internal listen
2198     * address).
2199     */
2200 
2201    /* only used on the destination side, NULL otherwise. */
2202    udptarget_t                   *dstv;
2203    size_t                        dstcmax;  /* number of slots in dstv array.  */
2204    size_t                        dstc;     /* # of slots currently in use.    */
2205 #endif /* HAVE_UDP_SUPPORT */
2206 } sockd_io_direction_t;
2207 
2208 /*
2209  * part of objects received between processes, but where the size is not
2210  * fixed.  Not used yet.
2211  */
2212 typedef struct {
2213    void   *gssapidata;
2214    size_t gssapidatalen;
2215 
2216    void   *socketoptiondata;
2217    size_t socketoptdatalen;
2218 } dynamicdata_t;
2219 
2220 #define MAX_DYNAMICDATA()                                                      \
2221    (                                                                           \
2222       MAX_GSS_STATE                                                            \
2223     + sizeof(socketoption_t) * MAX_EXTERNAL_SOCKETOPTIONS                      \
2224    )
2225 
2226 
2227 typedef struct sockd_io_t {
2228    unsigned char          allocated; /* object currently allocated?           */
2229 
2230    reqinfo_t              reqinfo;   /* info from child about this request.   */
2231 
2232    connectionstate_t      state;
2233    authmethod_t           cauth;     /* client authentication in use.         */
2234    requestflags_t         reqflags;  /* original client request flags.        */
2235 
2236    sockd_io_direction_t   control;  /* clients controlconnection.             */
2237    sockd_io_direction_t   src;      /* client we receive data from.           */
2238    sockd_io_direction_t   dst;      /* remote peer.                           */
2239 
2240    dynamicdata_t          data;
2241 
2242    /*
2243     * data received from the client that should be sent to the remote server,
2244     * but has not yet.
2245     */
2246 #if HAVE_NEGOTIATE_PHASE
2247    char        clientdata[MAXREQLEN];
2248    size_t      clientdatalen;
2249 #endif /* HAVE_NEGOTIATE_PHASE */
2250 
2251 
2252    rule_t              crule;       /* client rule matched.                   */
2253 
2254 #if HAVE_SOCKS_HOSTID
2255    unsigned char       hrule_isset;
2256    rule_t              hrule;       /* rule matched for hostid().             */
2257 #endif /* HAVE_SOCKS_HOSTID */
2258 
2259    rule_t              srule;       /* socks-rule matched.                    */
2260 
2261    socketoption_t      extsocketoptionv[MAX_EXTERNAL_SOCKETOPTIONS];
2262    size_t              extsocketoptionc;
2263 
2264     union {
2265       struct {
2266          /*
2267           * These are pointers since they are only used in the i/o processes.
2268           * Making them pointers lets us save on the size of the i/o object
2269           * when passing it around.
2270           *
2271           * If the corresponding "use_saved_rule" variable is set, it
2272           * is possible (given some other constraints) that we can
2273           * reuse a previous rulespermit(), the resulting rule of which
2274           * is stored in these objects.
2275           */
2276          rule_t *sfwdrule;   /* for packets forwarded from client  */
2277          rule_t *sreplyrule; /* for packets forwarded from target. */
2278       } udp;
2279 
2280 #if SOCKS_SERVER
2281       struct {
2282          /*
2283           * the i/o-process only handles bind replies, but may need to log
2284           * information related to the bind session that initiated the
2285           * bind reply session also.
2286           */
2287          sockshost_t host;
2288          rule_t      rule;
2289       } bind;
2290 #endif /* SOCKS_SERVER */
2291    } cmd; /* extra info required for certain commands. */
2292 
2293    struct timeval     lastio;          /* time of last i/o operation.         */
2294 
2295    /* tests already done/scheduled on this object. */
2296    struct {
2297       networktest_tested_t     internal;
2298       networktest_tested_t     external;
2299    } tested;
2300 
2301    struct sockd_io_t  *next;           /* for bind-extension.                 */
2302 } sockd_io_t;
2303 
2304 
2305 typedef struct {
2306    reqinfo_t         reqinfo;    /* info from child about this request. */
2307    struct timeval    accepted;   /* time client was accepted.           */
2308 
2309    int               s;          /* socket client was accepted on.      */
2310    struct sockaddr_storage from;       /* client's control address.           */
2311    struct sockaddr_storage to;         /* address we accepted client on.      */
2312 
2313 
2314 #if COVENANT
2315    /*
2316     * if not zero, this is an "old" client that has been sent back
2317     * to the negotiate process from the i/o process, due to the client
2318     * changing it's target (remote http server).
2319     * "clientdata" contains the request received from the client,
2320     * already parsed into "request".
2321     */
2322    char                   clientdata[MAXREQLEN];
2323    size_t                 clientdatalen;
2324 
2325    authmethod_t           auth;
2326    request_t              request;
2327 #endif /* COVENANT */
2328 } sockd_client_t;
2329 
2330 typedef struct negotiate_state_t {
2331    unsigned char        complete;     /* completed?                           */
2332 
2333 #if SOCKS_SERVER
2334    unsigned char        mem[ 1                       /* VER                   */
2335                            + 1                       /* NMETHODS              */
2336                            + (AUTHMETHOD_MAX + 1)    /* METHODS               */
2337 #if HAVE_GSSAPI
2338                            + MAXGSSAPITOKENLEN
2339 #endif /* HAVE_GSSAPI */
2340                            + sizeof(request_t)
2341                            + sizeof(authmethod_t)   /*
2342                                                      * size authmethod uname
2343                                                      * really, but include the
2344                                                      * whole struct as if
2345                                                      * not we will surly forget
2346                                                      * to change this if a
2347                                                      * bigger authmethod is
2348                                                      * ever added.
2349                                                      */
2350                            ];
2351 #elif COVENANT
2352    /* no fixed limit in the http protocol?  Try this for now. */
2353    unsigned char        mem[MAXREQLEN];
2354 
2355    unsigned char         haverequestedproxyauth;
2356    unsigned char         havedonerulespermit;
2357 #endif /* COVENANT */
2358 
2359    size_t               reqread;                     /* read so far.          */
2360    size_t               start;                       /* start of current req  */
2361    char                 emsg[512];                   /* error message, if any.*/
2362    negotiate_result_t   (*rcurrent)(int s,
2363                                     request_t *request,
2364                                     struct negotiate_state_t *state);
2365 
2366    sockshost_t          src;          /* client's address.                    */
2367    sockshost_t          dst;          /* our address.                         */
2368 
2369    rule_t               *crule;        /* client-rule that permitted client.  */
2370 #if HAVE_GSSAPI
2371    unsigned short       gssapitoken_len; /* length of token we're working on. */
2372 #endif /* HAVE_GSSAPI */
2373 } negotiate_state_t;
2374 
2375 typedef struct {
2376    unsigned char       allocated;
2377 
2378 
2379    request_t           req;
2380    negotiate_state_t   negstate;
2381 
2382    rule_t              crule;       /* client-rule matched.            */
2383    authmethod_t        cauth;       /* authentication for clientrule.  */
2384 
2385 #if HAVE_SOCKS_HOSTID
2386    unsigned char       hrule_isset;
2387    rule_t              hrule;       /* rule matched for hostid().      */
2388 #endif /* HAVE_SOCKS_HOSTID */
2389 
2390 #if COVENANT
2391    rule_t              srule;       /* rule matched at socks-level.    */
2392 #endif /* COVENANT */
2393    authmethod_t        sauth;       /* authentication for socks-rule.  */
2394 
2395    int                 s;           /* client connection.              */
2396    connectionstate_t   state;       /* state of connection.            */
2397 } sockd_negotiate_t;
2398 
2399 typedef struct sockd_request_t {
2400    reqinfo_t           reqinfo;   /* info from child about this request. */
2401    struct sockaddr_storage from;  /* client's control address.           */
2402    struct sockaddr_storage to;    /* address client was accepted on.     */
2403 
2404    request_t           req;       /* request to perform.                 */
2405 
2406    rule_t              crule;     /* client-rule matched.                */
2407    authmethod_t        cauth;     /* client authentication in use.       */
2408 
2409 #if HAVE_SOCKS_HOSTID
2410    rule_t              hrule;      /* hostid-rule matched, if any.       */
2411    unsigned char       hrule_isset;
2412 #endif /* HAVE_SOCKS_HOSTID */
2413 
2414 
2415    rule_t              srule;      /* rule matched at socks-level.       */
2416    unsigned char       srule_isset;/* did we progress far enough to use srule?*/
2417 
2418    authmethod_t        sauth;      /* socks authentication in use.       */
2419 
2420    int                 s;         /* clients control connection.         */
2421    connectionstate_t   state;     /* state of connection.                */
2422 
2423 #if HAVE_NEGOTIATE_PHASE          /* initial request from client.        */
2424    char                       clientdata[MAXREQLEN];
2425    size_t                     clientdatalen;
2426 #endif /* HAVE_NEGOTIATE_PHASE */
2427 } sockd_request_t;
2428 
2429 
2430 typedef struct {
2431    unsigned char    waitingforexit; /*
2432                                      * waiting for child to exit.  If set,
2433                                      * pipes should be -1 and no more clients
2434                                      * should be sent to this child, nor
2435                                      * should it be included in any counts.
2436                                      *
2437                                      * Basically just waiting for the SIGCHLD
2438                                      * so we can add it's resourceusage to
2439                                      * our counters.
2440                                      */
2441    unsigned char    exitingnormally;/* exiting normally, on our request?      */
2442 
2443    int              ack;            /* connection to child for acks.          */
2444    int              s;              /* connection to child for data.          */
2445 
2446    pid_t            pid;            /* childs pid.                            */
2447    int              type;           /* child type.                            */
2448 
2449    time_t           created;        /* time created.                          */
2450    size_t           freec;          /* free slots at the moment.              */
2451    size_t           sentc;          /* clients sent to this child.            */
2452 
2453 #if BAREFOOTD
2454    unsigned char    hasudpsession;  /*
2455                                      * is one of the slots taken by an udp
2456                                      * session at the moment?
2457                                      */
2458 #endif /* BAREFOOTD */
2459 } sockd_child_t;
2460 
2461 typedef struct {
2462    /*
2463     * Note that these are not necessarily the physical endpoints.  It could
2464     * be this object refers to a connection via a proxy server, in which
2465     * case "local" will be the address of the proxy server we connected to,
2466     * while "peer" will be the address (we believe) the proxy server is
2467     * using on our behalf.
2468     */
2469    unsigned char  local_isset;
2470    sockshost_t    local;  /* local endpoint if known.  */
2471 
2472    unsigned char  peer_isset;
2473    sockshost_t    peer;   /* remote endpoint if known. */
2474 
2475    /*
2476     * auth used on the connection between local and peer, if set.
2477     */
2478    unsigned char  auth_isset;
2479    authmethod_t   auth;
2480 
2481 #if HAVE_SOCKS_HOSTID
2482    /*
2483     * if set, the hostids of servers between local and peer.
2484     * Not to be confused with a possible proxy server used by us to
2485     * establish a session with peer.
2486     */
2487    struct in_addr hostidv[HAVE_MAX_HOSTIDS];
2488    unsigned char  hostidc; /* how many hostids are actually present/set. */
2489 #endif /* HAVE_SOCKS_HOSTID */
2490 } iologaddr_t;
2491 
2492 void
2493 io_updatemonitor(sockd_io_t *io);
2494 /*
2495  * Updates "io" according to the current monitor configuration.
2496  */
2497 
2498 void
2499 io_add_alarmdisconnects(sockd_io_t *io, const char *reason);
2500 /*
2501  * Called when the session belonging to "io" is to be removed and adds
2502  * any alarm disconnects not yet done.  "reason" is the reason for the
2503  * disconnect.
2504  */
2505 
2506 void
2507 io_update(const struct timeval *timenow, const size_t bwused,
2508           const iocount_t *internal_read, const iocount_t *internal_written,
2509           const iocount_t *external_read, const iocount_t *external_written,
2510           rule_t *rule, rule_t *packetrule, const int lock);
2511 /*
2512  * update the time/bw counters in "rule" and/or "packetrule" according to
2513  * the arguments.
2514  *
2515  * In the case of a TCP session, "rule" and "packetrule" are the same,
2516  * but in the case of a SOCKS UDP session, they can differ, with "packetrule"
2517  * being the rule matched for the given UDP packet transfer, while "rule"
2518  * is, as for TCP, the rule that controls the resources (bandwidth, session,
2519  * etc.).
2520  *
2521  * "bwused" is the bandwidth used at time "timenow", while
2522  * the iocount_t variables provide more detailed information about
2523  * what was read/written from/to where.
2524  */
2525 
2526 iostatus_t
2527 doio_tcp(sockd_io_t *io, fd_set *rset, fd_set *wset,
2528          const int flags, int *badfd);
2529 /*
2530  * Does i/o over the descriptors in "io", in to out and out to in.
2531  * "io" is the object to do i/o over,
2532  * "flags" is the flags to set on the actual i/o calls
2533  * (read()/write(), recvfrom()/sendto()), currently only MSG_OOB.
2534  *
2535  * Returns the status of the doio() call, IO_NOERROR on success, or
2536  * some other value on error.  If "badfd" is not -1, it will have the value
2537  * of the file descriptor on which the error was detected.
2538  *
2539  * In most cases, io_delete() should be called upon error.
2540  */
2541 
2542 
2543 #if HAVE_UDP_SUPPORT
2544 
2545 iostatus_t
2546 doio_udp(sockd_io_t *io, fd_set *rset, int *badfd);
2547 /*
2548  * does io over the udp sockets in "io".  "rset" is a set where at least
2549  * one of the fds matches a readable fd in io
2550  *
2551  * Returns the status of the i/o operation.  If an error is detected,
2552  * "badfd" contains the fd related to the error (io->src.s or io->dst.s).
2553  */
2554 
2555 iostatus_t
2556 io_packet_received(const recvfrom_info_t *recvflags,
2557                    const size_t bytesreceived,
2558                    const struct sockaddr_storage *from,
2559                    const struct sockaddr_storage *receivedon);
2560 
2561 /*
2562  * Called immedidately after a udp packet has been received.
2563  *
2564  * "recvflags" are the values set when receiving the packet.
2565  * "bytesreceived" gives the length of the packet received.
2566  * "from" is the address that sent the packet.
2567  * "receiveon" is the address we received the packet on.
2568  *
2569  * Normally returns IO_NOERROR, but if something is wrong with the packet,
2570  * the appropriate error is logged and a failurecode is returned.
2571  */
2572 
2573 iostatus_t
2574 io_packet_sent(const size_t bytestosend,
2575                const size_t bytessent,
2576                const struct timeval *tsreceived,
2577                const struct sockaddr_storage *from,
2578                const struct sockaddr_storage *to,
2579                char *emsg, size_t emsglen);
2580 /*
2581  * Called immediately after a udp packet has been sent.
2582  *
2583  * "bytestosend" gives the number of bytes we were supposed to send, while
2584  * "bytessent" gives the number of bytes actually sent.
2585  *
2586  * "tsreceived" is the time when the bytes we just sent was received.
2587  *
2588  * "from" is the address from which the packet was received.
2589  *
2590  * "to" is the address to which we sent the packet.
2591  *
2592  * Returns IO_NOERROR if everything is ok, or a failurecode on error.
2593  * If error, the reason for error is stored in "emsg".
2594  */
2595 
2596 
2597 in_port_t *udphdr_uh_dport(struct udphdr *udp);
2598 in_port_t *udphdr_uh_sport(struct udphdr *udp);
2599 uint16_t *udphdr_uh_ulen(struct udphdr *udp);
2600 uint16_t *udphdr_uh_sum(struct udphdr *udp);
2601 /*
2602  * Wrappers to access the member due to difference in naming between
2603  * BSD and linux.
2604  */
2605 
2606 
2607 
2608 udptarget_t *
2609 clientofsocket(const int s, const size_t udpclientc,
2610                udptarget_t *udpclientv);
2611 /*
2612  * Returns the udpclient belonging to socket "s", or NULL if no
2613  * such client.
2614  */
2615 
2616 void
2617 io_syncudp(sockd_io_t *io, udptarget_t *udpclient);
2618 /*
2619  * Syncs the i/o-object "io" based on the contents of "udpclient".
2620  * In Barefoot, udp is a point-to-multipoint case: we receive all client
2621  * packets on one socket, but use different outgoing sockets for each client.
2622  * We use this function to sync the necessary parts of the udpclient to the
2623  * io object before usage.
2624  */
2625 
2626 void
2627 io_syncudpdst(sockd_io_direction_t *dst, const udptarget_t *udptarget);
2628 /*
2629  * syncs only the "dst" part of an i/o object with "udptarget".
2630  */
2631 
2632 
2633 void
2634 io_syncudpsrc(sockd_io_direction_t *src, const udptarget_t *udpclient);
2635 /*
2636  * Syncs only the "src" part of an i/o object based on "udpclient".
2637  */
2638 
2639 #if BAREFOOTD
2640 
2641 rawsocketstatus_t
2642 rawsocket_recv(const int s, const size_t ioc, sockd_io_t iov[]);
2643 /*
2644  * Handles packets input on the raw socket "s".
2645  * Used to read icmp-errors concerning packets we send to/from udp clients.
2646  */
2647 
2648 int
2649 removeclient(const int s, size_t *clientc, udptarget_t *clientv);
2650 /*
2651  * Removes the udpclient associated with the socket "s" from the
2652  * "clientv" array, which contains "clientc" elements, and decrements
2653  * "clientc".
2654  * Returns 0 on success, -1 on failure.
2655  */
2656 
2657 
2658 udptarget_t *
2659 clientofclientaddr(const struct sockaddr_storage *addr,
2660                    const size_t udpclientc, udptarget_t *udpclientv);
2661 /*
2662  * Returns the udpclient that has the client address "addr", or NULL
2663  * if no such client exists.
2664  */
2665 
2666 #endif /* BAREFOOTD */
2667 
2668 size_t
2669 io_udpclients(const size_t ioc, const sockd_io_t iov[], const ssize_t mincount);
2670 /*
2671  * Returns the number of active udp clients.
2672  *
2673  * If "mincount" is not -1, returns as soon as at least "mincount" active
2674  * udp clients have been counted, rather than scanning till the end of
2675  * iov to count all possible clients.
2676  */
2677 
2678 
2679 #if HAVE_SO_TIMESTAMP
2680 void
2681 io_addts(const struct timeval *ts, const struct sockaddr_storage *from,
2682          const struct sockaddr_storage *to);
2683 /*
2684  * adds timestamp "ts" to the object we use to keep latency timestamps.
2685  * The ts is the time it took from a packet from "from" was received
2686  * by the kernel, until it was sent out on the correct socket, to "to".
2687  *
2688  * If "to" is NULL, it means this is only the time it took us to read
2689  * the packet out of the socket buffer.
2690  */
2691 
2692 struct timeval *
2693 io_calculatelatency(const struct timeval *ts_recv, const struct timeval *tnow,
2694              struct timeval *latency);
2695 /*
2696  * Calculates the packet latency for a packet received at "ts_recv" until
2697  * the current time, given as "tnow".
2698  *
2699  * The calculated latency is stored in "latency".
2700  *
2701  * Returns a pointer to latency.
2702  */
2703 
2704 #endif /* HAVE_SO_TIMESTAMP */
2705 
2706 iostat_t *io_get_ro_stats(void);
2707 iostat_t *io_get_io_stats(void);
2708 /*
2709  * Returns a pointer to the current (updated) iostats for read-only latency,
2710  * or i/o latency, accordingly to the function called.
2711  *
2712  * Returns NULL if information is not yet available.
2713  */
2714 
2715 void
2716 send_icmperror(const int s, const struct sockaddr_storage *receivedonaddr,
2717                const struct sockaddr_storage *originalpacketsrc,
2718                const struct sockaddr_storage *packettarget,
2719                const int iplen, const int udplen,
2720                const int type, const int code);
2721 /*
2722  * Handles packets output in on the raw socket "s".  Used to send icmp-errors
2723  * concerning packets we could not forward.
2724  *
2725  * "receivedonaddr" is the local address on which we received the packet we
2726  * could not forward.
2727  *
2728  * "originalpacketsrc" is the address which sent the packet we could not
2729  *
2730  * forward (client or remote target).
2731  *
2732  * "packettarget" it the target address the packet we could not forward
2733  * was intended for (client or remote target).
2734  *
2735  * "iplen" is the length of the IP packet containing the udp datagram we could
2736  * not send, or -1 if unknown.
2737  *
2738  * "udplen" is the length of the udp datagram we could not send, or -1 if
2739  * unknown.
2740  *
2741  * "type" and "code" is the icmp type and code we should use when sending the
2742  *  icmperror.
2743  */
2744 
2745 udptarget_t *
2746 initclient(const int control,
2747            const struct sockaddr_storage *client_laddr,
2748            const struct sockaddr_storage *client_raddr,
2749            const sockshost_t *tohost,
2750            const struct sockaddr_storage *toaddr, const rule_t *rule,
2751            char *emsg, const size_t emsglen, udptarget_t *client);
2752 /*
2753  * Fills in "client" with the necessary info for a new udp client, as well
2754  * as creating a socket for the client to send packets to the destination
2755  * "toaddr".
2756  *
2757  * "control", if not -1, specifies the socket used for the control connection.
2758  *
2759  * "client_laddr" gives the local address the UDP pakcet was received on.
2760  *
2761  * "client_raddr" gives the remote address the UDP packet was received from.
2762  *
2763  * "toaddr" gives the resolved destination address.
2764  *
2765  * "tohost" gives the original address requested by the client, which may
2766  * be a hostname.
2767  *
2768  * "rule" is the rule that permits the client.
2769  *
2770  * Returns "client" on success.
2771  * Returns NULL on failure.  On failure, "emsg" of "emsglen" will contain the
2772  * reason the call failed.
2773  */
2774 
2775 udptarget_t *
2776 addclient(const struct sockaddr_storage *clientladdr,
2777           const udptarget_t *client,
2778           size_t *clientc, size_t *maxclientc, udptarget_t **clientv,
2779           const connectionstate_t *state, const rule_t *rule);
2780 /*
2781  * Adds the udpclient "client" to the "clientv" array, which is large
2782  * enough to contain "maxclientc" clients.
2783  * "clientc" gives the index of the last slot in "clientv" that is
2784  * currently in use.
2785  * "clientladdr" is our local endpoint for packets from the client, and
2786  * "rule" is the rule that matched the client, and "state" is the state.
2787  *
2788  * Returns a pointer to the added client ("client"), or NULL if there
2789  * is no more room and clientv can not be expanded.
2790  */
2791 
2792 
2793 #endif /* HAVE_UDP_SUPPORT */
2794 
2795 int
2796 freedescriptors(const char *message, int *highestfdinuse);
2797 /*
2798  * Returns the number of currently unallocated descriptors, and also
2799  * writes the index of the highest fd in use to "highestfdinuse", if
2800  * not NULL.
2801  *
2802  * If "message" is not NULL, also logs the current status.
2803  */
2804 
2805 
2806 int
2807 sockd_unconnect(const int s, const struct sockaddr_storage *oldpeer);
2808 /*
2809  * "unconnects" a socket.  Must only be used with udp sockets.
2810  *
2811  * If "oldpeer" is not NULL it indicates the peer we are currently
2812  * unconnecting from.
2813  *
2814  * Returns:
2815  *      On success: 0
2816  *      On failure: -1 (something wrong with the socket).
2817  */
2818 
2819 void
2820 sockd_rstonclose(const int s);
2821 /*
2822  * Tries to set the necessary socket options so that when socket "s" is
2823  * closed, a TCP RST packet will also be sent automatically.
2824  * Used where we want to indicate to one end of the session that we received
2825  * a RST from the other end.
2826  */
2827 
2828 int
2829 bindinternal(const int protocol);
2830 /*
2831  * Binds all internal addresses using protocol "protocol".
2832  * Returns 0 on success, -1 on failure.
2833  */
2834 
2835 
2836 int
2837 pidismother(pid_t pid);
2838 /*
2839  * If "pid" refers to a mother, the number of "pid" in
2840  * state.motherpidv is returned.  Numbers are counted from 1.
2841  * If "pid" is not a motherprocess, 0 is returned.
2842  */
2843 
2844 int
2845 pidismainmother(pid_t pid);
2846 /*
2847  * If "pid" refers to main mother process, returns true.  Otherwise false.
2848  */
2849 
2850 
2851 int
2852 sockd_motherexists(void);
2853 /*
2854  * Simply check for whether mother still exists or not.
2855  * Not 100%, but is only used to limit noise related to shmem files
2856  * mother removes upon exit, making child processes unable to open
2857  * them.
2858  * Returns true if mother exists, false otherwise.
2859  */
2860 
2861 int
2862 descriptorisreserved(int d);
2863 /*
2864  * If "d" is a descriptor reserved for use globally, the function
2865  * returns true.
2866  * Otherwise, false.
2867  */
2868 
2869 size_t
2870 childcheck(int type);
2871 /*
2872  * Calculates the number of free slots every child of type "type" has,
2873  * combined, and returns that number.
2874  *
2875  * If the childtype "type" is not a child related to free slots, the function
2876  * instead returns the number of child processes of type "type" that exists.
2877  *
2878  * If "type" is negated, the function instead returns the total number of
2879  * slots (free or not) in every child of that type.
2880  * This function also adjusts the number of children of type "type" if needed,
2881  * according to configured variables.
2882  */
2883 
2884 int
2885 childtype(const pid_t pid);
2886 /*
2887  * Returns the type of child the child with pid "pid" is.
2888  */
2889 
2890 void
2891 removechild(const pid_t childpid);
2892 /*
2893  * Removes the child "child" with pid "childpid" from our list of children.
2894  * If "childpid" is 0, removes all children.
2895  */
2896 
2897 void
2898 closechild(const pid_t childpid, const int isnormalexit);
2899 /*
2900  * Closes our pipes to child "childpid" and marks it as unable to receive
2901  * further clients, but does not remove it from our list of children.
2902  *
2903  * If "isnormalexit" is set, we are closing the pipes to this child and
2904  * expect it to exit normally.  This notifies the child about the close,
2905  * telling it to exit normally when done serving it's clients, unlike what
2906  * happens if the child exiting by itself without us telling it to do so,
2907  * or closing it's pipes to us first.
2908  *
2909  * If "childpid" is 0, closes all children.
2910  */
2911 
2912 void
2913 setcommandprotocol(const objecttype_t type, command_t  *commands,
2914                    protocol_t *protocols);
2915 /*
2916  * Sets "commands" and "protocols" in an object of type "type".
2917  * I.e., if "protocols" specifies the udp protocol, sets udp-based
2918  * commands in "commands", and vice versa.
2919  */
2920 
2921 rule_t *
2922 addclientrule(const rule_t *rule);
2923 /*
2924  * Appends a copy of "rule" to our list of client rules, and returns
2925  * a pointer to the added rule.
2926  */
2927 
2928 #if HAVE_SOCKS_HOSTID
2929 int
2930 hostidmatches(const size_t hostidc, const struct in_addr *hostidv,
2931               const unsigned char hostindex, const ruleaddr_t *addr,
2932               const objecttype_t type, const size_t number);
2933 /*
2934  * Returns true if "addr" matches the corresponding hostid in hostidv.
2935  * "number" is the number of the object we are using (included for debug
2936  * logging and error messages).
2937  */
2938 
2939 rule_t *
2940 addhostidrule(const rule_t *rule);
2941 /*
2942  * Appends a copy of "rule" to our list of hostid rules, and returns a
2943  * pointer to the added rule.
2944  */
2945 #endif /* HAVE_SOCKS_HOSTID */
2946 
2947 
2948 rule_t *
2949 addsocksrule(const rule_t *rule);
2950 /*
2951  * Appends a copy of "rule" to our list of socks rules and returns a pointer
2952  * to the added rule.
2953  */
2954 
2955 void
2956 freerulelist(rule_t *rulehead);
2957 /*
2958  * Frees all rules and their contents, starting at "rulehead", then
2959  * continuing with "rulehead->next", etc.
2960  */
2961 
2962 void
2963 addinternal(const ruleaddr_t *addr, const int protocol);
2964 /*
2965  * Adds "addr" to the list of external addresses.
2966  * "protocol" gives the protocol to add, SOCKS_TCP or SOCKS_UDP.
2967  */
2968 
2969 void
2970 addexternal(const ruleaddr_t *addr);
2971 /*
2972  * Adds "addr" to the list of internal addresses (to listen on).
2973  */
2974 
2975 #if 0
2976 void
2977 external_set_safamily(unsigned char *hasipv4, unsigned char *hasipv6,
2978                       unsigned char *hasipv6_global_scope);
2979 /*
2980  * Checks if the list of external addresses we are configured to
2981  * use contain the specified address-families and sets "hasipv4"
2982  * and "hasipv6" as appropriate.
2983  *
2984  * Should be called when there are address-related changes on any of the
2985  * external interfaces configured for use by Dante, but currently there
2986  * is no code for that, so we currently depend on receiving a SIGHUP
2987  * when that happens, and then set the global hasipv4 and hasipv6
2988  * variables as part of the normal config-parsing (and not via this
2989  * special function).
2990  *
2991  * If "hasipv4" is not NULL, it is set to true if we have at least one IPv4
2992  * address configured on the list of external addresses.
2993  *
2994  * If "hasipv6" is not NULL, it is set to true if we have at least one IPv6
2995  * address configured on the list of external addresses.
2996  *
2997  * If "hasipv6_global_scope" is not NULL, it is set to true if we have at
2998  * least one IPv6 address with global scope configured on the list of external
2999  * addresses.
3000  */
3001 #endif
3002 
3003 struct in_addr *
3004 ipv4_mapped_to_regular(const struct in6_addr *ipv4_mapped,
3005                        struct in_addr  *ipv4_regular);
3006 /*
3007  * Converts the IPv4-mapped IPv6 address "ipv4_mapped" to a regular
3008  * IPv4 address, and stores it in "ipv4_regular".
3009  *
3010  * Returns: ipv4_regular.
3011  */
3012 
3013 void
3014 add_internal_safamily(const sa_family_t safamily);
3015 /*
3016  * Marks in global state that we have an address belonging to safamily
3017  * "safamily" on the internal side.
3018  */
3019 
3020 int
3021 internal_has_safamily(const sa_family_t safamily);
3022 /*
3023  * Checks if the list of internal addresses we are configured to
3024  * use contain at list one address of the "safamily" family.
3025  *
3026  * Returns true if there such an address, or false otherwise.
3027  */
3028 
3029 void
3030 add_external_safamily(const sa_family_t safamily, const int globalscope);
3031 /*
3032  * Marks in global state that we have an address belonging to safamily
3033  * "safamily" on the external side.
3034  *
3035  * If "globalscope" is true, the address is of global scope.
3036  */
3037 
3038 
3039 int
3040 external_has_safamily(const sa_family_t safamily);
3041 /*
3042  * Checks if the list of external addresses we are configured to
3043  * use contain at list one address of the "safamily" family.
3044  *
3045  * Returns true if there such an address, or false otherwise.
3046  */
3047 
3048 int
3049 external_has_only_safamily(const sa_family_t safamily);
3050 /*
3051  * Checks if the list of external addresses we are configured to
3052  * use contain addresses of the "safamily" family.
3053  *
3054  * Returns true if there at least one such an address, and only such an
3055  * address, or false otherwise.
3056  */
3057 
3058 int
3059 external_has_global_safamily(const sa_family_t safamily);
3060 /*
3061  * Checks if the list of external addresses we are configured to
3062  * use contain at list one address of the "safamily" family, *and*
3063  * that address has global scope.
3064  *
3065  * Returns true if there such an address, or false otherwise.
3066  */
3067 
3068 
3069 int
3070 addrisbindable(const ruleaddr_t *addr);
3071 /*
3072  * Checks whether "addr" is bindable.
3073  * Returns:
3074  *      On success: true.
3075  *      On failure: false.
3076  */
3077 
3078 int
3079 isreplycommandonly(const command_t *command);
3080 /*
3081  * Returns true if "command" specifies reply-commands only (bind/udp-replies),
3082  * Returns false otherwise.
3083  */
3084 
3085 int
3086 hasreplycommands(const command_t *command);
3087 /*
3088  * Returns true if "command" specifies any reply-commands.
3089  * Returns false otherwise.
3090  */
3091 
3092 
3093 
3094 linkedname_t *
3095 addlinkedname(linkedname_t **linkedname, const char *name);
3096 /*
3097  * Adds a link with the name "name" to the list hanging of "linkedname".
3098  * Returns:
3099  *      On success: a pointer to linkedname.
3100  *      On failure: NULL.
3101  */
3102 
3103 void
3104 freelinkedname(linkedname_t *link);
3105 /*
3106  * free(3)s all entries in the link starting at "link".
3107  */
3108 
3109 void
3110 showrule(const rule_t *rule, const objecttype_t ruletype);
3111 /*
3112  * Prints the rule "rule" to logfile.  "ruletype" says what kind of rule
3113  * "rule" refers to.
3114  */
3115 
3116 void
3117 rule_detachfromlist(rule_t *head);
3118 /*
3119  * sockd_shmdt() from rule-list starting at "head".
3120  */
3121 
3122 void
3123 showmonitor(const monitor_t *monitor);
3124 /*
3125  * Prints the monitor "monitor" to logfile.
3126  */
3127 
3128 void
3129 showlist(const linkedname_t *list, const char *prefix);
3130 /*
3131  * shows user names in "list".
3132  */
3133 
3134 void
3135 showlogspecial(const logspecial_t *log, const interfaceside_t isinternalside);
3136 /*
3137  * Displays the logsettings in "log".  "isinternalside" should be true if
3138  * "log" is from the internal side, and false if from the external side.
3139  */
3140 
3141 
3142 const char *
3143 authname(const authmethod_t *auth);
3144 /*
3145  * Returns a pointer to the name contained in "auth", or NULL if none.
3146  */
3147 
3148 const char *
3149 authinfo(const authmethod_t *auth, char *info, size_t infolen)
3150       __ATTRIBUTE__((__BOUNDED__(__string__, 2, 3)));
3151 /*
3152  * Fills in "info" with a printable representation of the "auth".
3153  * Returns a pointer to "info".
3154  */
3155 
3156 #if HAVE_PAC
3157 const char *
3158 authsids(const authmethod_t *auth);
3159 /*
3160  * Returns a pointer to the sids contained in "auth", or NULL if none.
3161  */
3162 #endif /* HAVE_PAC */
3163 
3164 int
3165 rule_inheritoruse(struct rule_t *from, const clientinfo_t *cinfo_from,
3166                   struct rule_t *to, const clientinfo_t *cinfo,
3167                   const size_t sidesconnected,
3168                   char *emsg, const size_t emsglen);
3169 /*
3170  * Checks whether rule "to" should inherit from the lower-level rule "from"
3171  * and uses unuses shmem and redirect settings in "from" and "to" as
3172  * appropriate.
3173  * "cinfo_from" is the clientinfo that was used when allocating resources
3174  * (if any) for rule "from", and "cinfo_to" is the clientinfo to use when
3175  * allocating resources (if any) for rule "to".
3176  *
3177  * "sidesconnected" gives the TCP session-sides currently connected
3178  * (ALARM_INTERNAL, ALARM_EXTERNAL.  Note that for udp there is only
3179  * one side possible, the internal).
3180  *
3181  * If limits (e.g., session-limits) prevents using one or more objects,
3182  * to->verdict will be set to VERDICT_BLOCK and the emsg will contain the
3183  * appropriate errormessage.  The function will then return -1.
3184  *
3185  * Returns 0 if there were no limits that prevented us from using the
3186  *           necessary objects.
3187  * Returns -1 otherwise, with the reason written to "emsg".
3188  */
3189 
3190 int
3191 rulespermit(int s, const struct sockaddr_storage *peer,
3192             const struct sockaddr_storage *local,
3193             const authmethod_t *clientauth, authmethod_t *srcauth,
3194             rule_t *rule, connectionstate_t *state,
3195             const sockshost_t *src, const sockshost_t *dst,
3196             sockshost_t *dstmatched,
3197             char *msg, size_t msgsize)
3198             __ATTRIBUTE__((__BOUNDED__(__buffer__, 11, 12)));
3199 /*
3200  * Checks whether the rules permit data from "src" to "dst".
3201  *
3202  * #if !BAREFOOTD
3203  *
3204  * "s" is the socket the control connection from the SOCKS client is on,
3205  * from SOCKS client "peer", accepted on our internal address "local".
3206  *
3207  * #else: BAREFOOTD
3208  *
3209  * "s" is the socket the client was accepted on, or on which udp packets from
3210  * it was received.  "peer" gives the client address, and "local" gives our
3211  * own internal address on which the connection/packets were accepted on.
3212  *
3213  * #endif: BAREFOOTD
3214  *
3215  *
3216  * "clientauth" is the authentication established for the client-rule, or
3217  * NULL if no authentication has yet been established for the client rule.
3218  * "srcauth" is the current authentication established for communicating with
3219  * "src".  It may be AUTHMETHOD_NONE or AUTHMETHOD_NOTSET and may be updated
3220  * by this function if an authentication-method is successfully established.
3221  * "state" is the state of the connection.
3222  * "msg" is filled in with any message/information provided when checking
3223  * access, "msgsize" is the size of "msg".
3224  *
3225  * Wildcard fields are supported for the following fields;
3226  *      ipv4:         INADDR_ANY
3227  *      port:         none [enum]
3228  *
3229  * "rule" is filled in with the contents of the matching rule.
3230  *
3231  * Returns:
3232  *      True if request should be allowed.  If so, "dstresolved", if not NULL,
3233  *      will contain the address the request was allowed for, which may be
3234  *      different from "dst" if "dst" had to be resolved or reverse-mapped
3235  *      in order to decide on the verdict.
3236  *
3237  *      Returns false otherwise.
3238  */
3239 
3240 int
3241 command_matches(const int command, const command_t *commands);
3242 /*
3243  * Returns true if "command" is set in "commands".
3244  * False otherwise.
3245  */
3246 
3247 int
3248 protocol_matches(const int protocol, const protocol_t *protocols);
3249 /*
3250  * Returns true if "protocol" is set in "protocols".
3251  * False otherwise.
3252  */
3253 
3254 int
3255 proxyprotocol_matches(const int protocol, const proxyprotocol_t *protocols);
3256 /*
3257  * Returns true if "protocol" is set in "protocols".
3258  * False otherwise.
3259  */
3260 
3261 
3262 int
3263 sockd_connect(int s, const sockshost_t *dst);
3264 /*
3265  * Tries to connect socket "s" to the host given in "dst".
3266  * Returns:
3267  *      On success: 0
3268  *      On failure: -1
3269  */
3270 
3271 int
3272 shmem2config(const struct config *old, struct config *new);
3273 /*
3274  * Copies a config from "old", a config in shmem, to "new", a config
3275  * in regular memory.  The copy includes allocating memory for attributes
3276  * as necessary (i.e., it's a "deep copy").
3277  *
3278  * Note that memory that is only set once at startup and never changed
3279  * is not copied from "old".  Instead it is copied from the processes
3280  * current config object.
3281  *
3282  * Returns 0 on success, -1 on failure.
3283  */
3284 
3285 void
3286 pointer_free(struct config *config);
3287 /*
3288  * Frees all pointers in "config".
3289  */
3290 
3291 size_t
3292 pointer_size(struct config *config);
3293 /*
3294  * Calculates the size of all the memory pointed to by all pointers (and
3295  * pointers to pointers, etc.) in the config "config".
3296  *
3297  * If an object is of an opaque type, and the size of the memory it
3298  * points to can not be determined, it is not counted.
3299  *
3300  * Returns the size of the memory pointed to by all pointers in config.
3301  */
3302 
3303 int
3304 pointer_copy(struct config *src, const ptrdiff_t srcptroffset,
3305              struct config *dst, void *mem, const size_t memsize);
3306 /*
3307  * Does a deep copy of the pointers in the config "src" to the config "dst".
3308  * If "srcptroffset" is not 0x0, it indicates that all the pointers in
3309  * "src" needs to be offset by this number of bytes to get the correct
3310  * address (i.e., the memory for the pointers were allocated in a different
3311  * process at a different address, based on one big block of memory).
3312  *
3313  * NOTE: The function call will update the pointers in "src" before copying,
3314  * and upon return, the pointers will point to the correct address.
3315  *
3316  * If "memsize" is not 0, it gives the size of "mem", which must point to a
3317  * memory area big enough to hold the contents of everything the pointers in
3318  * "src" point to
3319  *
3320  * Otherwise, if "memsize" is 0, the memory to hold the area each pointer
3321  * points to is allocated by this function via malloc(3) and must be
3322  * free(3)-ed in the usual way.
3323  *
3324  * Returns 0 on success, -1 on failure.
3325  */
3326 
3327 size_t
3328 compareconfigs(const struct config *a, const struct config *b);
3329 /*
3330  * Checks if config "a" and the contents of all it points to
3331  * equals that of config "b" and all it points to.
3332  *
3333  * Returns 0 if the configs are not equal.
3334  * Otherwise the configs are equal and the return value indicates the number
3335  * of bytes compared.
3336  */
3337 
3338 
3339 
3340 int
3341 send_req(int s, sockd_request_t *req);
3342 /*
3343  * Sends "req" to "s".
3344  * Returns:
3345  *      On success: 0
3346  *      On failure: -1
3347  */
3348 
3349 int
3350 send_client(int s, const sockd_client_t *client,
3351             const char *req, const size_t reqlen);
3352 /*
3353  * Sends the client "client" to the process connected to "s".
3354  * If "reqlen" is not 0, it is data that has already been read from the
3355  * client, but not forwarded.  This Can only happen in the case of COVENANT.
3356  *
3357  * Returns:
3358  *      On success: 0
3359  *      On failure: -1
3360  */
3361 
3362 /*
3363  * Returns a value indicating whether relaying from "src" to "dst" should
3364  * be permitted.
3365  */
3366 
3367 int
3368 selectmethod(const int *methodv, const size_t methodc,
3369       const unsigned char *offeredv, const size_t offeredc);
3370 /*
3371  * Selects the best method based on available methods and given
3372  * priority.
3373  * "methodv" is a list over available methods, methodc in length.
3374  * "offerdv" is a list over offered methods, offeredc in length.
3375  * The function returns the value of the method that should be selected,
3376  * AUTMETHOD_NOACCEPT if none is acceptable.
3377  */
3378 
3379 negotiate_result_t
3380 method_uname(int s, request_t *request, negotiate_state_t *state);
3381 /*
3382  * Enters username/password sub negotiation.  If successful,
3383  * "request->auth.mdata.uname" is filled in with values read from client.
3384  * If unsuccessful, the contents of "uname" is indeterminate.
3385  * After negotiation has finished and the response to client has been sent
3386  * the function returns.
3387  * Returns:
3388  *      On success: 0 (user/password accepted)
3389  *      On failure: -1  (user/password not accepted, communication failure,
3390  *                       or something else.)
3391  */
3392 
3393 #if HAVE_GSSAPI
3394 negotiate_result_t
3395 method_gssapi(int s, request_t *request, negotiate_state_t *state);
3396 /*
3397  * Enters gssapi sub negotiation.  If successful, "request->auth.mdata.gssapi"
3398  * is filled in with values read from client.
3399  * If unsuccessful, the contents of "gssapi" is indeterminate.
3400  *
3401  * After negotiation has finished and the response to client has been sent
3402  * the function returns.
3403  *
3404  * Returns:
3405  *      On success: 0 (authentication and encryption token accepted)
3406  *      On failure: -1  (authentication or encryption token not accepted,
3407  *                       communication failure, or something else.)
3408  */
3409 #endif /* HAVE_GSSAPI */
3410 
3411 /*
3412  * Functions for more consistent log messages.
3413  * XXX move to separate header file.
3414  */
3415 
3416 void
3417 sockd_freelogobject(logtype_t *logobject, const int closetoo);
3418 /*
3419  * Frees memory associated with the logobject "logobject".
3420  * If "closetoo" is set, closes the files associated too.
3421  */
3422 
3423 int
3424 sockd_reopenlogfiles(logtype_t *log, const int docloseold);
3425 /*
3426  * Reopens all logfiles in "log".  If "docloseold" is true, closes
3427  * old logfiles first.
3428  */
3429 
3430 
3431 int loglevel_errno(const int e,  const interfaceside_t side);
3432 int loglevel_gaierr(const int e, const interfaceside_t side);
3433 /*
3434  * Returns the LOG_* level the error "e" has been configured to be
3435  * logged at, or LOG_DEBUG if no particular loglevel has been configured
3436  * for this error.
3437  *
3438  * "side" is the interface-side (internal/external) the error occurred on.
3439  *
3440  * Returns the appropriate loglevel, or -1 if no loglevel configured.
3441  */
3442 
3443 const int *
3444 errnovalue(const char *symbol);
3445 /*
3446  * Returns a zero-terminated list of errnovalues corresponding to the
3447  * symbolic errno-name "symbol".
3448  *
3449  * "symbol" can also be a Dante-specific alias that will expand to
3450  * multiple error-values, which is the reason for returning a list.
3451  *
3452  * Returns NULL if "symbol" is unknown.
3453  */
3454 
3455 
3456 const int *
3457 gaivalue(const char *symbol);
3458 /*
3459  * Returns a zero-terminated list of libresolv errorvalues (like those
3460  * returned by getaddrinfo(3) and family) corresponding to the
3461  * symbolic error-name "symbol".
3462  *
3463  * "symbol" can also be a Dante-specific alias that will expand to
3464  * multiple error-values, which is the reason for returning a list.
3465  *
3466  * Returns NULL if "symbol" is unknown.
3467  */
3468 
3469 
3470 iologaddr_t *
3471 init_iologaddr(iologaddr_t *addr,
3472                const objecttype_t local_type, const void *local,
3473                const objecttype_t peer_type, const void *peer,
3474                const authmethod_t *auth,
3475                const struct in_addr *hostidv, const unsigned int hostidc);
3476 /*
3477  * Inits "addr" based on the passed arguments.  If "local" or "peer" is not
3478  * NULL, "local_type" or "peer_type" indicates what kind of object "local"
3479  * or "peer" is.
3480  *
3481  * Returns a pointer to "addr".
3482  */
3483 
3484 
3485 void
3486 iolog(const rule_t *rule, const connectionstate_t *state, const operation_t op,
3487       const iologaddr_t *src, const iologaddr_t *dst,
3488       const iologaddr_t *tosrc_proxy, const iologaddr_t *todst_proxy,
3489       const char *data, size_t datalen);
3490 
3491 /*
3492  * Called after each each complete io operation
3493  * (read then write, or read then block).
3494  * Does misc. logging based on the log options set in "log".
3495  * - "rule" is the rule that matched the iooperation, not "const" due to
3496  *    possible libwrap interaction.
3497  * - "state" is the state of the connection.
3498  * - "op" is the operation that was performed.
3499  * - "src" is where data was received from.
3500  * - "dst" is where data was written to.
3501  * - "tosrc_proxy", if not NULL, is the proxy used in the serverchain to
3502  *    reach "src.host".
3503  * - "todst_proxy", if not NULL, is the proxy used in the serverchain to
3504  *    reach "dst.host".
3505  * - "data" and "datalen" are interpreted depending on "operation".
3506  */
3507 
3508 char *
3509 build_addrstr_src(const struct in_addr *hostidv, const unsigned int hostidc,
3510                   const sockshost_t *peer, const sockshost_t *proxy_ext,
3511                   const sockshost_t *proxy, const sockshost_t *local,
3512                   const authmethod_t *peerauth, const authmethod_t *proxyauth,
3513                   char *str, size_t strsize);
3514 
3515 char *
3516 build_addrstr_dst(const sockshost_t *local, const sockshost_t *proxy,
3517                   const sockshost_t *proxy_ext, const sockshost_t *peer,
3518                   const authmethod_t *peerauth, const authmethod_t *proxyauth,
3519                   const struct in_addr *hostidv, const unsigned int hostidc,
3520                   char *str, size_t strsize);
3521 
3522 void
3523 io_delete(int mother, sockd_io_t *io, int fd, const iostatus_t status);
3524 /*
3525  * deletes the io object "io".  "fd" is the descriptor on which "status"
3526  * was returned.  If "fd" is negative, it is ignored.
3527  * If "mother" is >= 0, the deletion of "io" is ACK'ed to her.
3528  * "status" is the reason for why the io was deleted.
3529  */
3530 
3531 
3532 void
3533 close_iodescriptors(const sockd_io_t *io);
3534 /*
3535  * A subset of io_delete().  Will just close all descriptors in
3536  * "io".
3537  */
3538 
3539 int
3540 sockdnegotiate(int s);
3541 /*
3542  * Sends the connection "s" to a negotiator child.
3543  * Returns:
3544  *      On success: 0
3545  *      On failure: -1
3546  */
3547 
3548 void
3549 run_monitor(void);
3550 /*
3551  * Sets a io child running.
3552  */
3553 
3554 void
3555 run_io(void);
3556 /*
3557  * Sets a io child running.
3558  *
3559  * A child starts running with zero clients and waits
3560  * indefinitely for mother to send at least one.
3561  */
3562 
3563 void
3564 run_negotiate(void);
3565 /*
3566  * Sets a negotiator child running.
3567  * A child starts running with zero clients and waits
3568  * indefinitely for mother to send at least one.
3569  */
3570 
3571 void
3572 run_request(void);
3573 /*
3574  * Sets a request child running.
3575  * A child starts running with zero clients and waits
3576  * indefinitely for mother to send at least one.
3577  */
3578 
3579 void mother_preconfigload(void);
3580 void monitor_preconfigload(void);
3581 void negotiate_preconfigload(void);
3582 void request_preconfigload(void);
3583 void io_preconfigload(void);
3584 
3585 void mother_postconfigload(void);
3586 void monitor_postconfigload(void);
3587 void negotiate_postconfigload(void);
3588 void request_postconfigload(void);
3589 void io_postconfigload(void);
3590 /*
3591  * Process-specific post/pre-processing after loading config.
3592  */
3593 
3594 void detach_from_shmem(void);
3595 /*
3596  * Detaches from shmem not all processes need to be attached to.
3597  * Processes who need it, will attach later as needed.
3598  */
3599 
3600 
3601 void mother_envsetup(int argc, char *argv[]);
3602 /*
3603  * Cleans up surrounding environment before we start forking of processes.
3604  * argc and argv are the argc/argv arguments passed main.
3605  */
3606 
3607 char *
3608 mother_getlimitinfo(void);
3609 /*
3610  * returns a string with some information about current state and limits.
3611  */
3612 
3613 void
3614 log_rusage(const int childtype, const pid_t pid, const struct rusage *rusage);
3615 /*
3616  * Logs the rusage in "rusage" for a child of type "childtype with the
3617  * pid "pid".  If pid is 0, assumes "rusage" is for all children of
3618  * the given childtype.
3619  */
3620 
3621 
3622 
3623 void
3624 checkconfig(void);
3625 /*
3626  * Scans through the config, perhaps fixing some things and warning
3627  * about strange things, or errors out on serious mistakes.
3628  */
3629 
3630 
3631 int
3632 send_io(int s, sockd_io_t *io);
3633 /*
3634  * Sends the io-object "io" to "s".
3635  * Returns
3636  *    On success: 0
3637  *    On failure: -1
3638  */
3639 
3640 
3641 int
3642 recv_io(int mother, sockd_io_t *io);
3643 /*
3644  * Attempts to read a new io object from "mother".
3645  * If a io is received it is either copied into "io", or it's copied
3646  * Returns:
3647  *      On success: 0
3648  *      On failure: -1.  Errno will be set.
3649  */
3650 
3651 int
3652 recv_req(int s, sockd_request_t *req);
3653 /*
3654  * Receives a request from the socket "s" and stores it in "req".
3655  * Returns:
3656  *      On success: 0
3657  *      On failure: -1
3658  */
3659 
3660 negotiate_result_t
3661 recv_clientrequest(int s, request_t *request, negotiate_state_t *state);
3662 /*
3663  * Reads a request from the socket "s", which can be set to non-blocking.
3664  * "request" will be filled in as reading progresses but it should
3665  * be considered of indeterminate contents until the whole request
3666  * has been read.
3667  * Returns the result (continue, finished, error).
3668  */
3669 
3670 negotiate_result_t
3671 recv_sockspacket(int s, request_t *request, negotiate_state_t *state);
3672 /*
3673  * When method negotiation has finished (if appropriate) this function
3674  * is called to receive the actual packet.
3675  */
3676 
3677 void
3678 disable_childcreate(int err, const char *reason);
3679 /*
3680  * Disables creation of children.  "err" is the errno reason to do so, if
3681  * any, while "reason" is an additional textual description.
3682  */
3683 
3684 void
3685 enable_childcreate(void);
3686 /*
3687  * Enables creation of children again.
3688  */
3689 
3690 
3691 sockd_child_t *
3692 getchild(pid_t pid);
3693 /*
3694  * Attempts to find a child with pid "pid".
3695  * Returns:
3696  *      On success: a pointer to the found child.
3697  *      On failure: NULL.
3698  */
3699 
3700 void
3701 sigchildbroadcast(int sig);
3702 /*
3703  * Sends signal "sig" to all children of type "childtype".
3704  */
3705 
3706 int
3707 fillset(fd_set *set, size_t *negc, size_t *reqc, size_t *ioc);
3708 /*
3709  * Sets every child's descriptor in "set", as well as sockets we listen on.
3710  * "negc", "reqc", and "ioc" is upon return filled in with the number of
3711  * currently free negotiate slots, request slots, and io slots, respectively.
3712  *
3713  * Returns the number of the highest descriptor set, or -1 if none was set.
3714  */
3715 
3716 void
3717 clearset(whichpipe_t type, const sockd_child_t *child, fd_set *set);
3718 /*
3719  * Clears every descriptor of type "type" in "child" from "set".
3720  * "type" gives the type of pipe that must be set.
3721  */
3722 
3723 void
3724 clearchildtype(const int childtype, whichpipe_t pipetype,
3725                const int nfds, fd_set *set);
3726 /*
3727  * Like clearset(), but for all children of the type "childtype".
3728  */
3729 
3730 sockd_child_t *
3731 getset(whichpipe_t type, fd_set *set);
3732 /*
3733  * If there is a child with a descriptor set in "set", a pointer to
3734  * the child is returned.
3735  * "type" gives the type of pipe that must be set.
3736  * The children returned are returned in prioritized order.
3737  * If no child is found, NULL is returned.
3738  */
3739 
3740 sockd_child_t *
3741 nextchild(const int type, const int protocol);
3742 /*
3743  * Returns:
3744  *      On success: pointer to a child of correct type with at least one free
3745  *      slot of protocol type "protocol".
3746  *      On failure: NULL.
3747  */
3748 
3749 #if HAVE_SCHED_SETAFFINITY
3750 /*
3751  * Modelled after the CPU_SET() macros.
3752  */
3753 
3754 size_t
3755 cpu_get_setsize(void);
3756 
3757 void
3758 cpu_set(const int cpu, cpu_set_t *set);
3759 
3760 void
3761 cpu_zero(cpu_set_t *set);
3762 
3763 int
3764 cpu_isset(const int cpu, const cpu_set_t *set);
3765 
3766 int
3767 cpu_equal(const cpu_set_t *set1, const cpu_set_t *set2);
3768 
3769 int
3770 cpu_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask);
3771 
3772 int
3773 cpu_setaffinity(pid_t pid, size_t cpusetsize, const cpu_set_t *mask);
3774 
3775 int
3776 sockd_cpuset_isok(const cpu_set_t *set);
3777 /*
3778  * Returns false if one or more of the cpus set in "set" is not valid
3779  * on the current system.  True otherwise.
3780  */
3781 #endif /* HAVE_SCHED_SETAFFINITY */
3782 
3783 #if HAVE_SCHED_SETSCHEDULER
3784 
3785 int
3786 cpupolicy2numeric(char *name);
3787 /*
3788  * return cpupolicy id value for given policy name, or -1 if not found.
3789  */
3790 
3791 char *
3792 numeric2cpupolicy(int value);
3793 /*
3794  * return pointer to name for given policy id value, or NULL if not found.
3795  */
3796 
3797 #endif /* HAVE_SCHED_SETSCHEDULER */
3798 
3799 int
3800 sockd_setcpusettings(const cpusetting_t *old, const cpusetting_t *new);
3801 /*
3802  * Applies the cpusettings in "new" to the current process.
3803  * "old", if not NULL, contains the current settings, and is used to avoid
3804  * reapplying existing settings.
3805  *
3806  * Returns 0 on success, -1 on failure.
3807  */
3808 
3809 void
3810 setsockoptions(const int s, const sa_family_t family, const int type,
3811                const int isclientside);
3812 /*
3813  * Sets options _all_ server sockets should have set on the socket "s".
3814  *
3815  * "family" gives the socket family (AF_INET or AF_INET6),
3816  * "type" gives the socket type (SOCK_STREAM or SOCK_DGRAM),
3817  * "isclientside" says if the socket is to be used to receive data
3818  * from the client.
3819  */
3820 
3821 void
3822 sockdexit(const int exitcode)
3823    __ATTRIBUTE__((noreturn));
3824 /*
3825  * Exits with the value of "exitcode".
3826  */
3827 
3828 
3829 /*
3830  * DNS-functions.
3831  * Same API as libresolv, but uses internal cache if possible.
3832  */
3833 
3834 struct hostent *
3835 cgethostbyname(const char *name);
3836 
3837 struct hostent *
3838 cgethostbyaddr(const void *addr, socklen_t len, int type);
3839 
3840 int
3841 cgetnameinfo(const struct sockaddr *addr, const socklen_t addrlen,
3842              char *host, const socklen_t hostlen, char *service,
3843              const socklen_t servicelen, const int flags);
3844 
3845 int
3846 cgetaddrinfo(const char *name, const char *service,
3847              const struct addrinfo *hints, struct addrinfo **res,
3848              dnsinfo_t *resmem);
3849 /*
3850  * Like getaddrinfo(3), but "resmem" is used to hold the contents of "res",
3851  * rather than allocating the memory for "res" dynamically and then
3852  * having to call freeaddrinfo(3).
3853  */
3854 
3855 
3856 #if !HAVE_PRIVILEGES
3857 int
3858 sockd_seteugid(const uid_t uid, const gid_t gid);
3859 /*
3860  * Sets the effective user/group-id to "uid" and "gid", and updates
3861  * sockscf.state.{euid,egid} if successful.
3862  *
3863  * Returns 0 on success, -1 on failure.
3864  */
3865 #endif /* !HAVE_PRIVILEGES */
3866 
3867 int
3868 sockd_initprivs(void);
3869 /*
3870  * Initializes things based on configured userid/privilege settings.
3871  * Returns 0 if inited ok, -1 if not.
3872  */
3873 
3874 void
3875 sockd_priv(const privilege_t privilege, const priv_op_t op);
3876 /*
3877  * Acquires or releases the privilege associated with the privilege
3878  * "privilege".
3879  * "op" indicates whether the privilege should be acquired or relinquished,
3880  * and must have one of the values PRIV_ON or PRIV_OFF, correspondingly.
3881  */
3882 
3883 void
3884 resetprivileges(void);
3885 /*
3886  * Resets privileges to correct state based on config.
3887  * Should be called when starting and after sighup.
3888  */
3889 
3890 
3891 int
3892 usermatch(const authmethod_t *auth, const linkedname_t *userlist);
3893 /*
3894  * Checks whether the username in "auth" matches a name in the
3895  * list "userlist".
3896  * Returns:
3897  *    If match: true.
3898  *      Else: false.
3899  */
3900 
3901 int
3902 groupmatch(const authmethod_t *auth, const linkedname_t *grouplist);
3903 /*
3904  * Checks whether the username in "auth" matches groupname listed in "userlist".
3905  * Returns:
3906  *    If match: true.
3907  *      Else: false.
3908  */
3909 
3910 #if HAVE_LDAP
3911 int
3912 ldapgroupmatch(const authmethod_t *auth, const rule_t *rule);
3913 /*
3914  * Checks whether the username in "auth" matches ldap groupname listed
3915  * in "userlist".
3916  * Returns:
3917  *    If match: true.
3918  *    Else: false.
3919  */
3920 
3921 int
3922 ldapgroupmatches(const authmethod_t *auth,
3923                  const char *username, const char *userdomain,
3924                  const char *group, const char *groupdomain,
3925                  const rule_t *rule);
3926 /*
3927  * Checks if user "username" in Kerberos domain "userdomain" is member of
3928  * ldap group "group" in Kerberos domain "groupdomain".
3929  * Rule "rule" contains further ldap parameters.
3930  */
3931 
3932 int
3933 ldapauth_passwordcheck(int s, const struct sockaddr_storage *src,
3934                        const struct sockaddr_storage *dst,
3935                        authmethod_ldap_t *auth,
3936 		       char *emsg, size_t emsgsize);
3937 /*
3938  * Checks if user password against ldap server
3939  */
3940 
3941 
3942 void
3943 cache_ldap_user(const char *username, int result, size_t rulenumber);
3944 /*
3945  * Add user "username" to cache for rule "rulenumber".
3946  * "retval" gives the result to cache.
3947  * XXX result should be enum, and used in ldap_user_is_cached() also?
3948  */
3949 
3950 int
3951 ldap_user_is_cached(const char *username, size_t rulenumber);
3952 /*
3953  * Checks if user "username" is cached for rule "rulenumber".
3954  * Returns:
3955  *    If not cached: -1
3956  *    Else: 0 or 1
3957  */
3958 
3959 char *
3960 asciitoutf8(char *input);
3961 /*
3962  * Checks if string contains character > 127 and converts them to UTF8
3963  */
3964 
3965 char *
3966 hextoutf8(const char *input, int flag);
3967 /*
3968  * Convert hex input to UTF8 character string
3969  * flag = 2 convert input (all)
3970  * flag = 1 convert input (group name/basedn and realm)
3971  * flag = 0 convert input (only group name/basedn)
3972  * XXX flag should be enum.
3973  */
3974 
3975 #endif /* HAVE_LDAP */
3976 
3977 #if HAVE_PAC
3978 
3979 #define MAX_BASE64_LEN 256
3980 
3981 int
3982 sidmatch(const authmethod_t *auth, const linkedname_t *objectsids);
3983 /*
3984  * Checks whether the username in "auth" matches SID listed
3985  * in "userlist".
3986  * Returns:
3987  * If match: true.
3988  * Else: false.
3989  */
3990 
3991 int
3992 binsidtob64(const char *bsid, char *b64buf, int bsid_len, size_t b64buflen);
3993 /*
3994  * Converts binary format SID to a base64 encoded string.
3995  * Returns:
3996  *  If success:  0
3997  *  If Failure: -1
3998  */
3999 
4000 int
4001 sidtob64(const char *sid, char *b64buf, size_t b64buflen);
4002 /*
4003  * Converts a SID string to a base64 encoded string.
4004  * Returns:
4005  *   If success:  0
4006  *   If failure: -1
4007  */
4008 
4009 int
4010 b64tosid(const char *b64, char *sidbuf, size_t sidbuflen);
4011 /*
4012  * Converts a base64 encoded string to a SID string.
4013  * Returns:
4014  *   If success:  0
4015  *   If failure: -1
4016  */
4017 
4018 #endif /* HAVE_PAC */
4019 
4020 unsigned long
4021 medtv(struct timeval *tvarr, size_t tvsize);
4022 /*
4023  * Return median time in microseconds from sorted timeval array with
4024  * tvsize entries.
4025  */
4026 
4027 unsigned long
4028 avgtv(struct timeval *tvarr, size_t tvsize);
4029 /*
4030  * Return average time in microseconds from sorted timeval array with
4031  * tvsize entries.
4032  */
4033 
4034 unsigned long
4035 stddevtv(struct timeval *tvarr, size_t tvsize, unsigned long avg);
4036 /*
4037  * Return standard deviation in microseconds for sorted timeval array with
4038  * tvsize entries and an average of avg.
4039  */
4040 
4041 int
4042 accesscheck(int s, authmethod_t *auth, const struct sockaddr_storage *src,
4043             const struct sockaddr_storage *dst, char *emsg, size_t emsgsize)
4044             __ATTRIBUTE__((__BOUNDED__(__buffer__, 5, 6)));
4045 /*
4046  * Checks whether access matches according to supplied arguments.
4047  * "auth" is the authentication to be matched against,
4048  * "s" is the socket the client is connected to,
4049  * "src" is address client connected from, "dst" is address client
4050  * connected to.
4051  * "emsg" is a buffer that information can be written into, "emsgsize"
4052  * is the size of that buffer.
4053  *
4054  * Returns:
4055  *      If access is ok: true.
4056  *      Otherwise: false.  Writes the reason into "emsg".
4057  */
4058 
4059 int
4060 passwordcheck(const char *name, const char *cleartextpassword,
4061               char *emsg, size_t emsglen)
4062               __ATTRIBUTE__((__BOUNDED__(__buffer__, 3, 4)));
4063 /*
4064  * First it checks whether "name" is in the password file.  If
4065  * "cleartextpassword" is NULL, as is the case if called as part of
4066  * rfc931/ident authentication, that is all that is done.
4067  *
4068  * If "cleartextpassword" is not NULL, also checks if "name"'s
4069  * password in the system passwordfile is "cleartextpassword".
4070  *
4071  * Returns:
4072  *      If "name" and "cleartextpassword" is matched: 0
4073  *      Otherwise: -1.  "emsg" is filled in with the error message.
4074  */
4075 
4076 int
4077 pam_passwordcheck(int s,
4078       const struct sockaddr_storage *src, const struct sockaddr_storage *dst,
4079       const authmethod_pam_t *auth, char *emsg, size_t emsglen)
4080       __ATTRIBUTE__((__BOUNDED__(__buffer__, 5, 6)));
4081 /*
4082  * Checks whether pam grants access to the client connected to the socket "s".
4083  * "src" is the clients source address, "dst" is address we accepted the
4084  * clients connection on.
4085  *
4086  * Returns:
4087  *      If "name" and "cleartext password" is matched: 0
4088  *      Otherwise: -1.  "emsg" is filled in with the error message.
4089  */
4090 
4091 int
4092 bsdauth_passwordcheck(int s,
4093       const struct sockaddr_storage *src, const struct sockaddr_storage *dst,
4094       authmethod_bsd_t *auth, char *emsg, size_t emsgsize)
4095       __ATTRIBUTE__((__BOUNDED__(__buffer__, 5, 6)));
4096 /*
4097  * Checks whether bsd authentication grants access to the client
4098  * connected to the socket "s".  "src" is the clients source address,
4099  * "dst" is address we accepted the clients connection on.
4100  *
4101  * Returns:
4102  *      If "name" and "cleartext password" is matched: 0
4103  *      Otherwise: -1.  "emsg" is filled in with the error message.
4104  */
4105 
4106 void
4107 redirectsetup(void);
4108 /*
4109  * sets up things for using the redirect module.
4110  * Must be called at start and after sighup by main mother.
4111  */
4112 
4113 int
4114 redirect(int s, struct sockaddr_storage *addr,
4115 #if !BAREFOOTD
4116          sockshost_t *host,
4117 #endif /* !BAREFOOTD */
4118          int command, const ruleaddr_t *from
4119 #if !BAREFOOTD
4120          , const ruleaddr_t *to
4121 #endif /* !BAREFOOTD */
4122          );
4123 /*
4124  * "s" is the socket to use for performing "command", while  "from"
4125  * and "to" are the redirect from/to values specified in the redirect
4126  * statement from the matching rule.
4127  *
4128  * The meaning of "addr" and "host" varies depending on what "command" is.
4129  * When passed to the redirect() function, they contain the values
4130  * that will be used if the redirect() function does not change them.
4131  *
4132  * The redirect() function supports all commands and will change
4133  * "addr" and host as follows for the different commands:
4134  *      SOCKS_BIND:
4135  *         "addr" is local address of "s", to accept remote connection on.
4136  *         "host" is ignored.
4137  *
4138  *      SOCKS_BINDREPLY:
4139  *         "addr" is the address to say bindreply is from.
4140  *         "host" is the address to send reply to (only for bind extension).
4141  *
4142  *      SOCKS_CONNECT:
4143  *         "addr" is local address of socket "s".
4144  *         "host" is host to connect to.
4145  *
4146  *      case SOCKS_UDPASSOCIATE:
4147  *         "addr" is the address to send the udp packet from.
4148  *         "host" is the address to send packet to.
4149  *
4150  *      case SOCKS_UDPREPLY:
4151  *         "addr" is the address to say the reply is from.
4152  *         "host" is the address to send the reply to.
4153  *
4154  * "host", "addr", and the local address of "s" will be changed if needed.
4155  *
4156  * Returns:
4157  *      On success: 0.
4158  *      On failure: -1.
4159  */
4160 
4161 void
4162 hostcachesetup(void);
4163 /*
4164  * Initializes the hostcache.  Must be called before any calls to
4165  * cgethostby*().
4166  */
4167 
4168 void
4169 hostcacheinvalidate(void);
4170 /*
4171  * Invalidates all entries in the hostcache.
4172  */
4173 
4174 void
4175 ldapcachesetup(void);
4176 /*
4177  * Initializes the ldapcache.  Must be called before any calls to
4178  * ldap functions.
4179  */
4180 
4181 void
4182 ldapcacheinvalid(void);
4183 /*
4184  * Clear all ldap cache entries.
4185  */
4186 
4187 char *
4188 sockd_getshmemname(const unsigned long id, const statekey_t key);
4189 /*
4190  * Returns the shmemname corresponding to the id "id" and key "key".
4191  */
4192 
4193 void
4194 sockd_shmdt(rule_t *rule, const int which);
4195 /*
4196  * Detaches shared memory segments in rule "rule" as indicated by which,
4197  * and sets the value of the detached objects to not in use.
4198  */
4199 
4200 int
4201 sockd_shmat(rule_t *rule, int which);
4202 /*
4203  * Attaches shared memory segments in "rule" as indicated by which.
4204  *
4205  * The attachments that fail are set to NULL/-1.  It is therefore important
4206  * to check shmid/object twice if trying to map more than one (when which
4207  * does not indicate a single object); once before calling sockd_shmat(),
4208  * and once after, as the first sockd_shmat() call may have failed on some
4209  * or all the shmem segments and NULL-ed them if so.
4210  *
4211  * Returns 0 on success, -1 if one or more attachments failed.
4212  */
4213 
4214 void
4215 shmem_setup(void);
4216 /*
4217  * sets up things for using shared memory.
4218  */
4219 
4220 void
4221 shmem_idupdate(struct config *config);
4222 /*
4223  * Goes through "sockscf" and allocates shmemids for all objects that need
4224  * it.
4225  */
4226 
4227 
4228 int
4229 shmem_alloc(const size_t len, const key_t key);
4230 /*
4231  * allocate shared memory of size "len" and the shmid of the memory.
4232  * Return -1 on failure.
4233  */
4234 
4235 int
4236 shmem_unuse(shmem_object_t *object, const clientinfo_t *cinfo, int lock);
4237 /*
4238  * Says we are no longer using "object" on behalf of the client in "cinfo".
4239  * "lock" is used for locking.  If it is -1, no locking is enforced.
4240  *
4241  * Returns 0 on success, -1 on failure.
4242  */
4243 
4244 int
4245 shmem_use(shmem_object_t *object, const clientinfo_t *cinfo, const int lock,
4246           const int mapisopen);
4247 /*
4248  * Marks "object" as in use on behalf of the client in "cinfo".
4249  * "lock" is used for locking.  If it is -1, no locking is enforced.
4250  *
4251  * If "mapisopen" is true, any keymap in shmem to be used for keystate
4252  * is already open.  Upon function return, the open/close state of the
4253  * keystate map should remain as it was.
4254  *
4255  * Returns 0 on success, -1 on failure.
4256  */
4257 
4258 int
4259 shmem_userule(rule_t *rule, const clientinfo_t *cinfo, char *emsg,
4260               const size_t emsglen);
4261 /*
4262  * Uses shmem-resources set in rule "rule".
4263  * Returns 0 on success.
4264  * Returns -1 on error.  In this case, "emsg" contains the reason.
4265  */
4266 
4267 void
4268 monitor_use(shmem_object_t *stats, const clientinfo_t *cinfo, const int lock);
4269 /*
4270  * Marks alarms in "stats" as in use on behalf of the client in "cinfo".
4271  * "lock" is used for locking.  If it is -1, no locking is enforced.
4272  */
4273 
4274 void
4275 monitor_unuse(shmem_object_t *stats, const clientinfo_t *cinfo, const int lock);
4276 /*
4277  * Decrements usage count for alarms in "stats" on behalf of the client
4278  * in "cinfo".
4279  * "lock" is used for locking.  If it is -1, no locking is enforced.
4280  */
4281 
4282 void
4283 monitor_sync(shmem_object_t *alarm, const unsigned long shmid,
4284              const size_t alarmsconfigured, const size_t sidesconnected,
4285              const clientinfo_t *cinfo, const int lock);
4286 /*
4287  * Called a sighup invalidates the old monitor and we want to transfer
4288  * the settings to the new monitor referenced by "alarm".
4289  * "alarmsconfigured" gives the alarms configured on the new monitor, and
4290  * "sidesconnected" is the session-sides currently connected (internal,
4291  * external, or both).
4292  */
4293 
4294 void
4295 alarm_inherit(rule_t *from, const clientinfo_t *cinfo_from,
4296               rule_t *to,   const clientinfo_t *cinfo_to,
4297               const size_t sidesconnected);
4298 /*
4299  * Handles alarm inheritance from rule "from" into rule "to".
4300  * "sidesconnected" is the sides connected (internal/external).
4301  * Note that for udp, there is only one side possible, the internal.
4302  */
4303 
4304 
4305 void
4306 alarm_add_connect(rule_t *alarm, const size_t sides,
4307                   const clientinfo_t *cinfo, const int lock);
4308 /*
4309  * Adds a connect to the alarmobject referenced by "rule", on the sides
4310  * indicated by sides.
4311  */
4312 
4313 
4314 void
4315 alarm_add_disconnect(const int weclosedfirst, rule_t *alarm,
4316                      const size_t sides, const clientinfo_t *cinfo,
4317                      const char *reason, const int lock);
4318 /*
4319  * Adds a disconnect to the alarmobject referenced by "rule", on the sides
4320  * indicated by "sides".
4321  *
4322  * If "weclosefirst" is set, the disconnect/close by peer is considered a
4323  * response to a previous close by us.
4324  *
4325  * "reason" is the reason for for the disconnect.
4326  */
4327 
4328 void
4329 alarm_remove_session(rule_t *alarm, const size_t sides,
4330                      const clientinfo_t *cinfo, const int lock);
4331 /*
4332  * Removes a previously added session on the sides "sides" from the
4333  * alarmobject referenced by "rule".
4334  *
4335  * Typically used when a session is to be inherited by another
4336  * monitor, and we want to remove the session from the old monitor
4337  * without affecting other things.
4338  */
4339 
4340 void *
4341 sockd_mmap(void *oldmap, size_t size, const int prot, const int flags,
4342            const int fd, const int docreate);
4343 /*
4344  * Allocates shared memory of size "size", using "fd" for storage
4345  * and mmap()s it.
4346  * If "oldmap" is not NULL, it should be a previously mmap(2)-ed segment that
4347  * should now be re-mmap(2)-ed.
4348  *
4349  * If "docreate" is set, this is a call to create or extend the memory and
4350  * function will make sure to extend the file referenced by fd to at least
4351  * "size" bytes, but will not explicitly initialize the memory.
4352  * If "docreate" is not set, this is a remap of a previously created
4353  * shmem segment and the file referenced by fd will not be touched.
4354  *
4355  * Returns a pointer to the memory allocated, or MAP_FAILED on failure.
4356  */
4357 
4358 ssize_t
4359 keystate_index(shmem_object_t *shmem, const clientinfo_t *cinfo,
4360                const int expireoldtoo);
4361 /*
4362  * Returns the index of "cinfo" in shmem's keystate array,
4363  * or -1 if no such index exists.
4364  * If "expireoldtoo" is set, expired old keystate entries in shmem,
4365  * if any, too.
4366  */
4367 
4368 int
4369 keystate_openmap(const unsigned long id, keystate_t *keystate,
4370                  size_t *sizemapped);
4371 /*
4372  * opens and mmap's the file corresponding to "id" and "keystate".
4373  * If "mappedsize"  is not NULL, it will contain the size of the
4374  * object mapped.
4375 
4376  * Note that the lock corresponding to keystate should be taken
4377  * before calling this function, to make sure the correct size
4378  * is mmap'ed.
4379  *
4380  * Returns 0 on success, -1 on failure.
4381  */
4382 
4383 void
4384 keystate_closemap(const unsigned long id, keystate_t *keystate,
4385                   const size_t mappedsize, const ssize_t changedindex);
4386 /*
4387  * Closes the previously opened keystate map of size "mappedsize".
4388  * Also truncates the file used if the current size is different from
4389  * the size mapped.
4390  *
4391  * If "datawaschanged" is true it means some of the data was changed, and
4392  * a msync(2) may have to be done.
4393  */
4394 
4395 int
4396 keystate_hasexpired(const shmem_object_t *shmem, const size_t keyindex,
4397                     const struct timeval *timenow);
4398 /*
4399  * "timenow" is the current time.
4400  *
4401  * Returns true if the keystate at index "keyindex" in "shmem" has expired
4402  * or can be reset.
4403  * Returns false otherwise.
4404  */
4405 
4406 void
4407 disconnectalarm_use(shmem_object_t *disconnectalarm, const clientinfo_t *cinfo,
4408                     const int lock);
4409 /*
4410  * Marks "disconnectalarm" as in use by client "cinfo".
4411  */
4412 
4413 
4414 void
4415 disconnectalarm_unuse(shmem_object_t *disconnectalarm,
4416                       const clientinfo_t *cinfo, const int lock);
4417 /*
4418  * Marks "disconnectalarm" as no longer in use by client "cinfo".
4419  */
4420 
4421 void
4422 bw_use(shmem_object_t *bw, const clientinfo_t *cinfo, const int lock);
4423 /*
4424  * Marks "bw" as in use by client "cinfo".
4425  */
4426 
4427 void
4428 bw_unuse(shmem_object_t *bw, const clientinfo_t *cinfo, const int lock);
4429 /*
4430  * Says client "cinfo" is no longer using "bw".
4431  * If "bw" is NULL, nothing is done.
4432  */
4433 
4434 ssize_t
4435 bw_left(const shmem_object_t *bw, const int lock);
4436 /*
4437  * Returns how many bytes we should read if the client is restricted
4438  * by "bw".
4439  */
4440 
4441 void
4442 bw_update(shmem_object_t *bw, size_t bwused, const struct timeval *bwusedtime,
4443           const int lock);
4444 /*
4445  * Updates "bw".  "bwused" is the bandwidth used (in bytes) at time
4446  * "bwusedtime".
4447  */
4448 
4449 int
4450 bw_rulehasoverflown(const rule_t *rule, const struct timeval *tnow,
4451                     struct timeval *overflowok);
4452 /*
4453  * Checks if the bandwidth limit for the bw-object in "rule" has overflown.
4454  * If it has overflown, "overflowok" is set to the time when we can again do
4455  * i/o over the io objects using this rule.
4456  *
4457  * Return true if bw has overflown.  In this case, "overflowok" will be set.
4458  * Returns false if bw has not overflown.
4459  */
4460 
4461 
4462 int
4463 session_use(shmem_object_t *ss, const clientinfo_t *cinfo, const int lock,
4464             char *emsg, const size_t emsglen);
4465 /*
4466  * Allocates a session for client "cinfo".
4467  *
4468  * Returns true on success, false otherwise.  If false, the reason is
4469  * printed to "emsg".
4470  */
4471 
4472 void
4473 session_unuse(shmem_object_t *ss, const clientinfo_t *cinfo, const int lock);
4474 /*
4475  * Says "cinfo" is no longer using "ss".
4476  */
4477 
4478 
4479 
4480 void
4481 checkmodule(const char *name);
4482 /*
4483  * Checks that the system has the module "name" and permission to use it.
4484  * Aborts with an error message if not.
4485  */
4486 
4487 char *
4488 licensekey2string(const licensekey_t *key);
4489 /*
4490  * Returns a printable representation of the licensekey "key".
4491  * Exits on error.
4492  */
4493 
4494 
4495 
4496 int sockd_handledsignals(void);
4497 /*
4498  * Check if we have received any signal, and calls the appropriate
4499  * signal handler if so.
4500  *
4501  * Returns 1 if a signal handler was called, 0 otherwise.
4502  */
4503 
4504 
4505 struct sockaddr_storage *
4506 getoutaddr(struct sockaddr_storage *laddr,
4507            const struct sockaddr_storage *client_laddr,
4508            const struct sockaddr_storage *client_raddr,
4509            const int command, const struct sockshost_t *request,
4510            char *emsg, const size_t emsglen);
4511 /*
4512  * Gets the outgoing IP address to use.
4513  *
4514  * "client_laddr" is address we accepted the client on.
4515  " "client_raddr" is the address of the client, on whos behalf we are
4516  *  binding an address on the external side.
4517  *
4518  * "command" is the SOCKS command the client requested.
4519  * "reqhost" is the host in the SOCKS request from the client.
4520  *
4521  * The address to use on the external side is stored in "laddr".
4522  *
4523  * Returns: "laddr", or NULL on failure.  On failure, "emsg" contains
4524  * the reason.
4525  */
4526 
4527 struct sockaddr_storage *
4528 getinaddr(struct sockaddr_storage *laddr,
4529           const struct sockaddr_storage *client,
4530           char *emsg, const size_t emsglen);
4531 /*
4532  * Gets the incoming address to use for a connection from the client address
4533  * "client" (which can be 0.0.0.0) if unknown.  The local address to
4534  * accept the connection on is saved in "laddr" on success.
4535  *
4536  * Only used to decide which address to bind for accepting udp packets *
4537  * currently.
4538  *
4539  * Returns:
4540  *    On success: laddr, populated appropriately.
4541  *    On failure: NULL.  Session should be aborted.  Reason for failure is
4542  *                then stored in "emsg", which must be of len "emsglen".
4543  */
4544 void
4545 sigserverbroadcast(int sig);
4546 /*
4547  * Broadcasts "sig" to other "main" servers (started with "-N" option).
4548  *
4549  */
4550 
4551 void
4552 sockd_pushsignal(const int sig, const siginfo_t *siginfo);
4553 /*
4554  * Adds the signal "sig" to the end of the internal signal stack.
4555  */
4556 
4557 
4558 int
4559 sockd_popsignal(siginfo_t *siginfo);
4560 /*
4561  * Pops the first signal on the internal signal stack.
4562  * Returns the signal number, and stores the siginfo in "siginfo".
4563  */
4564 
4565 ipv6_addrscope_t
4566 ipv6_addrscope(const struct in6_addr *addr);
4567 /*
4568  * Returns the address-scope of the ipv6 address "addr".
4569  */
4570 
4571 unsigned char *
4572 sockd_getmacaddr(const char *ifname, unsigned char *macaddr);
4573 /*
4574  * Writes the mac-address of the interface named "ifname" to "macaddr",
4575  * which must be of at least length ETHER_ADDR_LEN.
4576  * Returns a pointer to macaddress, or NULL if no mac-address
4577  * is set for the interface.
4578  */
4579 
4580 ssize_t
4581 addrindex_on_listenlist(const size_t listc, const listenaddress_t *listv,
4582                         const struct sockaddr_storage *addr,
4583                         const int protocol);
4584 /*
4585  * Checks if "addr" is on the list of internal addresses, as
4586  * given by "listc" and 'listv".
4587  * "protocol" gives the protocol to check for, SOCKS_TCP or SOCKS_UDP.
4588  *
4589  * Returns the index of addr in listv if addr is on the list, or -1 if not.
4590  */
4591 
4592 ssize_t
4593 addrindex_on_externallist(const externaladdress_t *external,
4594                           const struct sockaddr_storage *addr);
4595 /*
4596  * Checks if "addr" is on the list of external addresses, as
4597  * given by "external".
4598  *
4599  * Returns the index of addr in listv if addr is on the list, or -1 if not.
4600  */
4601 
4602 
4603 size_t
4604 maxfreeslots(const int childtype);
4605 /*
4606  * Returns the maximum number of free slots a child of type "childtype"
4607  * can have.
4608  */
4609 
4610 int
4611 child_should_retire( const sockd_child_t *child);
4612 /*
4613  * Returns true if child "child" is ready for retirement, indicating
4614  * we should not send any more clients to it.
4615  *
4616  * Returns false if child "child" is not ready for retiring, meaning
4617  * it should continue to accept new clients as normal.
4618  */
4619 
4620 
4621 void
4622 sockd_print_child_ready_message(const size_t freefds);
4623 /*
4624  * Prints the appropriate startup message for the child calling this
4625  * function.
4626  * "freefds" is the number of free fd's.
4627  */
4628 
4629 int methodcanprovide(const int method, const methodinfo_t what);
4630 /*
4631  * Returns true if method "method" can possibly provide "what".
4632  * It does not mean the method will always provide it, only
4633  * that it can in some cases.
4634  */
4635 
4636 int
4637 methodworkswith(const int method, const methodinfo_t what);
4638 /*
4639  * Returns true if method "method" can possibly work with "what".
4640  */
4641 
4642 
4643 int
4644 rulerequires(const rule_t *rule, const methodinfo_t what);
4645 /*
4646  * Returns true if rule "rule" requires "what".
4647  * Returns false otherwise.
4648  */
4649 
4650 
4651 void
4652 sighup_child(int sig, siginfo_t *si, void *sc);
4653 /*
4654  * SIGHUP-handler for everyone but main mother.
4655  */
4656 
4657 void
4658 io_handlesighup(void);
4659 /*
4660  * Called at sighup to let the i/o childs do what they need to do
4661  * upon receiving a sighup.
4662  */
4663 
4664 int sockd_check_ipclatency(const char *description,
4665                            const struct timeval *tsent,
4666                            const struct timeval *treceived,
4667                            const struct timeval *tnow);
4668 /*
4669  * checks whether the delay between a packet sent by process N (e.g.,
4670  * the negotiate-process) at time "tsent", and received by process
4671  * N + 1 (e.g., the request-process) at time "treceived" indicates
4672  * we are overloaded.
4673  *
4674  * "tnow" is the current time, and is used to avoid printing warnings
4675  * too frequently.  It is included in the API for this function in order
4676  * to avoid an unnecessary system call since "treceived" and "tnow" will
4677  * usually be the same.
4678  *
4679  * Returns true, and possibly prints a warning if we are overloaded.
4680  * Returns false if no overload condition is detected.
4681  */
4682 
4683 
4684       /*
4685        * for the i/o processes only.
4686        */
4687 
4688 typedef struct {
4689    /*
4690     * number of currently free file descriptors.  Should never become
4691     * a problem for Dante or Covenant, but Barefoot needs to keep track
4692     * of it so it does not end up using up all fds for udp clients, then
4693     * becomes unable to receive a new io from mother.
4694     */
4695    size_t freefds;
4696 
4697    /*
4698     * do any active i/o objects have a connect that we do not know whether
4699     * have completed or not yet?
4700     */
4701    int haveconnectinprogress;
4702 
4703 } iostate_t;
4704 
4705 
4706 #if BAREFOOTD
4707 
4708 void
4709 update_clientpointers(const size_t dstc, udptarget_t *dstv);
4710 /*
4711  * Updates the pointers in "dstv" after a realloc(3).
4712  */
4713 
4714 int
4715 io_remove_session(const size_t ioc, sockd_io_t *iov,
4716                   const struct sockaddr_storage *laddr, const int protocol,
4717                   const iostatus_t reason);
4718 /*
4719  * This function tries to find a session in iov where the local address is
4720  * "addr" and is using protocol "protocol".  If found, the session is removed.
4721  * If "addr" is NULL, all sessions using protocol "protocol" are removed.
4722  *
4723  * "reason" gives the reason why the session should be removed.
4724  *
4725  * Returns:
4726  *    If a matching session was found: 0.
4727  *    If no matching session was found: -1.
4728  */
4729 
4730 iostatus_t
4731 io_udp_client2target(sockd_io_direction_t *in, sockd_io_direction_t *out,
4732                      const authmethod_t *cauth, connectionstate_t *state,
4733                      iologaddr_t *src, iologaddr_t *dst,
4734                      int *bad, rule_t *packetrule, size_t *bwused);
4735 /*
4736  * Tries to read a udp packet from the socket in "in" and send it out on
4737  * the socket in "out".
4738  * "state" is the connection state of the io object "in" and "out" belong to.
4739  *
4740  * "lowerlevelrule" will be the rule matched at the previous (lower) level,
4741  * i.e., a clientrule or a hostidrule.
4742  *
4743  * "packetrule" is the rule used for sending a packet from "in" to "out".
4744  *
4745  * When called it will contain information necessary to call iolog() if
4746  * an error is detected before we get far enough to be be able to do a
4747  * full rule lookup.  Upon return, if there was no error, it will contain
4748  * the rule used for the forwarded packet.
4749  *
4750  * Returns a status code indicating whether the packet was forwarded or not.
4751  * If a fatal error occurred and the session should be removed, "bad" is
4752  * set to the socket where the error occurred (the socket in "in" or "out"
4753  * if it can be determined, or it will remain unchanged if not.
4754  */
4755 
4756 iostatus_t
4757 io_udp_target2client(sockd_io_direction_t *in,
4758                      sockd_io_direction_t *out,
4759                      const authmethod_t *cauth,
4760                      connectionstate_t *state,
4761                      iologaddr_t *src, iologaddr_t *dst,
4762                      int *bad, rule_t *packetrule, size_t *bwused);
4763 /*
4764  * The opposite of io_udp_client2target().
4765  */
4766 
4767 
4768 #elif SOCKS_SERVER
4769 
4770 iostatus_t
4771 io_udp_client2target(sockd_io_direction_t *control, sockd_io_direction_t *in,
4772                      sockd_io_direction_t *out, const authmethod_t *cauth,
4773                      connectionstate_t *state, iologaddr_t *clog,
4774                      iologaddr_t *dlog, int *bad,
4775                      rule_t *packetrule, size_t *bwused);
4776 /*
4777  * Tries to read a udp packet from the socket in "in" and send it out on
4778  * the socket in "out".
4779  * "state" is the connection state of the io object "in" and "out" belong to.
4780  *
4781  * "packetrule" is the rule used for sending a packet from "in" to "out".
4782  * When called it will contain information necessary to call iolog() if
4783  * an error is detected before we get far enough to be be able to do a
4784  * full rule lookup.  If the sockets are connected, "packetrule" may contain
4785  * all the necessary information and no rule lookup may be necessary.
4786  * Upon return, if there was no error, it will contain the rule used for the
4787  * forwarded packet.
4788  *
4789  * Returns a status code indicating whether the packet was forwarded or not.
4790  * If a fatal error occurred and the session should be removed, "bad" is
4791  * set to the socket where the error occurred (the socket in "in" or "out"
4792  * if it can be determined, or it will remain unchanged if not.
4793  */
4794 
4795 iostatus_t
4796 io_udp_target2client(sockd_io_direction_t *control,
4797                      sockd_io_direction_t *in, sockd_io_direction_t *out,
4798                      connectionstate_t *state,
4799                      iologaddr_t *clog, iologaddr_t *dlog, int *bad,
4800                      rule_t *packetrule, size_t *bwused);
4801 /*
4802  * The opposite of io_udp_client2target().
4803  */
4804 
4805 #endif /* SOCKS_SERVER */
4806 
4807 #if COVENANT
4808 
4809 int
4810 resend_client(sockd_io_t *io);
4811 /*
4812  * Resends the client using "io" to mother, for renegotiation.
4813  * This happens when a http client wants to connect to a different
4814  * remote server.
4815  *
4816  * Returns 0 on success, -1 on error.
4817  */
4818 
4819 int
4820 recv_resentclient(int s, sockd_client_t *client);
4821 /*
4822  * Receives the resent client from "s".  The resent client
4823  * stored in "client".
4824  *
4825  * Returns 0 on success, -1 on error.
4826  */
4827 
4828 negotiate_result_t
4829 recv_httprequest(int s, request_t *request,
4830                  negotiate_state_t *state);
4831 /*
4832  * Reads a http request from the socket "s", which can be set to
4833  * non-blocking.
4834  * "request" will be filled in as reading progresses but it should
4835  * be considered of indeterminate contents until the whole request
4836  * has been read.
4837  * Returns:
4838  *    On success: > 0
4839  *    On failure: <= 0.  If errno does not indicate the request should be
4840  *                       be retried, the connection "s" should be dropped.
4841  */
4842 
4843 int
4844 parse_httprequest(request_t *reqinfo, const char *req,
4845                   char *emsg, size_t emsglen);
4846 /*
4847  * Parses the http request present in the NUL-terminated string "req".
4848  * The information extracted from the request is stored in "reqinfo".
4849  *
4850  * Returns 0 on success, or -1 on error.  On error, "emsg", of size "emsglen"
4851  * is filled in with information about the error.
4852  */
4853 
4854 size_t
4855 httpresponse2mem(const int s, const response_t *response,
4856                  char *buf, const size_t buflen);
4857 
4858 #endif /* COVENANT */
4859 
4860 #if HAVE_NEGOTIATE_PHASE
4861 int
4862 send_connectresponse(const int s, const int error, sockd_io_t *io);
4863 /*
4864  * Sends the response to a connect request issued by the client
4865  * connected to the socket "s".  "io" is the object we created for
4866  * the client.
4867  *
4868  * "error", if not 0, is the errno value corresponding to the failure.
4869  * If "error" is 0, the connect succeeded, otherwise "error" is the
4870  * errno value corresponding to the failed connect(2).
4871  *
4872  * Returns 0 if the response was sent, -1 if an i/o error occurred.
4873  */
4874 
4875 response_t *
4876 create_response(const sockshost_t *host, authmethod_t *auth,
4877                 const int proxyprotocol, const int responsecode,
4878                 response_t *response);
4879 /*
4880  * Fills in the responseobject "response" based on data the passed data.
4881  * "responsecode" is responsecode, using proxyprotocol proxyprotocol" to
4882  * set the reply to.
4883  * If "host" is not NULL, it is the host to use in response.
4884  * If "host" is NULL, an all-zero ipv4 address is used instead.
4885  */
4886 
4887 void
4888 send_failure(const int s, response_t *response, const unsigned int failure);
4889 /*
4890  * Wrapper around send_response() that sends a failure message to the
4891  * client connected to "s" and deletes gss state if in use.
4892  *
4893  * "response" is the packet we send,
4894  * "failure" is the errno reason for failure,
4895  * and "auth" is the agreed on authentication.
4896  */
4897 
4898 int
4899 send_response(int s, const response_t *response);
4900 /*
4901  * Sends "response" to "s".
4902  *      On success: 0
4903  *      On failure: -1
4904  */
4905 
4906 #else /* !HAVE_NEGOTIATE_PHASE */
4907 
4908 #define send_failure(s, response, failure)
4909 #define send_response(s, response)            (0)
4910 
4911 #endif /* !HAVE_NEGOTIATE_PHASE */
4912 
4913 #if DIAGNOSTIC
4914 void doconfigtest(void);
4915 void shmemcheck(void);
4916 /*
4917  * Internal testing functions.
4918  */
4919 
4920 
4921 void
4922 checksockoptions(const int s, const sa_family_t family, const int type,
4923                  const int isclientside);
4924 /*
4925  * checks that the expected options are set on the socket and prints
4926  * warnings if not.
4927  */
4928 #endif /* DIAGNOSTIC */
4929 
4930 #endif /* !_SOCKD_H_ */
4931