1 /* 2 * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 3 * 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016, 2017, 2019, 4 * 2020, 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: common.h,v 1.931.4.7.2.8.4.20 2021/02/02 19:34:15 karls Exp $ */ 47 48 #ifndef _COMMON_H_ 49 #define _COMMON_H_ 50 51 /* ifdef, not if, defined on command line */ 52 #ifdef HAVE_CONFIG_H 53 #include "autoconf.h" 54 #endif /* HAVE_CONFIG_H */ 55 56 #ifndef NO_OSDEP 57 #include "osdep.h" 58 #endif /* !NO_OSDEP */ 59 60 #include "yacconfig.h" 61 62 #include "config.h" 63 64 /* global variables needed by everyone. */ 65 extern struct config sockscf; 66 extern char *__progname; 67 68 /* 69 * defines 70 */ 71 72 /* 73 * If we are compiling for unit-tests, there are functions 74 * that normally have static/file-local scope, but which we 75 * want to test in the unit-tests. The below #define is used as 76 * an easy way to make those functions be compiled with global 77 * scope for unit-tests. 78 */ 79 #if STANDALONE_UNIT_TEST 80 #define UNIT_TEST_STATIC_SCOPE 81 #else 82 #define UNIT_TEST_STATIC_SCOPE static 83 #endif 84 85 #if DIAGNOSTIC 86 /* 87 * Takes too much time, leading to one or more shmem-files usually having 88 * been deleted already by mother before child-processes get around to 89 * checking them. Instead enable this only if we (again) suspect there 90 * are bugs related to corruption of the shmem-header. 91 */ 92 #define DO_SHMEMCHECK (0) 93 #else 94 #define DO_SHMEMCHECK (0) 95 #endif 96 97 98 /* 99 * We base ourselves on RFC 5424. (LOG_ALERT (0) - LOG_DEBUG (7)) 100 */ 101 #define MAXLOGLEVELS (8) 102 103 104 #define PIPEBUFFER_IS_SEND_BASED (0) 105 #define PIPEBUFFER_IS_RECV_BASED (1) 106 #define PIPEBUFFER_IS_UNKNOWN_BASED (0) 107 108 #if HAVE_SOLARIS_BUGS 109 #define HAVE_UNIQUE_SOCKET_INODES (0) 110 #else /* !HAVE_SOLARIS_BUGS */ 111 #define HAVE_UNIQUE_SOCKET_INODES (1) 112 #endif /* HAVE_SOLARIS_BUGS */ 113 114 #define SOCKS_IGNORE_SIGNALSAFETY (0) 115 116 #if PRERELEASE 117 118 /* 119 * Solaris 2.5.1 and it's stream stuff is broken and puts the processes 120 * into never-never land forever on half the sendmsg() calls if they 121 * involve ancillary data. (it seems to deadlock the processes.) 122 * XXX need to retest what the current status of this is. 123 */ 124 /* always enable if PRERELEASE */ 125 #undef HAVE_SENDMSG_DEADLOCK 126 #define HAVE_SENDMSG_DEADLOCK 1 127 128 #endif /* PRERELEASE */ 129 130 #define TOIN(addr) ((struct sockaddr_in *)(addr)) 131 #define TOCIN(addr) ((const struct sockaddr_in *)(addr)) 132 133 #define TOIN6(addr) ((struct sockaddr_in6 *)(addr)) 134 #define TOCIN6(addr) ((const struct sockaddr_in6 *)(addr)) 135 136 #define TOSA(addr) ((struct sockaddr *)addr) 137 #define TOCSA(addr) ((const struct sockaddr *)addr) 138 #define TOSS(addr) ((struct sockaddr_storage *)addr) 139 #define TOCSS(addr) ((const struct sockaddr_storage *)addr) 140 141 #define IP_MAXPORT (65535) /* max value for ip port number. */ 142 143 144 /* 145 * redefine system limits to match that of socks protocol. 146 * No need for these to be bigger than protocol allows, but they 147 * _must_ be at least as big as protocol allows. 148 */ 149 150 #ifdef MAXHOSTNAMELEN 151 #undef MAXHOSTNAMELEN 152 #endif /* MAXHOSTNAMELEN */ 153 #define MAXHOSTNAMELEN (255 + 1) /* socks5: 255, +1 for len. */ 154 155 #ifndef MAXSERVICELEN 156 #define MAXSERVICELEN (255 + 1) /* aka /etc/services. */ 157 #endif /* MAXSERVICELEN */ 158 159 160 #ifdef MAXURLLEN 161 #undef MAXURLLEN 162 #endif /* MAXURLLEN */ 163 #define MAXURLLEN (255 + 1) /* whatever. */ 164 165 #ifdef MAXNAMELEN 166 #undef MAXNAMELEN 167 #endif /* MAXNAMELEN */ 168 #define MAXNAMELEN (255 + 1) /* socks5: 255, +1 for len. */ 169 170 #ifdef MAXPWLEN 171 #undef MAXPWLEN 172 #endif /* MAXPWLEN */ 173 #define MAXPWLEN (255 + 1) /* socks5: 255, +1 for len. */ 174 175 #define MAXTCPINFOLEN (2048) 176 177 #if HAVE_GSSAPI 178 #ifdef MAXGSSAPITOKENLEN 179 #undef MAXGSSAPITOKENLEN 180 #endif /* MAXGSSAPITOKENLEN */ 181 #define MAXGSSAPITOKENLEN (1024 * 64 - 1) /* socks5: up to 2^16 - 1 */ 182 183 /* 184 * GSSAPI headerlen (NOTE: SOCKS GSSAPI headerlen. After stripping of 185 * the socks gssapi header, there is another non-socks gssapi header 186 * also on the token). 187 */ 188 #define GSSAPI_HLEN (4) 189 190 /* 191 * XXX should be max-size of exported state, but we don't know what it is. 192 * Is there any way to find out? 193 */ 194 #define MAX_GSS_STATE (4000) 195 196 #endif /* HAVE_GSSAPI */ 197 198 #if HAVE_PAC 199 200 #ifdef MAXSIDSLEN 201 #undef MAXSIDSLEN 202 #endif /* MAXSIDSLEN */ 203 #define MAXSIDSLEN (200*60 + 1) /* assume max 40 sids (groups) */ 204 205 #endif /* HAVE_PAC */ 206 207 /* max number of socket options to set on the external side, per rule. */ 208 #define MAX_EXTERNAL_SOCKETOPTIONS (5) 209 210 #define MAXIFNAMELEN (255) 211 212 #define MAXSOCKADDRSTRING \ 213 (sizeof("0000:0000:0000:0000:0000:0000:0000:0000.65535")) 214 215 /* "." + "65535" + NUL */ 216 #define MAXSOCKSHOSTSTRING (MAXHOSTNAMELEN + 1 + 5) 217 #define MINSOCKSHOSTLEN ( 1 /* ATYPE */ \ 218 + 2 /* DST.ADDR (LEN + 1) */ \ 219 + 2 /* DST.PORT */) 220 221 #define MAXSOCKSHOSTLEN ( 1 /* ATYPE */ \ 222 + 1 /* DST.ADDR LEN */ \ 223 + MAXHOSTNAMELEN /* DST.ADDR */ \ 224 + 2 /* DST.PORT */) 225 226 #define MINSOCKSUDPHLEN ( 2 /* RSV */ \ 227 + 1 /* FRAG */ \ 228 + MINSOCKSHOSTLEN) 229 230 #define MAXSOCKSUDPHLEN ( 2 /* RSV */ \ 231 + 1 /* FRAG */ \ 232 + MAXSOCKSHOSTLEN) 233 234 #define MAXRULEADDRSTRING (MAXSOCKSHOSTSTRING * 2 + 32 /* atype, etc. */) 235 #define MAXGWSTRING (MAXSOCKSHOSTSTRING) 236 237 238 #define MAXSUBDOMAINS (10) /* a.b.c.d.e.f ... */ 239 240 241 #define MAXAUTHINFOLEN (((sizeof("(") - 1) + MAXMETHODSTRING) \ 242 + (sizeof(")") - 1) + (sizeof("@") - 1) + MAXNAMELEN) 243 244 245 #define MAXFACILITYNAMELEN (8 + 1) /* max length of syslog facility name. */ 246 247 #ifndef NUL 248 #define NUL '\0' 249 #endif /* !NUL */ 250 251 #define CONFIGTYPE_SERVER 1 252 #define CONFIGTYPE_CLIENT 2 253 254 #define PROTOCOL_TCPs "tcp" 255 #define PROTOCOL_UDPs "udp" 256 #define PROTOCOL_UNKNOWNs "unknown" 257 258 #define SOCKS_TCP (1) 259 #define SOCKS_UDP (2) 260 261 #define RESOLVEPROTOCOL_UDP (SOCKS_UDP) 262 #define RESOLVEPROTOCOL_TCP (SOCKS_TCP) 263 #define RESOLVEPROTOCOL_FAKE (3) 264 265 #define LOGTYPE_SYSLOG 0x1 266 #define LOGTYPE_FILE 0x2 267 268 /* 269 * Some things we may want to log at different levels in the server and 270 * the client. Use #defines here that map to the appropriate level. 271 */ 272 #if SOCKS_CLIENT 273 #define LOG_NEGOTIATE (LOG_INFO) 274 #else /* SOCKS_SERVER */ 275 #define LOG_NEGOTIATE (LOG_DEBUG) 276 #endif 277 278 279 #define NOMEM "<memory exhausted>" 280 281 /* environment variables used. */ 282 #define ENV_HTTP_PROXY "HTTP_CONNECT_PROXY" 283 #define ENV_SOCKS4_SERVER "SOCKS4_SERVER" 284 #define ENV_SOCKS5_PASSWD "SOCKS5_PASSWD" 285 #define ENV_SOCKS5_SERVER "SOCKS5_SERVER" 286 #define ENV_SOCKS5_USER "SOCKS5_USER" 287 #define ENV_SOCKS_BINDLOCALONLY "SOCKS_BINDLOCALONLY" 288 #define ENV_SOCKS_CONF "SOCKS_CONF" 289 #define ENV_SOCKS_DEBUG "SOCKS_DEBUG" 290 #define ENV_SOCKS_DIRECTROUTE_FALLBACK "SOCKS_DIRECTROUTE_FALLBACK" 291 #define ENV_SOCKS_DISABLE_THREADLOCK "SOCKS_DISABLE_THREADLOCK" 292 #define ENV_SOCKS_ERRLOGOUTPUT "SOCKS_ERRLOGOUTPUT" 293 #define ENV_SOCKS_FORCE_BLOCKING_CONNECT "SOCKS_FORCE_BLOCKING_CONNECT" 294 #define ENV_SOCKS_LOGOUTPUT "SOCKS_LOGOUTPUT" 295 #define ENV_SOCKS_PASSWD "SOCKS_PASSWD" 296 #define ENV_SOCKS_PASSWORD "SOCKS_PASSWORD" 297 #define ENV_SOCKS_ROUTE_ "SOCKS_ROUTE_" /* _<number> */ 298 #define ENV_SOCKS_SERVER "SOCKS_SERVER" 299 #define ENV_SOCKS_USER "SOCKS_USER" 300 #define ENV_SOCKS_USERNAME "SOCKS_USERNAME" 301 #define ENV_TMPDIR "TMPDIR" 302 #define ENV_UPNP_IGD "UPNP_IGD" 303 #define ENV_SOCKS_AUTOADD_LANROUTES "SOCKS_AUTOADD_LANROUTES" 304 #define ENV_SOCKS_REDIRECT_FROM "SOCKS_REDIRECT_FROM" 305 306 /* 307 * macros 308 */ 309 310 /* 311 * CompileTime assert. Based on an article in DrDobbs by Ralf Holly. 312 * (http://www.drdobbs.com/compile-time-assertions/184401873) 313 */ 314 #define CTASSERT(exp) \ 315 do { \ 316 enum { assert_static__ = 1/(exp) }; \ 317 } while (/* CONSTCOND */ 0) 318 319 /* 320 * Error macros. 321 */ 322 323 #if HAVE_LIVEDEBUG /* try to generate a coredump and continue if server. */ 324 325 #if SOCKS_CLIENT 326 #define SET_INTERNAL_ERROR() do { \ 327 sockscf.state.internalerrordetected = 1; \ 328 } while (/* CONSTCOND */ 0) 329 330 #else /* !SOCKS_CIENT */ 331 #define SET_INTERNAL_ERROR() do { } while (/* CONSTCOND */ 0) 332 #endif /* !SOCKS_CLIENT */ 333 334 #define HANDLE_RINGBUFFER() \ 335 do { \ 336 SET_INTERNAL_ERROR(); \ 337 \ 338 if (!sockscf.option.debug) \ 339 socks_flushrb(); \ 340 } while (/* CONSTCOND */ 0) 341 342 #else /* !HAVE_LIVEDEBUG */ 343 #define HANDLE_RINGBUFFER() do { } while (/* CONSTCOND */ 0) 344 345 #endif /* !HAVE_LIVEDEBUG */ 346 347 #define SASSERT_STARTSTRING "an internal error was detected at " 348 #define SASSERT_ENDSTRING \ 349 "Please report this to Inferno Nettverk A/S at \"" LCPRODUCT "-bugs@inet.no\"."\ 350 " Please check for a coredump too." 351 352 #define SIGNALSLOG_WITH_ERRNO(value, expstr, err) \ 353 do { \ 354 char _b[10][32]; \ 355 const char *_msgv[] \ 356 = { SASSERT_STARTSTRING, \ 357 __FILE__, \ 358 ":", \ 359 ltoa(__LINE__, _b[0], sizeof(_b[0])), \ 360 ", value ", \ 361 ltoa((value), _b[1], sizeof(_b[1])), \ 362 ", expression \"", \ 363 (expstr), \ 364 "\", errno ", \ 365 ltoa(err, _b[2], sizeof(_b[2])), \ 366 " (", \ 367 strerror(errno), \ 368 "). Version: ", \ 369 rcsid, \ 370 ". ", \ 371 SASSERT_ENDSTRING, \ 372 NULL \ 373 }; \ 374 \ 375 signalslog(LOG_WARNING, _msgv); \ 376 } while (/* CONSTCOND */ 0) \ 377 378 #define SIGNALSLOG_WITHOUT_ERRNO(value, expstr) \ 379 do { \ 380 char _b[10][32]; \ 381 const char *_msgv[] \ 382 = { SASSERT_STARTSTRING, \ 383 __FILE__, \ 384 ":", \ 385 ltoa(__LINE__, _b[0], sizeof(_b[0])), \ 386 ", value ", \ 387 ltoa((value), _b[1], sizeof(_b[1])), \ 388 ", expression \"", \ 389 (expstr), \ 390 "\"", \ 391 ". Version: ", \ 392 rcsid, \ 393 ". ", \ 394 SASSERT_ENDSTRING, \ 395 NULL \ 396 }; \ 397 \ 398 signalslog(LOG_WARNING, _msgv); \ 399 } while (/* CONSTCOND */ 0) 400 401 #define SIGNALSLOG_WITH_ERRNO_FAD(_value, expstr, err) \ 402 do { \ 403 char _b[10][32]; \ 404 const char *_msgv[] \ 405 = { SASSERT_STARTSTRING, \ 406 __FILE__, \ 407 ":", \ 408 ltoa(__LINE__, _b[0], sizeof(_b[0])), \ 409 ", by pid ", \ 410 ltoa(getppid(), _b[1], sizeof(_b[1])), \ 411 ". Value ", \ 412 ltoa((_value), _b[2], sizeof(_b[2])), \ 413 ", expression \"", \ 414 (expstr), \ 415 "\", errno ", \ 416 ltoa(err, _b[3], sizeof(_b[3])), \ 417 " (", \ 418 strerror(errno), \ 419 "). Version: ", \ 420 rcsid, \ 421 ". ", \ 422 SASSERT_ENDSTRING, \ 423 NULL \ 424 }; \ 425 \ 426 signalslog(LOG_WARNING, _msgv); \ 427 } while (/* CONSTCOND */ 0) \ 428 429 #define SIGNALSLOG_WITHOUT_ERRNO_FAD(_value, expstr) \ 430 do { \ 431 char _b[10][32]; \ 432 const char *_msgv[] \ 433 = { SASSERT_STARTSTRING, \ 434 __FILE__, \ 435 ":", \ 436 ltoa(__LINE__, _b[0], sizeof(_b[0])), \ 437 ", by pid ", \ 438 ltoa(getppid(), _b[1], sizeof(_b[1])), \ 439 ". Value ", \ 440 ltoa((_value), _b[2], sizeof(_b[2])), \ 441 ", expression \"", \ 442 (expstr), \ 443 "\"", \ 444 ". Version: ", \ 445 rcsid, \ 446 ". ", \ 447 SASSERT_ENDSTRING, \ 448 NULL \ 449 }; \ 450 \ 451 signalslog(LOG_WARNING, _msgv); \ 452 } while (/* CONSTCOND */ 0) 453 454 #define SERR_BODY(_value, expstr, _err) \ 455 do { \ 456 const int err = (_err); \ 457 \ 458 SIGNALSLOG_WITH_ERRNO(_value, expstr, err); \ 459 HANDLE_RINGBUFFER(); \ 460 abort(); \ 461 } while (/* CONSTCOND */ 0) 462 463 \ 464 #define SERRX_BODY(_value, expstr) \ 465 do { \ 466 SIGNALSLOG_WITHOUT_ERRNO(_value, expstr); \ 467 HANDLE_RINGBUFFER(); \ 468 abort(); \ 469 } while (/* CONSTCOND */ 0) 470 471 472 #define SWARN_BODY(_value, expstr, _err) \ 473 do { \ 474 pid_t forked; \ 475 const int err = (_err); \ 476 \ 477 switch ((forked = fork())) { \ 478 case -1: \ 479 SIGNALSLOG_WITH_ERRNO(_value, expstr, err); \ 480 break; \ 481 \ 482 case 0: \ 483 newprocinit(); \ 484 SIGNALSLOG_WITH_ERRNO_FAD(_value, expstr, err); \ 485 HANDLE_RINGBUFFER(); \ 486 abort(); \ 487 break; /* NOTREACHED */ \ 488 \ 489 default: \ 490 SIGNALSLOG_PARENT_CONTINUING(forked); \ 491 } \ 492 } while (/* CONSTCOND */ 0) 493 494 #define SWARNX_BODY(_value, expstr) \ 495 do { \ 496 pid_t forked; \ 497 \ 498 switch ((forked = fork())) { \ 499 case -1: \ 500 SIGNALSLOG_WITHOUT_ERRNO(_value, expstr); \ 501 break; \ 502 \ 503 case 0: \ 504 newprocinit(); \ 505 SIGNALSLOG_WITHOUT_ERRNO_FAD(_value, expstr); \ 506 HANDLE_RINGBUFFER(); \ 507 abort(); \ 508 break; /* NOTREACHED */ \ 509 \ 510 default: \ 511 SIGNALSLOG_PARENT_CONTINUING(forked); \ 512 } \ 513 } while (/* CONSTCOND */ 0) 514 515 #define SIGNALSLOG_PARENT_CONTINUING(childpid) \ 516 do { \ 517 char _b[10][32]; \ 518 const char *_msgv[] \ 519 = { "continuing after internal error. Unless disabled on system we " \ 520 "should have a coredump from pid ", \ 521 ltoa(getpid(), _b[0], sizeof(_b[0])), \ 522 " by way of pid ", \ 523 ltoa((childpid), _b[1], sizeof(_b[1])), \ 524 " now", \ 525 NULL \ 526 }; \ 527 \ 528 signalslog(LOG_WARNING, _msgv); \ 529 } while (/* CONSTCOND */ 0) 530 531 532 #define SWARN(expression) \ 533 do { \ 534 const long _value = (const long)(expression); \ 535 const char *expstr = #expression; \ 536 \ 537 SWARN_BODY(_value, expstr, errno); \ 538 } while (/* CONSTCOND */ 0) 539 540 #define SWARNX(expression) \ 541 do { \ 542 const long _value = (const long)(expression); \ 543 const char *expstr = #expression; \ 544 \ 545 SWARNX_BODY(_value, expstr); \ 546 } while (/* CONSTCOND */ 0) 547 548 #define SERR(expression) \ 549 do { \ 550 const long _value = (const long)(expression); \ 551 const char *expstr = #expression; \ 552 \ 553 SERR_BODY(_value, expstr, errno); \ 554 } while (/* CONSTCOND */ 0) 555 556 #define SERRX(expression) \ 557 do { \ 558 const long _value = (const long)(expression); \ 559 const char *expstr = #expression; \ 560 \ 561 SERRX_BODY(_value, expstr); \ 562 } while (/* CONSTCOND */ 0) 563 564 #define SASSERT(expression) \ 565 do { \ 566 const long _value = (const long)(expression); \ 567 const char *expstr = #expression; \ 568 \ 569 if (_value == 0) \ 570 SERR_BODY(_value, expstr, errno); \ 571 } while (/* CONSTCOND */ 0) 572 573 #define SASSERTX(expression) \ 574 do { \ 575 const long _value = (const long)(expression); \ 576 const char *expstr = #expression; \ 577 \ 578 if (_value == 0) \ 579 SERRX_BODY(_value, expstr); \ 580 } while (/* CONSTCOND */ 0) 581 582 #if 0 583 /* so we can attach to the process while it's alive ... */ 584 #define abort() do { sleep(60); } while (1) 585 #endif 586 587 588 /* 589 * Make sure length of "_src" is not larger than the size of "_dst". 590 */ 591 #define STRCPY_ASSERTLEN(__dst, __src) \ 592 do { \ 593 const void *_src = (__src); \ 594 const size_t _len = strlen((const char *)_src); \ 595 void *_dst = (__dst); \ 596 \ 597 SASSERTX(_len <= (sizeof((__dst)) - 1)); \ 598 memcpy((_dst), (_src), _len + 1); \ 599 } while (/* CONSTCOND */ 0) 600 601 602 /* 603 * Round up or down a struct timeval to whole seconds. 604 */ 605 #define timeval2seconds(tval) \ 606 ((tval)->tv_sec + ((tval)->tv_usec >= 500000 ? 1 : 0)) 607 608 609 /* 610 * Make sure length of "_src" is not lager than "maxlen", and copy it to _dst. 611 */ 612 #define STRCPY_CHECKLEN(__dst, __src, _maxlen, _function) \ 613 do { \ 614 const void *_src = (__src); \ 615 const size_t _len = strlen((const char *)_src); \ 616 void *_dst = (__dst); \ 617 \ 618 if (_len >= (_maxlen) - 1) { \ 619 _function("the value given is %lu bytes long, but the maximum length, " \ 620 "set at compiletime, is %lu", \ 621 (unsigned long)(_len), \ 622 (unsigned long)((_maxlen))); \ 623 break; \ 624 } \ 625 \ 626 memcpy((_dst), (_src), _len + 1); \ 627 } while (/* CONSTCOND */ 0) 628 629 630 #define STRCPY_ASSERTSIZE(__dst, __src) \ 631 do { \ 632 const void *_src = (__src); \ 633 const size_t _len = strlen((const char *)_src); \ 634 void *_dst = (__dst); \ 635 \ 636 CTASSERT(sizeof((__dst)) >= sizeof((__src))); \ 637 SASSERTX(_len + 1 <= sizeof((__dst))); \ 638 SASSERTX(_len + 1 <= sizeof((__src))); \ 639 \ 640 memcpy((_dst), (_src), _len + 1); \ 641 } while (0 /* CONSTCOND */) 642 643 644 #define STRCPY_CHECKUTFLEN(__dst, __src, _maxlen, _function) \ 645 do { \ 646 const void *_src = (__src); \ 647 const size_t _len = strlen((const char *)__src); \ 648 void *_dst = (__dst); \ 649 char *utfsrc; \ 650 \ 651 if (_len / 2 >= ((_maxlen) - 1)) { \ 652 _function("the value given is %lu bytes long, but the maximum length, " \ 653 "set at compiletime, is %lu", \ 654 (unsigned long)(_len / 2), \ 655 (unsigned long)((_maxlen) - 1)); \ 656 break; \ 657 } \ 658 \ 659 if ((utfsrc = hextoutf8((const char *)_src, 2)) == NULL) \ 660 _function("failed to convert string \"%s\" to UTF-8", \ 661 (const char *)_src); \ 662 \ 663 strncpy((char *)_dst, utfsrc, (_maxlen) - 1); \ 664 ((char *)(_dst))[(_maxlen) - 1] = NUL; \ 665 } while (/* CONSTCOND */ 0) 666 667 668 #define TVMIN(a, b) \ 669 (timercmp((a), (b), <) ? (a) : (b)) 670 671 #define TVMAX(a, b) \ 672 (timercmp((a), (b), >) ? (a) : (b)) 673 674 675 /* 676 * Can not call these function directly since we need to make sure unused 677 * bytes in the destination are zero (requirement of the socket API), 678 * but the size of the destination can vary. :-/ 679 */ 680 681 #define sockshost2sockaddr2(host, addr, gaierr, emsg, emsglen) \ 682 int_sockshost2sockaddr2((host), \ 683 (addr), \ 684 sizeof((*addr)), \ 685 (gaierr), \ 686 (emsg), \ 687 (emsglen)) \ 688 689 #define sockshost2sockaddr(host, addr) \ 690 int_sockshost2sockaddr((host), addr, sizeof((*addr))) 691 692 #define fakesockshost2sockaddr(host, addr) \ 693 int_fakesockshost2sockaddr((host), (addr), sizeof((*addr))) 694 695 #define urlstring2sockaddr(string, addr, gaierr, emsg, elen) \ 696 int_urlstring2sockaddr((string), \ 697 (addr), \ 698 sizeof((*addr)), \ 699 (gaierr), \ 700 (emsg), \ 701 (elen)) 702 703 #define ruleaddr2sockaddr(ruleaddr, addr, protocol) \ 704 int_ruleaddr2sockaddr((ruleaddr), (addr), sizeof((*addr)), (protocol)) 705 706 #define ruleaddr2sockaddr2(ruleaddr, addr, protocol, gaierr, emsg, emsglen) \ 707 int_ruleaddr2sockaddr2((ruleaddr), \ 708 (addr), \ 709 (sizeof((*addr))), \ 710 (protocol), \ 711 (gaierr), \ 712 (emsg), \ 713 (emsglen)) 714 715 #define hostname2sockaddr(name, index, addr) \ 716 int_hostname2sockaddr((name), (index), addr, sizeof((*addr))) 717 718 #define hostname2sockaddr2(name, index, addr, gaierr, emsg, emsglen) \ 719 int_hostname2sockaddr2(name, \ 720 index, \ 721 addr, \ 722 sizeof((*addr)), \ 723 gaierr, \ 724 emsg, \ 725 emsglen) 726 727 #define ifname2sockaddr(ifname, index, addr, mask) \ 728 int_ifname2sockaddr((ifname), \ 729 (index), \ 730 (addr), \ 731 sizeof((*addr)), \ 732 (mask), \ 733 sizeof((*mask))) 734 735 736 #if HAVE_GSSAPI 737 #define GSSAPI_OVERHEAD(gssapistate) \ 738 ((MAXGSSAPITOKENLEN - GSSAPI_HLEN) - (gssapistate)->maxgssdata) 739 740 #define GSSERR_IS_OK(e) \ 741 ( (e) == GSS_S_CONTEXT_EXPIRED \ 742 || (e) == GSS_S_CREDENTIALS_EXPIRED) 743 #endif /* HAVE_GSSAPI */ 744 745 /* 746 * Matched against sockscf.option.debug. If the value there is 747 * >= to DEBUG_NORMAL, do normal debug logging. If >= DEBUG_VERBOSE, 748 * do verbose, possibly expensive, debug logging also. 749 */ 750 #define DEBUG_NORMAL (1) 751 #define DEBUG_VERBOSE (2) 752 #define DEBUG_DEBUG (9) /* only for debuging problems. */ 753 754 /* 755 * If client, it might need to call malloc(3) to expand socksfdv 756 * from the signal handler upon SIGIO, but if we are in a gssapi-function 757 * that also is calling malloc(3) ... Still not safe of course, as we 758 * have no idea if client is in a function that has called malloc(3). 759 */ 760 #if SOCKS_CLIENT 761 762 #define SOCKS_SIGBLOCK_IF_CLIENT(sig, oldset) \ 763 do { socks_sigblock(sig, oldset); } while (/* CONSTCOND */ 0) 764 765 #define SOCKS_SIGUNBLOCK_IF_CLIENT(oldset) \ 766 do { socks_sigunblock(oldset); } while (/* CONSTCOND */ 0) 767 768 #define SIGSET_ALLOCATE(name) sigset_t name 769 770 #else /* !SOCKS_CLIENT */ 771 #define SIGSET_ALLOCATE(name) 772 #define SOCKS_SIGBLOCK_IF_CLIENT(sig, oldset) 773 #define SOCKS_SIGUNBLOCK_IF_CLIENT(oldset) 774 #endif /* !SOCKS_CLIENT */ 775 776 /* due to external libraries/software trying to log to stdout/stderr. :-( */ 777 #define FD_IS_RESERVED_EXTERNAL(fd) \ 778 ((fd) == STDOUT_FILENO || (fd) == STDERR_FILENO) 779 780 781 /* 782 * when using very large numbers (e.g., 9223372036854775807 on a 64 bit cpu), 783 * difftime() returns strange results, even when the second arg is 0. 784 * Don't know why, but converting the time_t value to double and 785 * then back to time_t changes 9223372036854775807 to -9223372036854775808, 786 * which seems to be what happens when we do the equivalent of 787 * difftime(9223372036854775807, 0) 788 * 789 * The below seems to work better, so use it until we encounter a platform 790 * where it does not work better. 791 */ 792 #define socks_difftime(t1, t2) ((t1) - (t2)) 793 794 /* 795 * Wrappers for our own functions that modify things a little in a way 796 * that should not have any negative effects. 797 */ 798 #define close(n) closen((n)) 799 #define socket(d, t, p) socks_socket((d), (t), (p)) 800 #define strerror(e) socks_strerror((e)) 801 #define getifaddrs(ifap) socks_getifaddrs((ifap)) 802 #define gai_strerror(errcode) socks_gai_strerror((errcode)) 803 804 #undef snprintf 805 #define snprintf snprintfn 806 807 /* 808 * If "str", of size "strused", contains characters present in 809 * "strip", strips them off from "str". 810 */ 811 #define STRIPTRAILING(str, strused, strip) \ 812 do { \ 813 ssize_t i; \ 814 \ 815 for (i = (ssize_t)(strused) - 1; i > 0; --i) \ 816 if (strchr((strip), str[i]) != NULL) \ 817 (str)[i] = NUL; \ 818 else \ 819 break; \ 820 } while (/* CONSTCOND */ 0) 821 822 #define SKIPLEADING(str, strip) \ 823 do { \ 824 while (*(str) != NUL) \ 825 if (strchr((strip), *(str))) \ 826 ++(str); \ 827 else \ 828 break; \ 829 } while (/* CONSTCOND */ 0) 830 831 832 /* 833 * for dynamically-sized fd_sets. Note that this means all our fd_set's 834 * must be maxsize, or the macros we define will write over memory not 835 * belonging to them. 836 */ 837 838 #ifndef howmany 839 #define howmany(x, y) (((x) + ((y) - 1)) / (y)) 840 #endif /* !howmany */ 841 842 #define SOCKD_FD_SIZE() \ 843 ((size_t)(howmany((sockscf.state.maxopenfiles + 1), NFDBITS) * sizeof(fd_mask))) 844 845 #ifdef FD_ZERO 846 #undef FD_ZERO 847 #endif /* FD_ZERO */ 848 849 #define FD_ZERO(p) \ 850 do { \ 851 memset((p), 0, SOCKD_FD_SIZE()); \ 852 } while (/* CONSTCOND */ 0) 853 854 #ifdef FD_CMP 855 #undef FD_CMP 856 #endif /* FD_CMP */ 857 858 #define FD_CMP(a, b) (memcmp((a), (b), SOCKD_FD_SIZE())) 859 860 #ifdef FD_COPY 861 #undef FD_COPY 862 #endif /* FD_COPY */ 863 864 #define FD_COPY(dst, src) \ 865 do { \ 866 memcpy((dst), (src), SOCKD_FD_SIZE()); \ 867 } while (/* CONSTCOND */ 0) 868 869 870 871 #define ERRNOISNOFILE(errno) \ 872 ((errno) == EMFILE || (errno) == ENFILE) 873 874 #define ERRNOISRST(errno) \ 875 ((errno) == ECONNREFUSED || (errno) == ECONNRESET) 876 877 #define ERRNOISPREVIOUSPACKET(errno) \ 878 ( ERRNOISRST(errno) \ 879 || ERRNOISNOROUTE(errno) /* Linux ... */ \ 880 || ERRNOISACCES(errno) /* Linux ... */ \ 881 || (errno) == EMSGSIZE /* Linux ... */ \ 882 || (errno) == ETIMEDOUT \ 883 ) 884 885 #define ERRNOISTMP(errno) \ 886 ( (errno) == EAGAIN \ 887 || (errno) == EWOULDBLOCK \ 888 || (errno) == EINTR \ 889 || (errno) == ENOBUFS \ 890 || (errno) == ENOMEM \ 891 || (errno) == ENOMSG) 892 893 #define ERRNOISACCES(errno) ((errno) == EPERM || (errno) == EACCES) 894 895 #define ERRNOISNOROUTE(errno) \ 896 ((errno) == ENETUNREACH || (errno) == EHOSTUNREACH || (errno) == ENETDOWN) 897 898 #define ERRNOISNETWORK(errno) (\ 899 ERRNOISNOROUTE(errno) \ 900 || ERRNOISRST(errno) \ 901 ) 902 903 #define PORTISRESERVED(port) \ 904 (ntohs((port)) != 0 && ntohs((port)) < IPPORT_RESERVED) 905 906 #define IPADDRISBOUND(addr) \ 907 (TOSA((addr))->sa_family == AF_UNSPEC ? \ 908 0 : (TOSA((addr))->sa_family == AF_INET ? \ 909 (TOIN((addr))->sin_addr.s_addr != htonl(INADDR_ANY)) \ 910 : (memcmp(TOIN6((addr))->sin6_addr.s6_addr, \ 911 &in6addr_any, \ 912 sizeof(in6addr_any)) != 0)) \ 913 ) 914 915 #define PORTISBOUND(addr) \ 916 (TOSA((addr))->sa_family == AF_UNSPEC ? \ 917 0 : (TOSA((addr))->sa_family == AF_INET ? \ 918 (ntohs(TOIN((addr))->sin_port) != 0) \ 919 : (ntohs(TOIN6((addr))->sin6_port)) != 0) \ 920 ) 921 922 #define ADDRISBOUND(addr) \ 923 (IPADDRISBOUND((addr)) && PORTISBOUND((addr))) 924 925 #define SOCKSHOSTISNOTBOUND(host) \ 926 ((host)->port == htons(0) || !SOCKSHOST_ADDRISBOUND(host)) 927 928 #define SOCKSHOSTISBOUND(host) (!(SOCKSHOSTISNOTBOUND((host)))) 929 930 #define SOCKSHOST_ADDRISBOUND(host) \ 931 ( ((host)->atype == SOCKS_ADDR_DOMAIN && *host->addr.domain != NUL) \ 932 || ((host)->atype == SOCKS_ADDR_IPV4 \ 933 && (host)->addr.ipv4.s_addr != htonl(INADDR_ANY)) \ 934 || ((host)->atype == SOCKS_ADDR_IPV6 \ 935 && memcmp(&(host)->addr.ipv6, &in6addr_any, sizeof(in6addr_any))) != 0) 936 937 #define RULEPORT_START(addr, protocol) ( \ 938 ((protocol) == SOCKS_TCP ? (addr)->port.tcp : (addr)->port.udp)) 939 940 #if HAVE_SOCKADDR_STORAGE_SS_LEN 941 942 #define SET_SOCKADDRLEN(ss, len) \ 943 do { \ 944 ((ss)->ss_len = (len)); \ 945 } while (/* CONSTCOND */ 0) 946 947 #else /* !HAVE_SOCKADDR_STORAGE_SS_LEN */ 948 949 #define SET_SOCKADDRLEN(ss, len) 950 951 #endif /* !HAVE_SOCKADDR_STORAGE_SS_LEN */ 952 953 #define SET_SOCKADDR(sa, family) \ 954 do { \ 955 ((sa)->ss_family = (family)); \ 956 SET_SOCKADDRLEN((sa), salen((family))); \ 957 } while (/* CONSTCOND */ 0) 958 959 #define SET_SOCKADDRPORT(sa, port) \ 960 do { \ 961 switch ((sa)->ss_family) { \ 962 case AF_INET: \ 963 (TOIN(sa))->sin_port = (port); \ 964 break; \ 965 \ 966 case AF_INET6: \ 967 (TOIN6(sa))->sin6_port = (port); \ 968 break; \ 969 \ 970 default: \ 971 SERRX((sa)->ss_family); \ 972 } \ 973 } while (/* CONSTCOND */ 0) 974 975 976 #define GET_SOCKADDRPORT(sa) \ 977 (((sa)->ss_family) == AF_INET ? \ 978 TOCIN(sa)->sin_port : TOCIN6(sa)->sin6_port) \ 979 980 #define SET_SOCKADDRADDR(sa, addr) \ 981 do { \ 982 switch ((sa)->ss_family) { \ 983 case AF_INET: \ 984 memcpy(&(TOIN(sa))->sin_addr, addr, sizeof(TOIN(sa))->sin_addr); \ 985 break; \ 986 \ 987 case AF_INET6: \ 988 memcpy(&(TOIN6(sa))->sin6_addr, addr, sizeof(TOIN6(sa))->sin6_addr); \ 989 break; \ 990 \ 991 default: \ 992 SERRX((sa)->ss_family); \ 993 } \ 994 } while (/* CONSTCOND */ 0) 995 996 997 #define GET_SOCKADDRADDR(sa) \ 998 (((sa)->ss_family) == AF_INET ? \ 999 ((const void *)&(TOCIN(sa)->sin_addr)) \ 1000 : ((const void *)&(TOCIN6(sa)->sin6_addr))) \ 1001 1002 1003 1004 #define ELEMENTS(array) (sizeof(array) / sizeof(array[0])) 1005 1006 #define OCTETIFY(a) ((a) &= 0xff) 1007 /* 1008 * Note that the argument will be truncated, not just the return value. 1009 */ 1010 1011 1012 /* 1013 * Stuff for messages between our processes. 1014 */ 1015 1016 /* padding for each message between mother/child, including separation. */ 1017 #define SENDMSG_PADBYTES (sizeof(long) * 64) /* just a guess. */ 1018 1019 1020 /* 1021 * macros to manipulate ancillary data depending on if we're on sysv or BSD. 1022 */ 1023 1024 /* 1025 * Modern CMSG alignment macros. Use them if the platform has them, 1026 * if not we get the default behavior. 1027 */ 1028 1029 #if HAVE_CMSGHDR 1030 1031 #if !HAVE_CMSG_LEN 1032 #define CMSG_LEN(len) (sizeof(struct cmsghdr) + (len)) 1033 #endif /* !HAVE_CMSG_LEN */ 1034 1035 #if !HAVE_CMSG_SPACE 1036 #define CMSG_SPACE(len) (sizeof(struct cmsghdr) + (len)) 1037 #endif /* !HAVE_CMSG_SPACE */ 1038 1039 #else /* HAVE_CMSGHDR */ 1040 1041 #if !HAVE_CMSG_LEN 1042 #define CMSG_LEN(len) (len) 1043 #endif /* !HAVE_CMSG_LEN */ 1044 1045 #if !HAVE_CMSG_SPACE 1046 #define CMSG_SPACE(len) (len) 1047 #endif /* !HAVE_CMSG_SPACE */ 1048 1049 #endif /* HAVE_CMSGHDR */ 1050 1051 /* 1052 * allocate memory for a control message of size "size". "name" is the 1053 * name of the allocated memory. 1054 */ 1055 #if HAVE_CMSGHDR 1056 1057 #define CMSG_AALLOC(name, size) \ 1058 union { \ 1059 char cmsgmem[CMSG_SPACE(size)]; \ 1060 struct cmsghdr align; \ 1061 } __CONCAT3(_, name, mem) = { { 0 } }; /* cleared to appease valgrind */ \ 1062 struct cmsghdr *name = (struct cmsghdr *)__CONCAT3(_, name, mem).cmsgmem; 1063 1064 #else /* !HAVE_CMSGHDR */ 1065 1066 #define CMSG_AALLOC(name, size) \ 1067 char name[(size)] = NUL; 1068 1069 #endif /* !HAVE_CMSGHDR */ 1070 1071 1072 /* 1073 * Returns the size of the previously allocated control message named 1074 * "name" 1075 */ 1076 #if HAVE_CMSGHDR 1077 #define CMSG_MEMSIZE(name) (sizeof(__CONCAT3(_, name, mem))) 1078 #else /* !HAVE_CMSGHDR */ 1079 #define CMSG_MEMSIZE(name) (sizeof((name))) 1080 #endif /* HAVE_CMSGHDR */ 1081 1082 /* 1083 * Verifies length of received control message. 1084 * 1085 * Final padding might not be present in received message, 1086 * expected length can be either value of CMSG_SPACE() or CMSG_LEN(). 1087 */ 1088 #define CMSG_RCPTLEN_ISOK(msg, datalen) \ 1089 ((datalen) == 0 ? ((size_t)(CMSG_TOTLEN(msg) == 0)) \ 1090 : ((size_t)CMSG_TOTLEN((msg)) == (size_t)(CMSG_SPACE((datalen))) \ 1091 || (size_t)CMSG_TOTLEN((msg)) == (size_t)(CMSG_LEN((datalen))))) 1092 1093 /* 1094 * Returns the control data member of "msg". 1095 */ 1096 #if HAVE_CMSGHDR 1097 /* 1098 * cast is necessary on AIX, due to buggy headers there? 1099 * needs additional testing on AIX, disable for now. 1100 */ 1101 #define CMSG_CONTROLDATA(msg) ((msg).msg_control) 1102 #else /* !HAVE_CMSGHDR */ 1103 #define CMSG_CONTROLDATA(msg) ((msg).msg_accrights) 1104 #endif /* HAVE_CMSGHDR */ 1105 1106 /* 1107 * add "object" to "data". "object" is the object to add to "data" at 1108 * offset "offset". 1109 */ 1110 #if HAVE_CMSGHDR 1111 #define CMSG_ADDOBJECT(object, data, offset) \ 1112 do \ 1113 memcpy(CMSG_DATA(data) + (offset), &(object), sizeof(object)); \ 1114 while (/* CONSTCOND */ 0) 1115 #else /* !HAVE_CMSGHDR */ 1116 #define CMSG_ADDOBJECT(object, data, offset) \ 1117 do \ 1118 memcpy(data + (offset), &(object), sizeof((object))); \ 1119 while (/* CONSTCOND */ 0) 1120 #endif /* !HAVE_CMSGHDR */ 1121 1122 /* 1123 * get a object from control data "data". 1124 * "object" is the object to fill with data gotten from "data" at offset 1125 * "offset". 1126 */ 1127 #if HAVE_CMSGHDR 1128 #define CMSG_GETOBJECT(object, data, offset) \ 1129 do \ 1130 memcpy(&(object), CMSG_DATA((data)) + (offset), sizeof((object))); \ 1131 while (/* CONSTCOND */ 0) 1132 #else /* !HAVE_CMSGHDR */ 1133 #define CMSG_GETOBJECT(object, data, offset) \ 1134 do \ 1135 memcpy(&(object), ((data) + (offset)), sizeof((object))); \ 1136 while (/* CONSTCOND */ 0) 1137 #endif /* !HAVE_CMSGHDR */ 1138 1139 /* 1140 * Sets up "object" for sending a control message of size "size". 1141 * "controlmem" is the memory the control message is stored in. 1142 * 1143 * CMSG_SPACE() rather than CMSG_LEN() apparently correct value 1144 * for msg_controllen. 1145 */ 1146 #if HAVE_CMSGHDR 1147 #define CMSG_SETHDR_SEND(object, controlmem, size) \ 1148 do { \ 1149 if (size == 0) { \ 1150 object.msg_control = NULL; \ 1151 object.msg_controllen = 0; \ 1152 } \ 1153 else { \ 1154 bzero(controlmem, sizeof(*controlmem)); \ 1155 \ 1156 controlmem->cmsg_level = SOL_SOCKET; \ 1157 controlmem->cmsg_type = SCM_RIGHTS; \ 1158 controlmem->cmsg_len = CMSG_LEN(size); \ 1159 \ 1160 object.msg_control = (caddr_t)controlmem; \ 1161 object.msg_controllen = (size) == 0 ? 0 : CMSG_SPACE((size)); \ 1162 } \ 1163 } while (/* CONSTCOND */ 0) 1164 #else /* !HAVE_CMSGHDR */ 1165 #define CMSG_SETHDR_SEND(object, controlmem, size) \ 1166 do { \ 1167 object.msg_accrights = (caddr_t)controlmem; \ 1168 object.msg_accrightslen = (size); \ 1169 } while (/* CONSTCOND */ 0) 1170 #endif /* !HAVE_CMSGHDR */ 1171 1172 /* 1173 * Sets up "object" for receiving a control message of size "size". 1174 * "controlmem" is the memory set aside for the control message. 1175 */ 1176 #if HAVE_CMSGHDR 1177 #define CMSG_SETHDR_RECV(object, controlmem, size) \ 1178 do { \ 1179 object.msg_control = (caddr_t)controlmem; \ 1180 object.msg_controllen = (size); \ 1181 } while (/* CONSTCOND */ 0) 1182 #else /* !HAVE_CMSGHDR */ 1183 #define CMSG_SETHDR_RECV(object, controlmem, size) \ 1184 do { \ 1185 object.msg_accrights = (caddr_t)controlmem; \ 1186 object.msg_accrightslen = (size); \ 1187 } while (/* CONSTCOND */ 0) 1188 #endif /* !HAVE_CMSGHDR */ 1189 1190 /* returns length of control data actually sent. */ 1191 #if HAVE_CMSGHDR 1192 #define CMSG_GETLEN(msg) ((msg).msg_controllen - CMSG_LEN(0)) 1193 #else 1194 #define CMSG_GETLEN(msg) ((msg).msg_accrightslen) 1195 #endif /* HAVE_CMSGHDR */ 1196 1197 #if HAVE_CMSGHDR 1198 #define CMSG_TOTLEN(msg) ((msg).msg_controllen) 1199 #else 1200 #define CMSG_TOTLEN(msg) ((msg).msg_accrightslen) 1201 #endif /* HAVE_CMSGHDR */ 1202 1203 1204 /* the size of a UDP header "packet" (no padding) */ 1205 #define HEADERSIZE_UDP(packet) ( \ 1206 sizeof((packet)->flag) + sizeof((packet)->frag) \ 1207 + sizeof((packet)->host.atype) + sizeof((packet)->host.port) \ 1208 + (ADDRESSIZE_V5(packet))) 1209 1210 1211 /* 1212 * returns the length of the current address field in socks packet "packet". 1213 * "packet" can be one of pointer to response_t, request_t or udpheader_t. 1214 */ 1215 #define ADDRESSIZE(packet) ( \ 1216 ((packet)->version == SOCKS_V4 ? \ 1217 (ADDRESSIZE_V4(packet)) : (ADDRESSIZE_V5(packet)))) 1218 1219 /* 1220 * version specifics 1221 */ 1222 #define ADDRESSIZE_V5(packet) ( \ 1223 (packet)->host.atype == SOCKS_ADDR_IPV4 ? \ 1224 sizeof((packet)->host.addr.ipv4) \ 1225 : (packet)->host.atype == (unsigned char)SOCKS_ADDR_IPV6 ? \ 1226 sizeof((packet)->host.addr.ipv6.ip) \ 1227 : (strlen((packet)->host.addr.domain) + 1)) 1228 1229 #define ADDRESSIZE_V4(packet) ( \ 1230 (packet)->atype == SOCKS_ADDR_IPV4 ? \ 1231 sizeof((packet)->addr.ipv4) : (strlen((packet)->addr.host) + 1)) 1232 1233 1234 /* 1235 * This is for Rgethostbyname() support for clients without access to 1236 * DNS. 1237 * FAKEIP_START is the first address in the range of "fake" IP addresses, 1238 * FAKEIP_END is the last. 1239 * There can thus be FAKEIP_END - FAKEIP_START number of fake IP addresses 1240 * supported per program. 1241 * 1242 * INADDR_NONE and INADDR_ANY may not be part of the range. 1243 */ 1244 #define FAKEIP_START 0x00000001 1245 #define FAKEIP_END 0x000000ff 1246 1247 #define PROXY_UPNP 3 1248 #define PROXY_UPNPs "UPNP" 1249 #define PROXY_BROADCASTs "broadcast" /* subset of upnp. */ 1250 #define PROXY_SOCKS_V4 4 1251 #define PROXY_SOCKS_V4s "socks_v4" 1252 #define PROXY_SOCKS_V4REPLY_VERSION 0 1253 #define PROXY_SOCKS_V5 5 1254 #define PROXY_SOCKS_V5s "socks_v5" 1255 #define PROXY_DIRECT 6 1256 #define PROXY_DIRECTs "direct" 1257 #define PROXY_HTTP_10 7 1258 #define PROXY_HTTP_10s "HTTP/1.0" 1259 #define PROXY_HTTP_11 8 1260 #define PROXY_HTTP_11s "HTTP/1.1" 1261 1262 /* sub negotiation. */ 1263 #define SOCKS_UNAMEVERSION 1 1264 #define SOCKS_GSSAPI_VERSION 1 1265 #define SOCKS_GSSAPI_AUTHENTICATION 1 1266 #define SOCKS_GSSAPI_ENCRYPTION 2 1267 #define SOCKS_GSSAPI_PACKET 3 1268 #define SOCKS_GSSAPI_CLEAR 0 1269 #define SOCKS_GSSAPI_INTEGRITY 1 1270 #define SOCKS_GSSAPI_CONFIDENTIALITY 2 1271 #define SOCKS_GSSAPI_PERMESSAGE 3 1272 1273 /* authentication METHOD values. */ 1274 #define AUTHMETHOD_NOTSET -1 1275 #define AUTHMETHOD_NOTSETs "notset" 1276 #define AUTHMETHOD_NONE 0 1277 #define AUTHMETHOD_NONEs "none" 1278 #define AUTHMETHOD_GSSAPI 1 1279 #define AUTHMETHOD_GSSAPIs "gssapi" 1280 #define AUTHMETHOD_UNAME 2 1281 #define AUTHMETHOD_UNAMEs "username" 1282 1283 /* X'03' to X'7F' IANA ASSIGNED */ 1284 1285 /* X'80' to X'FE' RESERVED FOR PRIVATE METHODS */ 1286 1287 #define AUTHMETHOD_NOACCEPT 255 1288 #define AUTHMETHOD_NOACCEPTs "<no acceptable method>" 1289 1290 /* non-standard methods. Must be > AUTHMETHOD_NOACCEPT. */ 1291 #define AUTHMETHOD_RFC931 (AUTHMETHOD_NOACCEPT + 1) 1292 #define AUTHMETHOD_RFC931s "rfc931" 1293 1294 #define AUTHMETHOD_PAM_ANY (AUTHMETHOD_RFC931 + 1) 1295 #define AUTHMETHOD_PAM_ANYs "pam.any" 1296 1297 #define AUTHMETHOD_PAM_ADDRESS (AUTHMETHOD_PAM_ANY + 1) 1298 #define AUTHMETHOD_PAM_ADDRESSs "pam.address" 1299 1300 #define AUTHMETHOD_PAM_USERNAME (AUTHMETHOD_PAM_ADDRESS + 1) 1301 #define AUTHMETHOD_PAM_USERNAMEs "pam.username" 1302 1303 #define AUTHMETHOD_BSDAUTH (AUTHMETHOD_PAM_USERNAME + 1) 1304 #define AUTHMETHOD_BSDAUTHs "bsdauth" 1305 1306 #define AUTHMETHOD_LDAPAUTH (AUTHMETHOD_BSDAUTH + 1) 1307 #define AUTHMETHOD_LDAPAUTHs "ldapauth" 1308 1309 #define AUTHMETHOD_MAX (AUTHMETHOD_LDAPAUTH) 1310 1311 #define MAXMETHODSTRING (MAX(sizeof(AUTHMETHOD_NONEs), \ 1312 MAX(sizeof(AUTHMETHOD_GSSAPIs), \ 1313 MAX(sizeof(AUTHMETHOD_UNAMEs), \ 1314 MAX(sizeof(AUTHMETHOD_RFC931s), \ 1315 MAX(sizeof(AUTHMETHOD_PAM_ANYs), \ 1316 MAX(sizeof(AUTHMETHOD_PAM_ADDRESSs), \ 1317 MAX(sizeof(AUTHMETHOD_PAM_USERNAMEs), \ 1318 MAX(sizeof(AUTHMETHOD_BSDAUTHs), \ 1319 sizeof(AUTHMETHOD_LDAPAUTHs)))))))))) 1320 1321 /* number of supported methods. */ 1322 #define METHODS_KNOWN ( 1 /* NONE */ \ 1323 + 1 /* GSSAPI */ \ 1324 + 1 /* UNAME */ \ 1325 + 1 /* RFC931 */ \ 1326 + 1 /* PAM */ \ 1327 + 1 /* BSDAUTH */ \ 1328 + 1) /* LDAPAUTH */ 1329 1330 #define MAXMETHODS (255) /* 1331 * max number of methods we can be offered, and 1332 * potentially support. 1333 */ 1334 1335 /* 1336 * Response commands/codes 1337 */ 1338 #define SOCKS_CONNECT 1 1339 #define SOCKS_CONNECTs "connect" 1340 #define SOCKS_BIND 2 1341 #define SOCKS_BINDs "bind" 1342 #define SOCKS_UDPASSOCIATE 3 1343 #define SOCKS_UDPASSOCIATEs "udpassociate" 1344 1345 /* pseudo commands */ 1346 1347 #define SOCKS_COMMANDEND 0xff 1348 1349 #define SOCKS_BINDREPLY (SOCKS_COMMANDEND + 1) 1350 #define SOCKS_BINDREPLYs "bindreply" 1351 1352 #define SOCKS_UDPREPLY (SOCKS_BINDREPLY + 1) 1353 #define SOCKS_UDPREPLYs "udpreply" 1354 1355 /* misc. stuff */ 1356 #define SOCKS_ACCEPT (SOCKS_UDPREPLY + 1) 1357 #define SOCKS_ACCEPTs "accept" 1358 1359 #define SOCKS_DISCONNECT (SOCKS_ACCEPT + 1) 1360 #define SOCKS_DISCONNECTs "disconnect" 1361 1362 #define SOCKS_BOUNCETO (SOCKS_DISCONNECT + 1) 1363 #define SOCKS_BOUNCETOs "bounce-to" 1364 1365 #define SOCKS_HOSTID (SOCKS_BOUNCETO + 1) 1366 #define SOCKS_HOSTIDs "hostid" 1367 1368 #define SOCKS_UNKNOWN (SOCKS_HOSTID + 1) 1369 #define SOCKS_UNKNOWNs "unknown" 1370 1371 1372 /* reply field values */ 1373 #define SOCKS_SUCCESS 0x00 1374 #define SOCKS_FAILURE 0x01 1375 #define SOCKS_NOTALLOWED 0x02 1376 #define SOCKS_NETUNREACH 0x03 1377 #define SOCKS_HOSTUNREACH 0x04 1378 #define SOCKS_CONNREFUSED 0x05 1379 #define SOCKS_TTLEXPIRED 0x06 1380 #define SOCKS_CMD_UNSUPP 0x07 1381 #define SOCKS_ADDR_UNSUPP 0x08 1382 1383 /* version 4 codes. */ 1384 #define SOCKSV4_SUCCESS 90 1385 #define SOCKSV4_FAIL 91 1386 #define SOCKSV4_NO_IDENTD 92 1387 #define SOCKSV4_BAD_ID 93 1388 1389 /* http stuff. */ 1390 #define HTTP_SUCCESS 200 1391 #define HTTP_NOTALLOWED 401 1392 #define HTTP_FORBIDDEN 403 1393 #define HTTP_PROXYAUTHREQUIRED 407 1394 #define HTTP_HOSTUNREACH 504 1395 #define HTTP_FAILURE 501 1396 #define SOCKD_HTTP_PORT 80 1397 1398 /* upnp stuff. */ 1399 #define UPNP_DISCOVERYTIME_MS (1000) 1400 #define UPNP_IP_TTL (2) 1401 #define DEFAULT_SSDP_BROADCAST_IPV4ADDR "239.255.255.250" 1402 #define DEFAULT_SSDP_PORT (1900) 1403 1404 /* return codes from UPNP_GetValidIGD(). */ 1405 #define UPNP_NO_IGD (0) 1406 #define UPNP_CONNECTED_IGD (1) 1407 #define UPNP_DISCONNECTED_IGD (2) 1408 #define UPNP_UNKNOWN_DEVICE (3) 1409 1410 #define UPNP_SUCCESS (1) 1411 #define UPNP_FAILURE (2) 1412 1413 /* flag _bits_ */ 1414 #define SOCKS_INTERFACEREQUEST 0x01 1415 #define SOCKS_USECLIENTPORT 0x04 1416 1417 /* subcommands */ 1418 #define SOCKS_INTERFACEDATA 0x01 1419 1420 #define SOCKS_RECV 0 1421 #define SOCKS_SEND 1 1422 1423 /* offsets into authentication packet */ 1424 #define AUTH_VERSION (0) /* version of method packet. */ 1425 1426 /* request */ 1427 #define AUTH_NMETHODS (1) /* offset of number of methods offered. */ 1428 #define AUTH_FIRSTMETHOD (2) /* offset of first method offered. */ 1429 1430 /* reply */ 1431 #define AUTH_SELECTEDMETHOD (1) /* offset for selected method in response. */ 1432 1433 /* offsets into username/password negotiation packet */ 1434 #define UNAME_VERSION (0) 1435 #define UNAME_STATUS (1) 1436 1437 1438 /* uname status values. */ 1439 #define UNAME_STATUS_ISOK (0) 1440 #define UNAME_STATUS_ISNOK (1) 1441 1442 /* offsets into gssapi negotiation packet */ 1443 #define GSSAPI_VERSION 0 1444 #define GSSAPI_STATUS 1 1445 #define GSSAPI_TOKEN_LENGTH 2 1446 #define GSSAPI_TOKEN 4 1447 1448 1449 #define GSSAPI_CLEAR 0 1450 #define GSSAPI_INTEGRITY 1 1451 #define GSSAPI_CONFIDENTIALITY 2 1452 1453 #define GSS_REQ_INT 0 1454 #define GSS_REQ_CONF 1 1455 1456 #define SOCKS_IPV6_ALEN 16 1457 #define IPV6_NETMASKBITS (128) 1458 #define IPV4_NETMASKBITS (32) 1459 #define IPV4_FULLNETMASK (0xffffffff) 1460 1461 #define IP6_ELEMENTS(ip6) \ 1462 (ip6)->s6_addr[0], \ 1463 (ip6)->s6_addr[1], \ 1464 (ip6)->s6_addr[2], \ 1465 (ip6)->s6_addr[3], \ 1466 (ip6)->s6_addr[4], \ 1467 (ip6)->s6_addr[5], \ 1468 (ip6)->s6_addr[6], \ 1469 (ip6)->s6_addr[7], \ 1470 (ip6)->s6_addr[8], \ 1471 (ip6)->s6_addr[9], \ 1472 (ip6)->s6_addr[10], \ 1473 (ip6)->s6_addr[11], \ 1474 (ip6)->s6_addr[12], \ 1475 (ip6)->s6_addr[13], \ 1476 (ip6)->s6_addr[14], \ 1477 (ip6)->s6_addr[15] 1478 1479 #define IP6_FMTSTR "%02x%02x:%02x%02x:%02x%02x:%02x%02x"\ 1480 "%02x%02x:%02x%02x:%02x%02x:%02x%02x" 1481 1482 #define BINDEXTENSION_IPADDR (0xffffffff) 1483 1484 1485 1486 /* 1487 * hostid related defines 1488 */ 1489 1490 /* socket option hostid types */ 1491 #define SOCKS_HOSTID_TYPE_NONE 0 1492 #define SOCKS_HOSTID_TYPE_TCP_IPA 1 1493 1494 #if SOCKS_HOSTID_TYPE == SOCKS_HOSTID_TYPE_NONE 1495 #define HAVE_SOCKS_HOSTID (0) 1496 #else 1497 #define HAVE_SOCKS_HOSTID (1) 1498 #endif 1499 1500 /* supported commands/command strings for parsing */ 1501 #define SOCKS_HOSTID_NONE 0 1502 #define SOCKS_HOSTID_NONE_SYMNAME "none" 1503 #define SOCKS_HOSTID_PASS 1 1504 #define SOCKS_HOSTID_PASS_SYMNAME "pass" 1505 #define SOCKS_HOSTID_ADDCLIENT 2 1506 #define SOCKS_HOSTID_ADDCLIENT_SYMNAME "add-client" 1507 #define SOCKS_HOSTID_SETCLIENT 3 1508 #define SOCKS_HOSTID_SETCLIENT_SYMNAME "set-client" 1509 1510 typedef enum { NONESETIF = 0, INTERNALIF, EXTERNALIF } interfaceside_t; 1511 1512 enum operator_t { none = 0, eq, neq, ge, le, gt, lt, range }; 1513 typedef enum { dontcare, istrue, isfalse } value_t; 1514 typedef enum { username, udpreplies, tcpreplies, replies } methodinfo_t; 1515 typedef enum { softlimit, hardlimit } limittype_t; 1516 typedef enum { type_global, type_rule, type_route } opttype_t; 1517 1518 1519 #define SOCKS_ADDR_NOTSET (0) 1520 #define SOCKS_ADDR_IPV4 (1) 1521 #define SOCKS_ADDR_IFNAME (2) 1522 #define SOCKS_ADDR_DOMAIN (3) 1523 #define SOCKS_ADDR_IPV6 (4) 1524 #define SOCKS_ADDR_URL (5) 1525 #define SOCKS_ADDR_IPVANY (6) /* for 0/0 address matching ipv4 and ipv6. */ 1526 1527 typedef enum { object_none = 0, /* no object set. */ 1528 object_sockaddr, 1529 object_sockshost, 1530 object_crule, 1531 object_hrule, 1532 object_srule, 1533 object_route, 1534 object_monitor } objecttype_t; 1535 1536 1537 #define MAXLOGLEVELLEN (sizeof("warning")) 1538 typedef struct { 1539 const char name[MAXLOGLEVELLEN]; 1540 const int value; 1541 } loglevel_t; 1542 1543 1544 typedef struct { 1545 /* 1546 * if we mark a route/proxy server as bad, how many seconds to wait 1547 * until we expire the badmarking so it will be tried again for new 1548 * connections. A value of zero means never. 1549 */ 1550 time_t badexpire; 1551 1552 /* 1553 * how many times a route can fail before being marked as bad. 1554 * A value of zero means it will never be marked as bad. 1555 */ 1556 size_t maxfail; 1557 } routeoptions_t; 1558 1559 typedef struct { 1560 int type; /* type of logging (where to). */ 1561 1562 char **fnamev; /* name of file, if logging to file. */ 1563 unsigned char *createdv; /* did we create this logfile ourselves? */ 1564 int *filenov; /* if logging is to file, the file descriptor. */ 1565 size_t filenoc; /* number of files. */ 1566 1567 int facility; /* if logging to syslog, this is the facility. */ 1568 char facilityname[MAXFACILITYNAMELEN]; /* facilityname. */ 1569 } logtype_t; 1570 1571 typedef struct linkedname_t { 1572 char *name; 1573 struct linkedname_t *next; /* next name in list. */ 1574 } linkedname_t; 1575 1576 #if HAVE_LDAP 1577 1578 /* 1579 * This struct contains variables used for LDAP authorization. 1580 */ 1581 1582 typedef struct { 1583 linkedname_t *ldapurl; /* name of ldap urls. */ 1584 linkedname_t *ldapbasedn; /* name of ldap basedns. */ 1585 linkedname_t *ldapserver; /* name of predefined ldap servers. */ 1586 1587 char attribute[MAXNAMELEN]; 1588 char attribute_AD[MAXNAMELEN]; 1589 int auto_off; 1590 int certcheck; 1591 char certfile[MAXNAMELEN]; 1592 char certpath[MAXNAMELEN]; 1593 int debug; 1594 char domain[MAXNAMELEN]; 1595 char filter[MAXNAMELEN]; 1596 char filter_AD[MAXNAMELEN]; 1597 int keeprealm; 1598 char keytab[MAXNAMELEN]; 1599 int mdepth; 1600 int port; 1601 int portssl; 1602 int ssl; 1603 } ldapauthorisation_t; 1604 1605 /* 1606 * This struct contains variables used for LDAP authentication. 1607 */ 1608 1609 typedef struct { 1610 linkedname_t *ldapurl; /* name of ldap urls. */ 1611 linkedname_t *ldapbasedn; /* name of ldap basedns. */ 1612 linkedname_t *ldapserver; /* name of predefined ldap servers.*/ 1613 1614 int auto_off; 1615 int certcheck; 1616 char certfile[MAXNAMELEN]; 1617 char certpath[MAXNAMELEN]; 1618 int debug; 1619 char domain[MAXNAMELEN]; 1620 char filter[MAXNAMELEN]; 1621 char filter_AD[MAXNAMELEN]; 1622 char keytab[MAXNAMELEN]; 1623 int port; 1624 int portssl; 1625 int ssl; 1626 } ldapauthentication_t; 1627 1628 #endif /* HAVE_LDAP */ 1629 1630 1631 /* extensions supported by us. */ 1632 typedef struct { 1633 unsigned char bind; /* use bind extension? */ 1634 } extension_t; 1635 1636 typedef enum { TIMEOUT_NOTSET = 0, 1637 TIMEOUT_NEGOTIATE, 1638 TIMEOUT_CONNECT, 1639 TIMEOUT_IO, 1640 TIMEOUT_TCP_FIN_WAIT, 1641 TIMEOUT_NETWORKTEST 1642 } timeouttype_t; 1643 1644 typedef struct { 1645 /* 1646 * type should match the struct timeval.tv_sec used by select(2). 1647 * POSIX says it's time_t. 1648 */ 1649 1650 time_t connect; /* how long to wait before giving up connect(2). */ 1651 #if !SOCKS_CLIENT 1652 time_t negotiate; /* how long negotiation can last. */ 1653 time_t tcpio; /* how long session can last without i/o. */ 1654 time_t udpio; /* how long session can last without i/o. */ 1655 1656 time_t tcp_fin_wait; /* how long to wait after one end closes. */ 1657 #endif /* !SOCKS_CLIENT */ 1658 } timeout_t; 1659 1660 /* method rfc931 */ 1661 typedef struct { 1662 unsigned char name[MAXNAMELEN]; 1663 } authmethod_rfc931_t; 1664 1665 /* method pam. */ 1666 typedef struct { 1667 char servicename[MAXNAMELEN]; /* servicename to use with pam. */ 1668 unsigned char name[MAXNAMELEN]; 1669 unsigned char password[MAXPWLEN]; 1670 } authmethod_pam_t; 1671 1672 /* method bsdauth. */ 1673 typedef struct { 1674 char style[MAXNAMELEN]; /* style to use. */ 1675 unsigned char name[MAXNAMELEN]; 1676 unsigned char password[MAXPWLEN]; 1677 } authmethod_bsd_t; 1678 1679 #if HAVE_LDAP 1680 1681 /* method ldapauth. */ 1682 typedef struct { 1683 char name[MAXNAMELEN]; 1684 char password[MAXPWLEN]; 1685 ldapauthentication_t ldapauthentication; 1686 } authmethod_ldap_t; 1687 1688 #endif /* HAVE_LDAP */ 1689 1690 /* method username */ 1691 typedef struct { 1692 unsigned char version; 1693 unsigned char name[MAXNAMELEN]; 1694 unsigned char password[MAXPWLEN]; 1695 } authmethod_uname_t; 1696 1697 #if HAVE_GSSAPI 1698 typedef struct { 1699 unsigned char nec; 1700 unsigned char clear; 1701 unsigned char integrity; 1702 unsigned char confidentiality; 1703 unsigned char permessage; 1704 } gssapi_enc_t; 1705 1706 #ifndef BUFSIZ 1707 #define BUFSIZ 1024 1708 #endif /* !BUFSIZ */ 1709 typedef struct { 1710 int read; 1711 int rpos; 1712 int wpos; 1713 int isbuffered; 1714 unsigned char rbuffer[GSSAPI_HLEN + MAXGSSAPITOKENLEN]; 1715 unsigned char wbuffer[BUFSIZ]; 1716 } gssapi_buf_t; 1717 1718 typedef struct { 1719 int wrap; /* gssapi-wrapped, or clear? */ 1720 gss_ctx_id_t id; /* gssapi context id. */ 1721 int protection; /* selected protection mechanism. */ 1722 1723 OM_uint32 maxgssdata; /* max length of gss data pre-encoding. */ 1724 size_t gssoverhead; /* 1725 * overhead in bytes of gssapi given the 1726 * current mechanism/context/etc. 1727 * Don't know what the practical max 1728 * actually is, so this contains the 1729 * max overhead experienced so far. 1730 */ 1731 } gssapi_state_t; 1732 1733 /* method gssapi */ 1734 typedef struct { 1735 char servicename[MAXNAMELEN]; 1736 char keytab[MAXNAMELEN]; 1737 unsigned char name[MAXNAMELEN]; 1738 #if HAVE_PAC 1739 unsigned char sids[MAXSIDSLEN]; 1740 #endif /* HAVE_PAC */ 1741 gssapi_enc_t encryption; /* encryption details */ 1742 gssapi_state_t state; /* gssapi state details */ 1743 } authmethod_gssapi_t; 1744 1745 #endif /* HAVE_GSSAPI */ 1746 1747 1748 /* this must be big enough to hold a complete method request. */ 1749 typedef struct { 1750 int method; /* method in use. */ 1751 1752 /* 1753 * Methods authenticated at some stage of the process. 1754 */ 1755 int methodv[METHODS_KNOWN]; 1756 size_t methodc; /* number of methods authenticated. */ 1757 1758 /* 1759 * Methods that failed authentication at some stage of the process. 1760 */ 1761 int badmethodv[METHODS_KNOWN]; 1762 size_t badmethodc; /* number of methods that failed. */ 1763 1764 union { 1765 authmethod_uname_t uname; 1766 1767 #if HAVE_GSSAPI 1768 authmethod_gssapi_t gssapi; 1769 #endif /* HAVE_GSSAPI */ 1770 #if HAVE_LIBWRAP 1771 authmethod_rfc931_t rfc931; 1772 #endif /* HAVE_LIBWRAP */ 1773 #if HAVE_PAM 1774 authmethod_pam_t pam; 1775 #endif /* HAVE_PAM */ 1776 #if HAVE_BSDAUTH 1777 authmethod_bsd_t bsd; 1778 #endif /* HAVE_BSDAUTH */ 1779 1780 #if HAVE_LDAP 1781 1782 authmethod_ldap_t ldap; 1783 1784 #endif /* HAVE_LDAP */ 1785 1786 } mdata; 1787 } authmethod_t; 1788 1789 typedef union { 1790 int int_val; 1791 struct linger linger_val; 1792 struct timeval timeval_val; 1793 struct in_addr in_addr_val; 1794 unsigned char uchar_val; 1795 struct sockaddr_storage sockaddr_val; 1796 struct ipoption ipoption_val; 1797 1798 #if HAVE_TCP_IPA 1799 struct tcp_ipa option28_val; 1800 #endif /* HAVE_TCP_IPA */ 1801 } socketoptvalue_t; 1802 1803 /* 1804 * make sure to keep this in sync with the size calculation in 1805 * setusersockoptions(). 1806 */ 1807 typedef enum { int_val = 1, linger_val, timeval_val, in_addr_val, uchar_val, 1808 sockaddr_val, ipoption_val, option28_val } socketoptvalue_type_t; 1809 1810 #if HAVE_TCP_IPA 1811 #define SOCKETOPTVALUETYPE2SIZE(type) \ 1812 ((type) == int_val ? sizeof(int) : \ 1813 (type) == linger_val ? sizeof(struct linger) : \ 1814 (type) == timeval_val ? sizeof(struct timeval) : \ 1815 (type) == in_addr_val ? sizeof(struct in_addr) : \ 1816 (type) == uchar_val ? sizeof(u_char) : \ 1817 (type) == sockaddr_val ? sizeof(struct sockaddr_storage) : \ 1818 (type) == ipoption_val ? sizeof(struct ipoption) : \ 1819 (type) == option28_val ? sizeof(struct tcp_ipa) : \ 1820 0) 1821 #else /* !HAVE_TCP_IPA */ 1822 1823 #define SOCKETOPTVALUETYPE2SIZE(type) \ 1824 ((type) == int_val ? sizeof(int) : \ 1825 (type) == linger_val ? sizeof(struct linger) : \ 1826 (type) == timeval_val ? sizeof(struct timeval) : \ 1827 (type) == in_addr_val ? sizeof(struct in_addr) : \ 1828 (type) == uchar_val ? sizeof(u_char) : \ 1829 (type) == sockaddr_val ? sizeof(struct sockaddr_storage) : \ 1830 (type) == ipoption_val ? sizeof(struct ipoption) : \ 1831 0) 1832 #endif /* !HAVE_TCP_IPA */ 1833 1834 #define SOCKETOPT_PRE (0x1) 1835 #define SOCKETOPT_POST (0x2) 1836 #define SOCKETOPT_ANYTIME (0x4) 1837 #define SOCKETOPT_ALL (SOCKETOPT_PRE | SOCKETOPT_POST | SOCKETOPT_ANYTIME) 1838 1839 typedef enum { preonly = 1, anytime, postonly, invalid } sockopt_calltype_t; 1840 typedef struct { 1841 size_t optid; /* option identifier */ 1842 socketoptvalue_type_t opttype; /* socket option argument type */ 1843 int value; /* value of SO_foo define */ 1844 int level; /* protocol level option applies to */ 1845 1846 unsigned char ipv4_on; /* settable for ipv4? */ 1847 unsigned char ipv6_on; /* settable for ipv6? */ 1848 1849 /* 1850 * XXX currently assumed that getsockopt() only called for options 1851 * where shift/mask is set 1852 */ 1853 sockopt_calltype_t calltype; /* when option can be set. */ 1854 unsigned int shift; /* number of bits to shift argument value. */ 1855 unsigned int mask; /* if set, mask specifying valid values. */ 1856 unsigned char dodup; /* whether option should be duplicated */ 1857 unsigned char needpriv; /* whether privileges are required */ 1858 char name[SOCKOPTNAME_MAXLEN]; /* optionname as string. */ 1859 } sockopt_t; 1860 1861 typedef struct { 1862 size_t optid; /* sockopt_t id symbol is valid for */ 1863 socketoptvalue_t symval; /* value of symbolic constant */ 1864 char *name; /* textual representation of constant value */ 1865 } sockoptvalsym_t; 1866 1867 typedef struct { 1868 const sockopt_t *info; /* NULL if unknown option. */ 1869 int level; /* 1870 * socket level to set option at. 1871 * Not necessarily the same as 1872 * info->level as we allow the user 1873 * to specify e.g. "tcp" instead 1874 * of level sol_socket, indicating 1875 * the option should only be set 1876 * for tcp sockets. The value 1877 * in "info" is the value we need 1878 * use when setting the option. 1879 */ 1880 1881 int optname; /* numeric of option to set. */ 1882 socketoptvalue_t optval; /* value set. */ 1883 socketoptvalue_type_t opttype; /* socket option argument type. */ 1884 1885 unsigned char isinternalside; /* option for the internal side? */ 1886 } socketoption_t; 1887 1888 1889 union socksaddr_t { 1890 char domain[MAXHOSTNAMELEN]; 1891 char urlname[MAXURLLEN]; 1892 char ifname[MAXIFNAMELEN]; 1893 struct in_addr ipv4; 1894 struct { 1895 struct in6_addr ip; 1896 uint32_t scopeid; 1897 } ipv6; 1898 }; 1899 1900 typedef struct sockshost_t { 1901 unsigned char atype; 1902 union socksaddr_t addr; 1903 in_port_t port; 1904 } sockshost_t; 1905 1906 typedef struct { 1907 unsigned char httpconnect; /* session is the result of a http connect. */ 1908 } requestflags_t; 1909 1910 typedef struct request_t { 1911 authmethod_t *auth; /* pointer to level above. */ 1912 unsigned char command; 1913 unsigned char flag; 1914 sockshost_t host; 1915 int protocol; 1916 unsigned char version; 1917 1918 requestflags_t flags; 1919 } request_t; 1920 1921 1922 typedef struct { 1923 unsigned char version; 1924 1925 union { 1926 unsigned char socks; 1927 unsigned char upnp; 1928 unsigned short http; 1929 } reply; 1930 1931 unsigned char flag; 1932 sockshost_t host; 1933 authmethod_t *auth; /* pointer to level above. */ 1934 } response_t; 1935 1936 /* encapsulation for UDP packets. */ 1937 typedef struct { 1938 unsigned char flag[2]; 1939 unsigned char frag; 1940 sockshost_t host; 1941 } udpheader_t; 1942 1943 typedef struct { 1944 unsigned char tcp; 1945 unsigned char udp; 1946 } protocol_t; 1947 1948 1949 typedef struct { 1950 unsigned char bind; 1951 unsigned char connect; 1952 unsigned char udpassociate; 1953 1954 /* not real commands as per standard, but they have their use. */ 1955 unsigned char bindreply; /* reply to bind command. */ 1956 unsigned char udpreply; /* reply to UDP packet. */ 1957 } command_t; 1958 1959 1960 typedef struct { 1961 unsigned char direct; 1962 unsigned char socks_v4; 1963 unsigned char socks_v5; 1964 unsigned char http; 1965 unsigned char upnp; 1966 } proxyprotocol_t ; 1967 1968 /* values in parentheses designate "don't care" values when searching. */ 1969 typedef struct { 1970 int acceptpending; /* a accept pending? (-1) */ 1971 authmethod_t auth; /* authentication in use. */ 1972 int command; /* command (-1) */ 1973 int err; /* if request failed, errno. */ 1974 #if HAVE_GSSAPI 1975 int gssimportneeded; 1976 gss_buffer_desc gssapistate; /* if gssimportneeded, data for it. */ 1977 unsigned char gssapistatemem[MAX_GSS_STATE]; 1978 #endif /* HAVE_GSSAPI */ 1979 int inprogress; /* operation in progress? (-1) */ 1980 unsigned char issyscall; /* started out as a real system call*/ 1981 protocol_t protocol; /* protocol in use. */ 1982 unsigned char udpconnect; /* connected UDP socket? */ 1983 int syscalldepth; 1984 int version; /* version (-1) */ 1985 } socksstate_t; 1986 1987 typedef struct ruleaddr_t { 1988 unsigned char atype; 1989 union { 1990 char domain[MAXHOSTNAMELEN]; 1991 1992 char ifname[MAXIFNAMELEN]; 1993 1994 struct { 1995 struct in_addr ip; 1996 struct in_addr mask; 1997 } ipv4; 1998 1999 struct { 2000 struct in6_addr ip; 2001 unsigned int maskbits; /* host order. */ 2002 uint32_t scopeid; /* host order. */ 2003 } ipv6; 2004 2005 struct { 2006 /* 2007 * both should always be zero as this is only meaningful for 2008 * a rule that should match all and any kind of ipaddress. 2009 */ 2010 struct in_addr ip; 2011 struct in_addr mask; 2012 } ipvany; 2013 2014 } addr; 2015 2016 struct { 2017 in_port_t tcp; /* TCP portstart or field to operator on. */ 2018 in_port_t udp; /* UDP portstart or field to operator on. */ 2019 } port; 2020 in_port_t portend; /* only used if operator is range. */ 2021 enum operator_t operator; /* operator to compare ports via. */ 2022 } ruleaddr_t; 2023 2024 #ifndef MINIUPNPC_URL_MAXSIZE 2025 #define MINIUPNPC_URL_MAXSIZE (128) 2026 #endif 2027 typedef union { 2028 struct { 2029 char controlurl[MINIUPNPC_URL_MAXSIZE]; 2030 char servicetype[MINIUPNPC_URL_MAXSIZE]; 2031 } upnp; 2032 } proxystate_t; 2033 2034 typedef struct { 2035 command_t command; 2036 extension_t extension; 2037 protocol_t protocol; 2038 2039 int cmethodv[METHODS_KNOWN]; /* clientmethods to offer. */ 2040 size_t cmethodc; /* number of methods to offer. */ 2041 int smethodv[METHODS_KNOWN]; /* socksmethods to offer. */ 2042 size_t smethodc; /* number of methods to offer. */ 2043 2044 proxyprotocol_t proxyprotocol; 2045 2046 #if HAVE_PAM 2047 char pamservicename[MAXNAMELEN]; 2048 #endif /* HAVE_PAM */ 2049 2050 #if HAVE_BSDAUTH 2051 char bsdauthstylename[MAXNAMELEN]; 2052 #endif /* HAVE_BSDAUTH */ 2053 2054 #if HAVE_GSSAPI 2055 char gssapiservicename[MAXNAMELEN]; 2056 char gssapikeytab[MAXNAMELEN]; 2057 gssapi_enc_t gssapiencryption; /* encryption status. */ 2058 #endif /* HAVE_GSSAPI */ 2059 2060 #if HAVE_LDAP 2061 /* 2062 * new ldap server details. Used for checking if an already 2063 * authenticated user is member of the appropriate LDAP group. I.e., 2064 * authorization rather than authentication. 2065 */ 2066 ldapauthorisation_t ldapauthorisation; 2067 2068 /* 2069 * new ldap auth server details. Used for performing LDAP-based 2070 * authentication of a new client (similar to username auth, 2071 * gssapi auth, etc.). Is independent of the ldap-object above that 2072 * is only used for authorization of an already authenticated user. 2073 */ 2074 ldapauthentication_t ldapauthentication; 2075 #endif 2076 2077 #if HAVE_LIBMINIUPNP 2078 proxystate_t data; 2079 #endif /* HAVE_LIBMINIUPNP */ 2080 } serverstate_t; 2081 2082 typedef struct { 2083 sockshost_t addr; 2084 serverstate_t state; 2085 } gateway_t; 2086 2087 2088 typedef struct { 2089 unsigned char version; 2090 /* 2091 * Negotiated version. Each request and 2092 * response will also contain a version number, that 2093 * is the version number given for that particular 2094 * packet and should be checked to make sure it is 2095 * the same as the negotiated version. 2096 */ 2097 request_t req; 2098 response_t res; 2099 gateway_t gw; 2100 socksstate_t state; 2101 } socks_t; 2102 2103 enum portcmp { e_lt = 1, e_gt, e_eq, e_neq, e_le, e_ge, e_nil }; 2104 2105 2106 2107 /* 2108 * for use in generic functions that take either reply or request 2109 * packets, include a field indicating what it is. 2110 */ 2111 #define SOCKS_REQUEST 0x1 2112 #define SOCKS_RESPONSE 0x2 2113 2114 /* 2115 * This object is either used for straightforward buffering, or 2116 * in the case the data is gssapi-encapsulated, to handle gssapi-data. 2117 * In the case of simple, non-gssapi, buffering, 2118 * no further explanation is given; the len field simply holds 2119 * the number of bytes currently buffered. 2120 * 2121 * Next we describe how it is used in the case of gssapi. 2122 * 2123 * In the case of gssapi, the buffer is divided into two parts, 2124 * the first part holding not-encoded data, and the latter part 2125 * holding encoded data. 2126 * 2127 * The operation when reading is as follows: 2128 * 1) Read into buf as much data as is needed to be able to 2129 * decode the data (in the case of gssapi, the whole token). 2130 * While doing this, we keep incrementing "enclen", to indicate 2131 * how much encoded data has been stored in the buffer. "len" 2132 * is not touch during this. 2133 * 2134 * 2) When 1) has completed, we replace the data in buf with 2135 * the decoded version of data in "buf", reset "enclen", and 2136 * set "len" to indicate how much decoded data is stored in the 2137 * buffer. 2138 * 2139 * 3) On subsequent read operations on the socket corresponding to 2140 * the data (s), return data from buf instead of reading it from 2141 * the socket. 2142 * 2143 * 4) When all data in buf has been returned, clear the iobuffer. 2144 * 2145 * The operation when writing is more complicated, because 2146 * we can get multiple write requests that we fail to send down 2147 * to the socket buffer, which in sum may be bigger than the 2148 * the iobuffer set aside to hold buffered unwritten data. 2149 * 2150 * The only way to prevent that situation from occurring is to 2151 * put a cap on how much we read, and never read more data than 2152 * we can store in our write-buffer, encoded. 2153 * We can use gss_wrap_size_limit() in combination with the amount 2154 * of data free in the buffer to find out the max amount of data to 2155 * read, and read no more than that in the tcp case. 2156 * 2157 * The operation for writing thus becomes: 2158 * 1) Encode the data received and write it to the socket. 2159 * 2160 * 2) If we fail to write all the data, and it is a tcp socket, 2161 * store the remaining data in the iobuffer, setting encodedlen 2162 * to the size of data remaining, and used to zero. 2163 * If it's a udp socket, there is not much to do, so return the 2164 * error. 2165 * 2166 * 3) On subsequent write operations on the socket, try to write the 2167 * data we had previously buffered. Then continue with 1). 2168 * 2169 $ 4) When all data has been written, clear the iobuffer. 2170 * 2171 */ 2172 2173 typedef enum { READ_BUF = 0 /* MUST BE 0 or 1 */, 2174 WRITE_BUF = 1 /* MUST BE 0 or 1 */ } whichbuf_t; 2175 2176 typedef struct { 2177 unsigned char allocated; 2178 int s; 2179 2180 #if HAVE_GSSAPI 2181 # if (SOCKD_BUFSIZE) < (2 * (MAXGSSAPITOKENLEN + GSSAPI_HLEN)) 2182 # error "SOCKD_BUFSIZE too small." 2183 # endif 2184 #endif /* HAVE_GSSAPI */ 2185 2186 char buf[2][SOCKD_BUFSIZE]; 2187 2188 struct { 2189 size_t len; /* length of decoded/plaintext data in buffer */ 2190 size_t enclen; /* length of encoded data in buffer. */ 2191 2192 int mode; /* buffering mode. Default is no buffering. */ 2193 ssize_t size; /* 2194 * size of buffer to use. Can not be larger than 2195 * SOCKD_BUFSIZE. Default is SOCKD_BUFSIZE. 2196 */ 2197 2198 #if SOCKS_CLIENT 2199 size_t readalready;/* 2200 * # of bytes we have already read from socket and 2201 * should ignore. 2202 */ 2203 #endif /* SOCKS_CLIENT */ 2204 } info[2]; 2205 2206 int stype; /* socket type; tcp or udp */ 2207 } iobuffer_t; 2208 2209 typedef struct route_t { 2210 int number; /* route number. */ 2211 2212 struct { 2213 unsigned char autoadded;/* autoadded route? */ 2214 size_t failed; /* route is bad? How many times it has failed. */ 2215 time_t badtime; /* if route is bad, time last marked as such. */ 2216 } state; 2217 2218 socketoption_t *socketoptionv; 2219 size_t socketoptionc; 2220 2221 ruleaddr_t src; 2222 ruleaddr_t dst; 2223 gateway_t gw; 2224 2225 ruleaddr_t rdr_from; 2226 2227 struct route_t *next; /* next route in list. */ 2228 } route_t; 2229 2230 typedef struct { 2231 unsigned char allocated; /* allocated? */ 2232 int control; /* control connection to server. */ 2233 socksstate_t state; /* state of this connection. */ 2234 2235 struct sockaddr_storage local; /* local address of control connection. */ 2236 /* XXX does not look to be case for udp. */ 2237 2238 struct sockaddr_storage server; /* remote address of control connection. */ 2239 struct sockaddr_storage remote; /* address server is using on our behalf. */ 2240 struct sockaddr_storage reply; /* 2241 * address to expect reply from, if not 2242 * same as control. 2243 */ 2244 2245 union { 2246 sockshost_t accepted; /* address server accepted for us. */ 2247 sockshost_t connected; /* address server connected to for us. */ 2248 } forus; 2249 2250 route_t *route; 2251 } socksfd_t; 2252 2253 /* 2254 * getaddrinfo(3) returns separate entries for udp and tcp, even when 2255 * everything else is the same. That means we effectively only get half 2256 * MAX_ADDRINFO_NEXT unique ipaddresses at most. We used 5 when we were 2257 * using the gethostby*(3) api, so double for getaddrinfo(3). 2258 * Might think about filtering out otherwise duplicate tcp/udp entries to 2259 * save memory. Would make the cache less general though. 2260 * 2261 * An additional thing to consider is that there is no way to specify in 2262 * the getaddrinfo(3)-api that we want ipv4-mapped ipv6 addresses 2263 * returned too, when we set ai_family to AF_INET in hints. The only way 2264 * to getr the ipv4-mapped addresses returned to is to set ai_family to 2265 * zero, but then we get the regular ipv6-addresses also. Since there 2266 * are cases when we want the ipv4-mapped addresses returned also, we 2267 * need to make the size set here able to accomodate that too. 2268 */ 2269 #define MAX_ADDRINFO_NEXT (10) 2270 2271 typedef enum { id_name = 1, id_addr } hostent_id_t; 2272 2273 typedef struct { 2274 unsigned allocated:1; /* entry allocated? */ 2275 time_t written; /* time this entry was created. */ 2276 2277 /* if looked up address/name was found, 0. Otherwise errorcode. */ 2278 int gai_rc; 2279 2280 /* 2281 * address or hostname used with DNS for this entry. 2282 * Note that gethostbyname(x) may return address k, but gethostbyaddr(k) 2283 * need not return the hostname 'x', so we need different entries for 2284 * hostnames and addresses and can not reuse one as the other. 2285 */ 2286 hostent_id_t key; 2287 union { 2288 char name[MAXHOSTNAMELEN]; 2289 struct sockaddr_storage addr; 2290 } id; 2291 2292 2293 char service[MAXSERVICELEN]; 2294 2295 union { 2296 struct { 2297 struct addrinfo addrinfo; 2298 /* 2299 * The pointers in addrinfo are set to point to the below memory, 2300 * to avoid having to do dynamic allocation/free repeatedly. 2301 */ 2302 2303 /* 2304 * there is only one hostname returned in struct addrinfo 2305 * by getnameinfo(3). 2306 */ 2307 char ai_canonname_mem[MAXHOSTNAMELEN]; 2308 2309 /* but there can be multiple addresses. */ 2310 struct sockaddr_storage ai_addr_mem[MAX_ADDRINFO_NEXT]; 2311 2312 struct addrinfo ai_next_mem[MAX_ADDRINFO_NEXT]; 2313 2314 struct addrinfo *hints; 2315 struct addrinfo hints_mem; /* memory for hints, if not NULL. */ 2316 } getaddr; 2317 2318 struct { 2319 char name[MAXHOSTNAMELEN]; 2320 int flags; 2321 } getname; 2322 } data; 2323 } dnsinfo_t; 2324 2325 2326 #define HOSTENT_MAX_ALIASES (5) 2327 typedef struct { 2328 unsigned allocated:1; /* entry allocated? */ 2329 unsigned notfound:1; /* looked up address/name was not found. */ 2330 time_t written; /* time this entry was created. */ 2331 2332 2333 /* 2334 * address or hostname used with DNS for this entry. 2335 * Note that gethostbyname(x) may return address k, but gethostbyaddr(k) 2336 * need not return the hostname 'x', so we need different entries for 2337 * hostnames and addresses and can not reuse one as the other. 2338 */ 2339 hostent_id_t key; 2340 union { 2341 char name[MAXHOSTNAMELEN]; 2342 struct in_addr ipv4; 2343 } id; 2344 2345 struct hostent hostent; 2346 2347 /* 2348 * The contents of hostent is set to point to the corresponding area here, 2349 * rather than allocating it on the stack. 2350 * We add one to HOSTENT_MAX_ALIASES because the last index is used 2351 * for NULL-terminating, as per the libresolv (rfc?) spec. 2352 */ 2353 char h_name[MAXHOSTNAMELEN]; 2354 char *h_aliases[HOSTENT_MAX_ALIASES + 1]; 2355 char *h_addr_list[HOSTENT_MAX_ALIASES + 1]; 2356 2357 /* memory for above arrays. */ 2358 char h_aliasesmem[HOSTENT_MAX_ALIASES + 1][MAXHOSTNAMELEN]; 2359 char h_addr_listmem[HOSTENT_MAX_ALIASES + 1][MAX(sizeof(struct in_addr), 2360 sizeof(struct in6_addr))]; 2361 2362 } hostentry_t; 2363 2364 typedef struct { 2365 #if !SOCKS_CLIENT 2366 interfaceside_t side; /* what interface-side we are sending out on. */ 2367 struct sockaddr_storage peer;/* peer we are receiving from. */ 2368 #endif /* !SOCKS_CLIENT */ 2369 2370 int type; /* socket type; SOCK_DGRAM or SOCK_STREAM. */ 2371 int flags; /* flags set on the received data. */ 2372 2373 size_t fromsocket; /* 2374 * number of bytes read from socket. This 2375 * may differ from the return value of the 2376 * function if some sort of encapsulation 2377 * is used (currently only gssapi is 2378 * possible), or parts or all of the data was 2379 * read from an internal buffer rather than 2380 * from the socket itself. 2381 * It may also be less than the return value, 2382 * if more was read from the socket than was 2383 * returned at this time. 2384 */ 2385 2386 struct timeval ts; /* time packet was received (for datagram only). */ 2387 } recvfrom_info_t; 2388 2389 typedef struct { 2390 interfaceside_t side; /* 2391 * what interface-side we are sending out on. 2392 * Only used by server. 2393 */ 2394 2395 size_t tosocket; /* 2396 * number of bytes written to socket. This 2397 * may differ from the return value of the 2398 * function if some sort of encapsulation 2399 * (currently only gssapi is possible) is 2400 * used, or parts or all of the data was 2401 * written from an internal buffer rather 2402 * than to the socket itself. 2403 */ 2404 } sendto_info_t; 2405 2406 2407 2408 2409 /* 2410 * versions of BSD's error functions that log via slog() instead. 2411 */ 2412 2413 void serr(const char *fmt, ...) 2414 __ATTRIBUTE__((noreturn)) __ATTRIBUTE__((FORMAT(printf, 1, 2))); 2415 2416 void serrx(const char *fmt, ...) 2417 __ATTRIBUTE__((noreturn)) __ATTRIBUTE__((FORMAT(printf, 1, 2))); 2418 2419 void swarn(const char *fmt, ...) 2420 __ATTRIBUTE__((FORMAT(printf, 1, 2))); 2421 2422 void swarnx(const char *fmt, ...) 2423 __ATTRIBUTE__((FORMAT(printf, 1, 2))); 2424 2425 2426 void 2427 runenvcheck(void); 2428 /* 2429 * Verify that run environment corresponds to build environment. 2430 */ 2431 2432 long long 2433 maxvalueoftype(const size_t typelen); 2434 /* 2435 * Gives the maxvalue for a signed integer-type stored in a object of length 2436 * "typelen". 2437 */ 2438 2439 long long 2440 minvalueoftype(const size_t typelen); 2441 /* 2442 * Gives the minvalue for a signed integer-type stored in a object of length 2443 * "typelen". 2444 */ 2445 2446 unsigned long long 2447 umaxvalueoftype(const size_t typelen); 2448 /* 2449 * Gives the maxvalue for an unsigned integer-type stored in a object of length 2450 * "typelen". 2451 */ 2452 2453 unsigned long long 2454 uminvalueoftype(const size_t typelen); 2455 /* 2456 * Gives the minvalue for an unsigned integer-type stored in a object of length 2457 * "typelen". 2458 */ 2459 2460 2461 void 2462 genericinit(void); 2463 /* 2464 * Generic init, called after clientinit()/serverinit(). 2465 */ 2466 2467 void 2468 optioninit(void); 2469 /* 2470 * sets options to a reasonable default. 2471 */ 2472 2473 void 2474 postconfigloadinit(void); 2475 /* 2476 * To be called after config is loaded. 2477 */ 2478 2479 int 2480 socks_initupnp(gateway_t *gw, char *emsg, const size_t emsglen); 2481 /* 2482 * Inits upnp for interface corresponding to the gateway "gw". 2483 * If successful, the necessary information to later use the found 2484 * upnp router is saved in "data", which should normally be part of a 2485 * route object. 2486 * 2487 * Returns: 2488 * On success: 0. 2489 * On failure: -1 (no appropriate upnp devices found, or some other error.) 2490 */ 2491 2492 void 2493 newprocinit(void); 2494 /* 2495 * After a new process is started/forked, this function should 2496 * be called. It will initialize various things, open needed 2497 * descriptors, etc. and can be called as many times as wanted. 2498 */ 2499 2500 void * 2501 udpheader_add(const sockshost_t *host, void *msg, size_t *len, 2502 const size_t msgsize); 2503 /* 2504 * Prefixes the udpheader_t version of "host" to a copy of "msg", 2505 * which is of length "len". 2506 * "msgsize" gives the total size of the memory pointed to by "msg", 2507 * which may be up to "len" big. 2508 * 2509 * If "msgsize" is large enough the function will prepend the socks 2510 * udpheader to "msg", moving the old contents in "msg" to the right. 2511 * If not, NULL will be returned with errno set to EMSGSIZE. This 2512 * should only happen if the payload + the socks udpheader is larger 2513 * than the maxsize of a UDP (IP) packet. 2514 * 2515 * Returns: 2516 * On success: "msg" with the udpheader prepended. The length of the new 2517 message is stored in "len". 2518 * On failure: NULL (message to large). 2519 */ 2520 2521 int 2522 fdisopen(const int fd); 2523 /* 2524 * returns true if the file descriptor "fd" currently references a open fd, 2525 * false otherwise. 2526 */ 2527 2528 int 2529 fdisblocking(const int fd); 2530 /* 2531 * returns true if the file descriptor "fd" is blocking, false otherwise. 2532 */ 2533 2534 void 2535 closev(size_t ic, int *iv); 2536 /* 2537 * Goes through "iv", which contains "ic" elements. 2538 * Each element that does not have a negative value is closed. 2539 */ 2540 2541 const loglevel_t * 2542 loglevel(const char *name); 2543 /* 2544 * Returns the loglevel value having the name "name". 2545 * Returns NULL if there is no such loglevel. 2546 */ 2547 2548 2549 int 2550 socks_logmatch(int d, const logtype_t *log); 2551 /* 2552 * Returns true if "d" is a descriptor matching any descriptor in "log". 2553 * Returns false otherwise. 2554 */ 2555 2556 struct sockaddr_storage * 2557 int_sockshost2sockaddr2(const sockshost_t *shost, struct sockaddr_storage *addr, 2558 size_t addrlen, int *gaierr, 2559 char *emsg, size_t emsglen); 2560 /* 2561 * Converts the sockshost_t "shost" to a sockaddr struct and stores it 2562 * in "addr". If conversion fails, 0/0 is stored in "addr" and "gaierr" 2563 * is set to the resolver errorcode. Otherwise, "gaierr" is set to 0. 2564 * 2565 * If "addr" is NULL, the function uses a static buffer which may be 2566 * overwritten on the next call to this function. 2567 * 2568 * If conversion fails, emsg contains the reason. If failure is related 2569 * to DNS, "gaierr" is in addition set. 2570 * 2571 * Returns: "addr". 2572 * 2573 */ 2574 2575 struct sockaddr_storage * 2576 int_sockshost2sockaddr(const sockshost_t *shost, struct sockaddr_storage *addr, 2577 size_t addrlen); 2578 /* 2579 * like int_sockshost2sockaddr(), but without the "gaierr" argument. 2580 */ 2581 2582 2583 struct sockaddr_storage * 2584 int_fakesockshost2sockaddr(const sockshost_t *host, 2585 struct sockaddr_storage *addr, size_t addrlen); 2586 /* 2587 * Like sockshost2sockaddr(), but checks whether the address in 2588 * "host" is fake when converting. 2589 */ 2590 2591 struct sockaddr_storage * 2592 int_urlstring2sockaddr(const char *string, struct sockaddr_storage *addr, 2593 size_t addrlen, int *gaierr, 2594 char *emsg, size_t emsglen); 2595 /* 2596 * Converts the address given in "string", on URL:// format, to 2597 * a sockaddr address stored in "saddr". 2598 * 2599 * Returns "saddr" on success. 2600 * 2601 * Returns NULL on failure with the reason written to "emsg", which must 2602 * be of at least "emsglen" size. If failure is due to resolver failure, 2603 * "gaierr" will contain the resolver errorcode, or 0 if not. 2604 */ 2605 2606 sockshost_t * 2607 sockaddr2sockshost(const struct sockaddr_storage *addr, sockshost_t *host); 2608 /* 2609 * Converts the sockaddr struct "shost" to a sockshost_t struct and stores it 2610 * in "host". If "host" is NULL, a static host object is used instead. 2611 * 2612 * Returns: a pointer to the object containing the sockshost_t representation. 2613 */ 2614 2615 int 2616 sockaddr2hostname(const struct sockaddr_storage *sa, char *hostname, 2617 const size_t hostnamelen); 2618 /* 2619 * reversemaps "sa" to hostname and stores it "hostname", which is at least 2620 * "hostnamelen" bytes big. 2621 * 2622 * Returns: 2623 * 0 on success. 2624 * The corresponding getnameinf(3) error on failure. 2625 */ 2626 2627 sockshost_t * 2628 ruleaddr2sockshost(const ruleaddr_t *address, sockshost_t *host, int protocol); 2629 /* 2630 * Converts the ruleaddr_t "address" to a sockshost_t struct and stores it 2631 * in "host". 2632 * Returns: "host". 2633 */ 2634 2635 struct sockaddr_storage * 2636 int_ruleaddr2sockaddr(const ruleaddr_t *address, struct sockaddr_storage *sa, 2637 size_t salen, const int protocol); 2638 /* 2639 * Converts the ruleaddr_t "address" to a sockshost_t struct and stores it 2640 * in "sa" if not NULL. 2641 * 2642 * Returns: "sa". 2643 */ 2644 2645 struct sockaddr_storage * 2646 int_ruleaddr2sockaddr2(const ruleaddr_t *address, struct sockaddr_storage *sa, 2647 size_t salen, const int protocol, int *gaierr, 2648 char *emsg, const size_t emsglen); 2649 /* 2650 * Converts the ruleaddr_t "address" to a sockshost_t struct and stores it 2651 * in "sa" if not NULL. 2652 * 2653 * On error, "gaierr" may be set, and "emsg" will be set if not NULL. 2654 * 2655 * Returns: "sa". 2656 */ 2657 2658 2659 2660 ruleaddr_t * 2661 sockshost2ruleaddr(const sockshost_t *host, ruleaddr_t *addr); 2662 /* 2663 * Converts the sockshost_t "host" to a ruleaddr_t struct and stores it 2664 * in "addr". 2665 * Returns: "addr". 2666 */ 2667 2668 ruleaddr_t * 2669 sockaddr2ruleaddr(const struct sockaddr_storage *addr, ruleaddr_t *ruleaddr); 2670 /* 2671 * Converts the struct sockaddr "addr" to a ruleaddr_t struct and stores 2672 * it in "ruleaddr". 2673 * Returns: "addr". 2674 */ 2675 2676 struct sockaddr_storage * 2677 int_hostname2sockaddr(const char *name, size_t index, 2678 struct sockaddr_storage *addr, size_t addrlen); 2679 /* 2680 * Retrieves the address with index "index" for the hostname named "name". 2681 * Returns: 2682 * On success: "addr", filled in with the address found. 2683 * On failure: NULL (no address found). 2684 */ 2685 2686 struct sockaddr_storage * 2687 int_hostname2sockaddr2(const char *name, size_t index, 2688 struct sockaddr_storage *addr, size_t addrlen, 2689 int *gaierr, char *emsg, const size_t emsglen); 2690 /* 2691 * Retrieves the address with index "index" for the hostname named "name". 2692 * Returns: 2693 * On success: "addr", filled in with the address found. 2694 * On failure: NULL (no address found). "gaierr" contains the 2695 * resolver error, if available, and "emsg" contains 2696 * a textual description of the error. 2697 */ 2698 2699 2700 struct sockaddr_storage * 2701 int_ifname2sockaddr(const char *ifname, size_t index, 2702 struct sockaddr_storage *addr, size_t addrlen, 2703 struct sockaddr_storage *mask, size_t masklen); 2704 /* 2705 * Retrieves the address with index "index" on the interface named "ifname". 2706 * If "mask" is not NULL, the mask of the interface is stored here. 2707 * 2708 * Returns: 2709 * On success: "addr", and possibly "netmask", filled in with the 2710 * address found. 2711 * On failure: NULL (no address found on the interface at that index. 2712 */ 2713 2714 const char * 2715 sockaddr2ifname(struct sockaddr_storage *addr, char *ifname, size_t iflen); 2716 /* 2717 * Retrieves the name of the interface the address "addr" belongs to. 2718 * The name is written to "ifname", which must be of len "iflen". 2719 * If "ifname" or "iflen" is NULL, the name is written to a local 2720 * buffer instead. 2721 * 2722 * Returns a pointer to the memory containing the interface name, or 2723 * NULL if no matching interface is found. 2724 * 2725 */ 2726 2727 int 2728 sockatmark(int s); 2729 /* 2730 * If "s" is at oob mark, return 1, otherwise 0. 2731 * Returns -1 if a error occurred. 2732 */ 2733 2734 ssize_t 2735 recvmsgn(int s, struct msghdr *msg, int flags); 2736 /* 2737 * Like recvmsg(), but handles some os-specific bugs. 2738 */ 2739 2740 ssize_t 2741 sendmsgn(int s, const struct msghdr *msg, int flags, const time_t timeoutms); 2742 /* 2743 * Like sendmsg(), but retries on temporary errors, including blocking 2744 * with select(2) for up to "timeoutms" milliseconds. 2745 * 2746 * If "timeout" is -1, block forever, or until we've failed a predefined 2747 * number of maxtimes, whatever comes first. 2748 */ 2749 2750 ssize_t 2751 readn(int, void *, size_t, const size_t minread, authmethod_t *auth) 2752 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 2753 /* 2754 * Like read() but with two additional arguments: 2755 * minread - the minimum amount of bytes to read before returning, or error. 2756 * auth - authentication info for the file descriptor. May be NULL. 2757 */ 2758 2759 ssize_t 2760 writen(int, const void *, size_t, const size_t minwrite, 2761 authmethod_t *auth) 2762 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 2763 /* 2764 * like write() but if with two additional arguments: 2765 * minwrite - the minimum amount of bytes to write before returning, or error. 2766 * auth - authentication info for the file descriptor. May be NULL. 2767 */ 2768 2769 ssize_t 2770 socks_recvfrom(int s, void *buf, size_t len, int flags, 2771 struct sockaddr_storage *from, 2772 socklen_t *fromlen, recvfrom_info_t *recvflags, 2773 authmethod_t *auth) 2774 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 2775 /* 2776 * Similar to recvfrom(), but with two additional arguments: 2777 * - auth: if not NULL, the authentication used for this session. 2778 * - recvflags: if not NULL, information about the data received. 2779 */ 2780 2781 ssize_t 2782 socks_recvfromn(const int s, void *buf, size_t len, const size_t minread, 2783 const int flags, struct sockaddr_storage *from, 2784 socklen_t *fromlen, recvfrom_info_t *recvflags, 2785 authmethod_t *auth) 2786 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 2787 /* 2788 * Like socks_recvfrom(), but retries until minread has been read, or failure. 2789 */ 2790 2791 ssize_t 2792 socks_sendto(int s, const void *msg, size_t len, int flags, 2793 const struct sockaddr_storage *, socklen_t, 2794 sendto_info_t *sendflags, authmethod_t *auth) 2795 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 2796 /* 2797 * Like sendto(), but with two additional arguments: 2798 * - sendflags: if not NULL, updated with sendto_info upon return. 2799 */ 2800 2801 ssize_t 2802 socks_sendton(int s, const void *buf, size_t len, const size_t minwrite, 2803 int flags, const struct sockaddr_storage *to, socklen_t tolen, 2804 sendto_info_t *sendflags, authmethod_t *auth) 2805 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 2806 /* 2807 * Like socks_sendto(), but retries until "minwrite" is written, or failure. 2808 */ 2809 2810 int 2811 linkednamesareeq(const linkedname_t *a, const linkedname_t *b); 2812 /* 2813 * Checks if the contents and order of the linked lists "a" and "b" 2814 * is equal. 2815 * 2816 * Returns true if a and b are equal. 2817 * Returns false if a and b are not equal. 2818 */ 2819 2820 2821 int 2822 closen(int); 2823 /* 2824 * Wrapper around close(). Retries on EINTR. 2825 */ 2826 2827 struct timeval * 2828 gettimeofday_monotonic(struct timeval *tv); 2829 /* 2830 * Similar to gettimeofday(2), but time is monotonic. 2831 * Returns "tv", filled with the current time. 2832 */ 2833 2834 time_t 2835 time_monotonic(time_t *tloc); 2836 /* 2837 * Similar to time(3), but time is monotonic. 2838 */ 2839 2840 unsigned long 2841 tv2us(const struct timeval *tv); 2842 /* 2843 * converts "tv" to microseconds and returns the result. 2844 */ 2845 2846 struct timeval * 2847 us2tv(const unsigned long us, struct timeval *tv); 2848 /* 2849 * converts "usec" to struct timeval and stores the result in "tv". 2850 * Returns "tv". 2851 */ 2852 2853 2854 int 2855 selectn(int nfds, fd_set *rset, fd_set *bufrset, fd_set *buffwset, 2856 fd_set *wset, fd_set *xset, struct timeval *); 2857 /* 2858 * Wrapper around select() that takes two additional arguments: 2859 * bufrset - if not NULL, set to contain descriptors with data buffered 2860 * for reading. 2861 * buffwset - if not NULL, set to contain descriptors with data buffered 2862 * for writing (buffered-for-writing). 2863 * 2864 * In addition, if it's called by the server, it checks whether we 2865 * have a signal queued internally, and if so calls the appropriate 2866 * signal handler. 2867 */ 2868 2869 int 2870 acceptn(int, struct sockaddr_storage *, socklen_t *); 2871 /* 2872 * Wrapper around accept(). Retries on EINTR. 2873 */ 2874 2875 int 2876 socks_socket(const int domain, const int type, const int protocol); 2877 /* 2878 * Like socket(2), but also sets some options we always want to set. 2879 */ 2880 2881 2882 int 2883 setblocking(const int fd, const char *context); 2884 /* 2885 * Configures "fd" to use blocking i/o. 2886 * "context" provides the context "fd" will be used in. 2887 * 2888 * Returns: 2889 * On success: the original fd-flags set on fd "fd" before the change. 2890 * On failure: -1. In this case errno will be set and a warning will 2891 * be logged using "context". 2892 */ 2893 2894 int 2895 setnonblocking(const int fd, const char *context); 2896 /* 2897 * Configures "fd" to use non-blocking i/o. 2898 * "context" provides the context "fd" will be used in. 2899 * 2900 * Returns: 2901 * On success: the original fd-flags set on fd "fd" before the change. 2902 * On failure: -1. In this case errno will be set and a warning will 2903 * be logged using "context". 2904 */ 2905 2906 int 2907 socks_socketisforlan(const int s); 2908 /* 2909 * If we can determine that the socket "s" is for lan use only, i.e. should 2910 * not be proxied, returns true. Otherwise, returns false. 2911 */ 2912 2913 struct sockaddr_storage * 2914 socketisconnected(const int s, struct sockaddr_storage *addr, socklen_t alen); 2915 /* 2916 * If the socket "s" is connected to a peer, returns peer's address. 2917 * If "addr" is not NULL, the peer address is stored in "addr", and a 2918 * pointer to "addr" is returned. Otherwise a static buffer is used 2919 * and a pointer to that static buffer is returned. 2920 * 2921 * If the socket "s" is not connected, NULL is returned. 2922 */ 2923 2924 int 2925 fdisdup(const int fd1, const int fd2); 2926 /* 2927 * Tries to determine if file descriptor fd1 is a dup of fd2. 2928 * Returns true if yes, false if not. 2929 */ 2930 2931 2932 int 2933 socks_rebind(int s, int protocol, struct sockaddr_storage *from, 2934 const struct ruleaddr_t *to, char *emsg, const size_t emsglen); 2935 /* 2936 * Tries to rebind the socket 's", currently bound to address "from", if 2937 * any, to match the range given by "to". 2938 * 2939 * Returns 0 on success. 2940 * Returns 0 on failure. Error will be written to emsg and errno will be set. 2941 */ 2942 2943 int 2944 socks_bindinrange(int s, struct sockaddr_storage *addr, 2945 in_port_t first, in_port_t last, const enum operator_t op); 2946 /* 2947 * Like sockd_bind(), but keeps trying to sockd_bind a address in the 2948 * range given by "addr", as indicated by "first", "last" and "op", 2949 * until whole range has been tried. 2950 */ 2951 2952 int 2953 socks_bind(int s, struct sockaddr_storage *addr, size_t retries); 2954 /* 2955 * Binds the address "addr" to the socket "s". The bind call will 2956 * be tried "retries" + 1 times if the error is EADDRINUSE, or until 2957 * successful, whatever comes first. 2958 * 2959 * If the port number is privileged, it will set and reset the euid 2960 * as appropriate. (Only applies when called called by server.) 2961 * 2962 * If successful, "addr" is filled in with the bound address. 2963 * Returns: 2964 * On success: 0. 2965 * On failure: -1 2966 */ 2967 2968 const struct in_addr * 2969 ipv4_addrisinlist(const struct in_addr *addr, const struct in_addr *mask, 2970 const struct addrinfo *ailist); 2971 2972 const struct in6_addr * 2973 ipv6_addrisinlist(const struct in6_addr *addr, const unsigned int maskbits, 2974 const struct addrinfo *ailist); 2975 2976 /* 2977 * Compares "addr", bitwise AND-ed with "mask", against each IPv4 or IPv6 2978 * address * in "list", also bitwise AND-ed with "mask". 2979 * 2980 * Returns: 2981 * If "list" contains a element matching "addr": pointer to the matching 2982 address in ailist. 2983 * otherwise: NULL. 2984 */ 2985 2986 2987 int 2988 sockaddrareeq(const struct sockaddr_storage *a, 2989 const struct sockaddr_storage *b, const size_t nocompare); 2990 /* 2991 * Compares the address "a" against "b". 2992 * If "nocompare" is not zero, the attributes set (ADDRINFO_PORT, etc.) 2993 * are excluded from the comparison. 2994 * 2995 * Returns: 2996 * If "a" and "b" are equal: true 2997 * else: false 2998 */ 2999 3000 3001 void 3002 usrsockaddrcpy(struct sockaddr_storage *dst, const struct sockaddr_storage *src, 3003 const size_t len); 3004 /* 3005 * Duplicate contents of sockaddr structure, up to len bytes. 3006 * Variant of sockaddrcpy() for sockaddr copying sockaddr data 3007 * from clients in Rfoo() functions. 3008 */ 3009 3010 void 3011 sockaddrcpy(struct sockaddr_storage *dst, const struct sockaddr_storage *src, 3012 const size_t len); 3013 /* 3014 * Duplicate contents of sockaddr structure, up to len bytes. 3015 */ 3016 3017 sa_len_type 3018 salen(const sa_family_t family); 3019 /* 3020 * returns the sockaddrlen of a sockaddr struct of family "family". 3021 */ 3022 3023 sa_len_type 3024 inaddrlen(const sa_family_t family); 3025 /* 3026 * returns the ipaddresslen of an address of the familytype "family". 3027 */ 3028 3029 3030 int 3031 safamily_issupported(const sa_family_t family); 3032 /* 3033 * Returns true if we support the sockaddr family "family". 3034 * Returns false if we do not. 3035 */ 3036 3037 sa_family_t 3038 atype2safamily(const int atype); 3039 /* 3040 * Returns the sa_family_t equivalent of the SOCKS address type 3041 * "atype", which must be one of SOCKS_ADDR_IPV4 or SOCKS_ADDR_IPV6. 3042 */ 3043 3044 int 3045 safamily2atype(const sa_family_t safamily); 3046 /* 3047 * Returns the atype equivalent of the sa_family_t "safamily". 3048 */ 3049 3050 3051 int 3052 addrinfo_issupported(const struct addrinfo *ai); 3053 /* 3054 * Returns true if we support the addrinfo in "ai". 3055 * Returns false if we do not. 3056 */ 3057 3058 3059 /* 3060 * Wrapper around standard functions. 3061 */ 3062 const char *socks_strerror(const int err); 3063 const char *socks_gai_strerror(const int err); 3064 3065 size_t 3066 snprintfn(char *str, size_t size, const char *format, ...) 3067 __ATTRIBUTE__((FORMAT(printf, 3, 4))) 3068 __ATTRIBUTE__((__NONNULL__(3))) 3069 __ATTRIBUTE__((__BOUNDED__(__string__, 1, 2))); 3070 /* 3071 * Wrapper around snprintf() for consistent behavior. Same as stdio 3072 * snprintf() but the following are also enforced: 3073 * returns 0 instead of -1 (rawterminates *str) on error. 3074 * never returns a value greater than size - 1. 3075 */ 3076 3077 void 3078 socks_sigblock(const int sig, sigset_t *oldset); 3079 /* 3080 * If "sig" is -1, blocks all signals. If not, adds only "sig" to 3081 * the list of currently blocked signals. 3082 * 3083 * The old signal mask is returned in "oldset". 3084 */ 3085 3086 void 3087 socks_sigunblock(const sigset_t *oldset); 3088 /* 3089 * Restores the current signal mask to "oldset". 3090 */ 3091 3092 const char * 3093 strcheck(const char *string); 3094 /* 3095 * Checks "string". If it is NULL, returns a string indicating memory 3096 * exhausted, if not, returns the same string it was passed. 3097 */ 3098 3099 unsigned char * 3100 sockshost2mem(const sockshost_t *host, unsigned char *mem, int version); 3101 /* 3102 * Writes "host" out to "mem". The caller must make sure "mem" 3103 * is big enough to hold the contents of "host". 3104 * "version" gives the socks version "host" is to be written out in. 3105 * Returns a pointer to one element past the last byte written to "mem". 3106 */ 3107 3108 const unsigned char * 3109 mem2sockshost(sockshost_t *host, const unsigned char *mem, size_t len, 3110 int version) 3111 __ATTRIBUTE__((__BOUNDED__(__buffer__, 2, 3))); 3112 /* 3113 * Writes "mem", which is assumed to be a sockshost string 3114 * of length "len" in version "version" in network order, out to "host". 3115 * Returns: 3116 * On success: pointer to one element past last byte used of mem 3117 * and fills in "host" appropriately. 3118 * On failure: NULL ("mem" is not a valid sockshost.) 3119 */ 3120 3121 unsigned int socks_get_responsevalue(const response_t *response); 3122 void socks_set_responsevalue(response_t *response, unsigned int value); 3123 /* 3124 * Functions to fetch or set the value of the response, depending on what 3125 * version the response belongs to. 3126 */ 3127 3128 int * 3129 charmethod2intmethod(const size_t methodc, 3130 const unsigned char charmethodv[], int intmethodv[]); 3131 /* 3132 * converts char method array "charmethodv" with "methodc" elements, 3133 * to a integer method array, storing the result in "intmethodv". 3134 * 3135 * Returns "intmethodv". 3136 */ 3137 3138 3139 int 3140 proxyprotocolisknown(const int version); 3141 /* 3142 * Returns true if "version" is a known proxy version. 0 if not. 3143 */ 3144 3145 int 3146 authmethodisknown(const int method); 3147 /* 3148 * Returns true if "method" is a known authmethod. 0 if not. 3149 */ 3150 3151 int 3152 socks_addlogfile(logtype_t *logcf, const char *logfile); 3153 /* 3154 * Adds the file "logfile" to the list of files we log to, stored in "logcf". 3155 * 3156 * Returns 0 on success. 3157 * Returns -1 on failure. 3158 */ 3159 3160 void slog(int priority, const char *fmt, ...) 3161 __ATTRIBUTE__((FORMAT(printf, 2, 3))); 3162 /* 3163 * Logs message "fmt" at priority "priority" to previously configured 3164 * output device. 3165 * Checks settings and ignores message if it's of to low a priority. 3166 */ 3167 3168 void vslog(int priority, const char *fmt, va_list ap, va_list apcopy) 3169 __ATTRIBUTE__((FORMAT(printf, 2, 0))); 3170 /* 3171 * Same as slog() but assumes varargs/stdargs have already processed 3172 * the arguments. 3173 */ 3174 3175 void 3176 signalslog(const int priority, const char *msgv[]); 3177 /* 3178 * Similar to slog(), but simpler. 3179 * 3180 * "msgv" is an array of NUL-terminated strings. The last element in this 3181 * array must be NULL. 3182 * The function logs all the strings in "msgv", as one. Caller must take 3183 * care of any desired space between the strings. 3184 * 3185 * Can be called from a signalhandler. 3186 */ 3187 3188 3189 3190 int 3191 parseconfig(const char *filename); 3192 /* 3193 * Parses the config stored in in the filename "filename", as well 3194 * as environment-variables related. 3195 * 3196 * Returns: 3197 * On success: 0. 3198 * On failure: -1. 3199 */ 3200 3201 void 3202 resetconfig(struct config *config, const int exiting); 3203 /* 3204 * resets the config "config" back to default, freeing memory as well. 3205 * If "exiting" is true, we are exiting and don't need to save 3206 * anything. 3207 */ 3208 3209 3210 int 3211 addrmatch(const ruleaddr_t *rule, const sockshost_t *address, 3212 sockshost_t *addrmatched, int protocol, int ipalias); 3213 /* 3214 * Tries to match "address" against "rule". "address" is resolved 3215 * if necessary. "rule" supports the wildcard INADDR_ANY and port of 0. 3216 * "protocol" is the protocol to compare under. 3217 * 3218 * If "ipalias" is true and "address" is an IP-address, the function will 3219 * try to reverse-map "address" to hostname, the hostname to ip, and match 3220 * those ipaddresses against "rule". 3221 * 3222 * Returns true if "rule" matched "address". In this case, if "addrmatched" 3223 * is not NULL, it is updated to reflect the address that matched, which may 3224 * be different from "address" if "address" had to be resolved or 3225 * reversemapped. 3226 */ 3227 3228 int 3229 socks_connecthost(int s, 3230 #if !SOCKS_CLIENT 3231 const interfaceside_t side, 3232 #endif /* !SOCKS_CLIENT */ 3233 const sockshost_t *host, 3234 struct sockaddr_storage *laddr, 3235 struct sockaddr_storage *raddr, 3236 const long timeout, char *emsg, const size_t emsglen); 3237 /* 3238 * Tries to connect to "host". If "host"'s address is not a IP address, 3239 * the function also tries to connect to any alias for "host"'s 3240 * name. The connection is done using the open descriptor "s". 3241 * 3242 * If "laddr" is not NULL, it is filled in with the address we connected to 3243 * "host" from, if a connect(2) was initiated. 3244 * 3245 * If "raddr" is not NULL, it is filled in with the address connected to if 3246 * successful. If "host" is a an ip address, it will be identical to that 3247 * ip address, but if "host" is a hostname, they will of course differ. 3248 * 3249 * If "timeout" is not negative, it gives the timeout for how long to wait 3250 * for the connect to complete. A value of zero means no wait will be 3251 * done, and the the function may return with errno set to EINPROGRESS. 3252 * A negative value for timeout means wait the kernel/system default. 3253 * 3254 * If the function fails, the reason is written to emsg, which must be 3255 * at least "emsglen" long. 3256 * 3257 * Returns: 3258 * On success: 0 3259 * On failure: -1. Reason for error is written to emsg. 3260 */ 3261 3262 route_t * 3263 socks_connectroute(const int s, socks_t *packet, 3264 const sockshost_t *src, const sockshost_t *dst, 3265 char *emsg, const size_t emsglen); 3266 /* 3267 * Finds a route from "src" to "dst" and connects to it "s". 3268 * If src or dst is NULL, that argument is ignored. 3269 * 3270 * The route used may take into account the contents of "packet->req", 3271 * which is assumed to be the packet that will be sent to a socks server, 3272 * so it is recommended that it's contents be as conservative as possible. 3273 * 3274 * When it has successfully connected to a gateway it will set 3275 * the packet->method members to point to the methods the gateway 3276 * should be offered. 3277 * 3278 * Returns: 3279 * On success: the route that was used. 3280 * On failure: NULL. See emsg for reason. 3281 */ 3282 3283 route_t * 3284 socks_requestpolish(request_t *req, const sockshost_t *src, 3285 const sockshost_t *dst); 3286 /* 3287 * Tries to "polish" (modify) the request "req" for a session from "src" 3288 * to "dst", so that a later socks_getroute() will succeed. 3289 * 3290 * Returns: 3291 * On success: the route that will match the polished request. 3292 * On failure: NULL. 3293 */ 3294 3295 int 3296 socks_routesetup(const int control, const int data, const route_t *route, 3297 char *emsg, const size_t emsglen); 3298 /* 3299 * Prepares for establishing a session via route "route". 3300 * "control" gives the controlsocket that will be used. 3301 * "data" gives the data socket that will be used. 3302 * 3303 * Return 0 on success. 3304 * Returns -1 on failure. Reason for failure will be stored in "emsg", and 3305 * errno will be set appropriately. 3306 */ 3307 3308 void 3309 showstate(const serverstate_t *state); 3310 /* 3311 * logs a printable representation of "state" to the logfile. 3312 */ 3313 3314 void 3315 showmethod(objecttype_t type, size_t methodc, const int *methodv); 3316 /* 3317 * Shows methods set in "methodv" array. 3318 * "type" indicates whether the methods are for a client/hostid-rule, 3319 * and thus are clientmethods, or for a socksrule, and thus are socksmethods. 3320 */ 3321 3322 void 3323 showtimeout(const timeout_t *timeout); 3324 /* 3325 * shows timeouts set in "timeout". 3326 */ 3327 3328 3329 void 3330 freeroutelist(route_t *routehead); 3331 /* 3332 * Frees a list of routes and their contents, starting at "routehead". 3333 */ 3334 3335 route_t * 3336 socks_addroute(const route_t *route, const int last); 3337 /* 3338 * Appends a copy of "route" to our list of routes. 3339 * If "last" is true, the route is added to the end of our list. 3340 * If not, it's added to the start, and existing rule numbers are updated 3341 * correspondingly. 3342 * 3343 * Returns a pointer to the added route. 3344 */ 3345 3346 route_t * 3347 socks_autoadd_directroute(const command_t *commands, 3348 const protocol_t *protocols, 3349 const struct sockaddr_storage *saddr, 3350 const struct sockaddr_storage *netmask); 3351 /* 3352 * Adds a direct route to "saddr", netmask "netmask", for the commands 3353 * "commands" and protocols "protocols". 3354 * 3355 * Intended to be used for routes that are added automatically, 3356 * and not via socks.conf. 3357 */ 3358 3359 void 3360 socks_showroute(const route_t *route); 3361 /* 3362 * prints the route "route". 3363 */ 3364 3365 route_t * 3366 socks_getroute(const request_t *req, const sockshost_t *src, 3367 const sockshost_t *dst); 3368 /* 3369 * Tries to find a route to be used for a connection going from 3370 * "src" to "dst". 3371 * If src or dst is NULL, that argument is ignored. 3372 * 3373 * The route used may take into account the contents of "req", which is 3374 * assumed to be the packet that will be sent to a socks server, so it is 3375 * recommended that it's contents be as conservative as possible. 3376 * 3377 * Returns: 3378 * On success: pointer to route that should be used. 3379 * On failure: NULL (no route found). 3380 */ 3381 3382 unsigned int 3383 sockscode(const int version, const int code); 3384 /* 3385 * Maps the socks reply code "code", which is in non-version specific format, 3386 * to the equivalent reply code in version "version". 3387 */ 3388 3389 unsigned int 3390 errno2reply(int errnum, int version); 3391 /* 3392 * Returns the proxy version "version" reply code for a error of type "errno". 3393 */ 3394 3395 char * 3396 str2vis(const char *string, size_t len, char *visstring, size_t vislen) 3397 __ATTRIBUTE__((__BOUNDED__(__string__, 3, 4))); 3398 /* 3399 * Visually encodes exactly "len" chars of "string" and stores the 3400 * result in "visstring", which is of length "vislen". "vislen" should 3401 * be at least "len" * 4 + 1. 3402 * Note that the function really will encode len characters, including 3403 * any NUL-characters. 3404 * 3405 * Returns: the visually encoded string, "visstring". 3406 */ 3407 3408 in_addr_t 3409 socks_addfakeip(const char *name); 3410 /* 3411 * Adds "name" to a internal table indexed by (fake)IP addresses. 3412 * Returns: 3413 * On success: "name"'s index. 3414 * On failure: INADDR_NONE 3415 */ 3416 3417 const char * 3418 socks_getfakehost(in_addr_t addr); 3419 /* 3420 * If "addr" is a "fake" (non-resolved) addr, it returns the name 3421 * corresponding to it. 3422 * Else, NULL is returned. 3423 */ 3424 3425 int 3426 socks_getfakeip(const char *host, struct in_addr *addr); 3427 /* 3428 * If "host" has a fake address entry, the address is written into 3429 * "addr". 3430 * Returns: 3431 * If a fake address exits: true 3432 * Else: false 3433 */ 3434 3435 sockshost_t * 3436 fakesockaddr2sockshost(const struct sockaddr_storage *addr, sockshost_t *host); 3437 /* 3438 * Identical to sockaddr2sockshost, but checks whether 3439 * the address in "addr" is a "fake" one when converting. 3440 */ 3441 3442 int 3443 sockshostareeq(const sockshost_t *a, const sockshost_t *b); 3444 /* 3445 * Compares the address "a" against "b". 3446 * Returns: 3447 * If "a" and "b" are equal: true 3448 * else: false 3449 */ 3450 3451 int 3452 fdsetop(int highestfd, int op, const fd_set *a, const fd_set *b, 3453 fd_set *result); 3454 /* 3455 * Performs operation on descriptor sets. 3456 * "highestfd" is the descriptors with the highest index to perform operation 3457 * "op" on in the sets "a" and "b". 3458 * 3459 * The result of the operation is stored in "result". 3460 * 3461 * Returns the number of the highest descriptor set in "result". 3462 * NOTES: 3463 * - operators supported is: AND ('&'), XOR ('^'), and OR ('|'). 3464 */ 3465 3466 int 3467 methodisset(int method, const int *methodv, size_t methodc); 3468 /* 3469 * Returns true if the method "method" is set in "methodv", false otherwise. 3470 * "methodc" is the length of "methodv". 3471 */ 3472 3473 3474 char * 3475 get_tcpinfo(const size_t fdc, int fdv[], char *buf, size_t buflen); 3476 /* 3477 * Retrieves tcp_info for the sockets in "fdv" and stores it in "buf", if 3478 * buf is not NULL. 3479 * If buf or buflen is not set, stores it in locally allocated memory 3480 * and return a pointer to it rather than to buf. 3481 * 3482 * If tcpinfo can not be retrieved for any of the sockets in fdv, 3483 * that index in fdv is set to -1. 3484 * 3485 * Returns: 3486 * String with tcpinfo values, or NULL if no tcpinfo could be retrieved. 3487 */ 3488 3489 int 3490 socketoptdup(int s, int new_s); 3491 /* 3492 * Duplicates the settings of "s" onto "new_s". If "new_s" is -1, 3493 * a new socket is created for it. 3494 * 3495 * Returns: 3496 * On success: new_s (or the descriptor for the new socket if new_s is -1). 3497 * On failure: -1 3498 */ 3499 3500 void 3501 socketoptioncheck(const socketoption_t *option); 3502 /* 3503 * Check socketoption arguments against sockopt_t entry. 3504 */ 3505 3506 int 3507 addedsocketoption(size_t *optc, socketoption_t **optv, 3508 const socketoption_t *newoption); 3509 /* 3510 * Adds the socketoption "newoption" to the list of current options 3511 * in the socketoption array "optv". 3512 * 3513 * Returns true on success. false on failure. 3514 */ 3515 3516 void setconfsockoptions(const int target, const int in, const int protocol, 3517 const int isclientside, 3518 const size_t optc, const socketoption_t *optv, 3519 const int whichlocals, const int whichglobals); 3520 /* 3521 * Sets the options in "optv" on the socket "target", presumably loaded from 3522 * the sockd.conf. "target" should be a socket of the type indicated by 3523 * protocol (SOCKS_TCP or SOCKS_UDP). 3524 * 3525 * If "in" is not -1, it indicates the socket the socket a connection from 3526 * a client came in from, and perhaps the reason "target" was created. 3527 * This is used in some special cases where we need to copy some special 3528 * options from the client connection (e.g., hostids). 3529 * 3530 * "isclientside" indicates whether "s" is a socket for the internal (client) 3531 * or external interface. 3532 * 3533 * "whichglobals" indicates what global (not rule/route-specific) options 3534 * configured should be checked at this time, and "whichlocals" the 3535 * same for the options in optv. 3536 */ 3537 3538 int 3539 socks_mklock(const char *template, char *newname, const size_t newnamelen); 3540 /* 3541 * Creates a file that can be used with socks_lock() and 3542 * socks_unlock(). Returns the file descriptor of the created file. 3543 * If "newname" or "newnamelen" is zero, the created file is unlinked. 3544 * Otherwise the file is not unlinked and the name of the created file is 3545 * is saved to newname. 3546 * 3547 * Returns: 3548 * On success: file descriptor 3549 * On failure: -1 3550 */ 3551 3552 int 3553 socks_lock(const int fd, const off_t offset, const off_t len, 3554 const int exclusive, const int wait); 3555 /* 3556 * Looks the file descriptor "fd" at offset "offset", length "len". 3557 * If "exclusive" is true, the lock is exclusive. If not, it is shared. 3558 * If "wait" is true, wait for the lock. If not, return if the lock 3559 * can not be taken. 3560 * 3561 * Upgrade/downgrade to/from exclusive is permitted. 3562 * 3563 * Returns: 3564 * On success: 0 3565 * On error : -1 3566 */ 3567 3568 void 3569 socks_unlock(int d, const off_t offset, const off_t len); 3570 /* 3571 * Unlocks the file descriptor "d", previously locked by this process, 3572 * at offset "offset", length "len". 3573 */ 3574 3575 int 3576 bitcount(unsigned long number); 3577 /* 3578 * Returns the number of bits set in "number". 3579 */ 3580 3581 int 3582 bitcount_in6addr(const struct in6_addr *in6addr); 3583 /* 3584 * Returns the number of bits set in "in6addr". 3585 */ 3586 3587 3588 #if SOCKSLIBRARY_DYNAMIC 3589 /* 3590 * Here because they may be indirectly used by the server too, when it 3591 * executes external library code (e.g., libwrap). 3592 */ 3593 3594 struct hostent *sys_gethostbyaddr(const char *addr, socklen_t len, int af); 3595 struct hostent *sys_gethostbyname(const char *); 3596 struct hostent *sys_gethostbyname2(const char *, int); 3597 3598 #if HAVE_GETADDRINFO 3599 int sys_getaddrinfo(const char *nodename, const char *servname, 3600 const struct addrinfo *hints, struct addrinfo **res); 3601 #endif /* HAVE_GETADDRINFO */ 3602 3603 #if HAVE_GETIPNODEBYNAME 3604 struct hostent *sys_getipnodebyname(const char *name, int af, int flags, 3605 int *error_num); 3606 #endif /* HAVE_GETIPNODEBYNAME */ 3607 3608 #if SOCKS_CLIENT 3609 #if HAVE___FPRINTF_CHK 3610 HAVE_PROT_FPRINTF_0 __fprintf_chk(HAVE_PROT_FPRINTF_1 stream, int dummy, 3611 HAVE_PROT_FPRINTF_2 format, ...); 3612 #endif /* HAVE___FPRINTF_CHK */ 3613 3614 #if HAVE___VFPRINTF_CHK 3615 HAVE_PROT_VFPRINTF_0 __vfprintf_chk(HAVE_PROT_VFPRINTF_1 stream, 3616 int dummy, HAVE_PROT_VFPRINTF_2 format, HAVE_PROT_VFPRINTF_3 ap); 3617 #endif /* HAVE___VFPRINTF_CHK */ 3618 #endif /* SOCKS_CLIENT */ 3619 3620 #if HAVE___READ_CHK 3621 HAVE_PROT__READ_CHK_0 3622 __read_chk(HAVE_PROT__READ_CHK_1 d, HAVE_PROT__READ_CHK_2 buf, 3623 HAVE_PROT__READ_CHK_3 nbytes, HAVE_PROT__READ_CHK_4 buflen); 3624 #endif /* HAVE___READ_CHK */ 3625 3626 #endif /* SOCKSLIBRARY_DYNAMIC */ 3627 3628 int 3629 httpproxy_negotiate(int control, socks_t *packet, 3630 char *emsg, const size_t emsglen); 3631 /* 3632 * Negotiates a session to be used with the server connected to "control". 3633 * "packet" is the packet with information about what we want the 3634 * server to do for us. 3635 * packet->res.reply will be set according to the result of negotiation. 3636 * Returns: 3637 * On success: 0 (server accepted our request). 3638 * On failure: -1. "emsg" will contain the details. 3639 */ 3640 3641 int 3642 upnp_negotiate(const int s, socks_t *packet, gateway_t *gw, 3643 char *emsg, const size_t emsglen); 3644 /* 3645 * Negotiates a session to be used with the upnp server. 3646 * If the request is for a i/o operation, socket is the socket to be used 3647 * for performing the i/o. 3648 * 3649 * "packet" is the packet with information about what we want the 3650 * server to do for us. 3651 * 3652 * "gw" is the upnp gateway to used. 3653 * 3654 * packet->res.reply will be set according to the result of negotiation. 3655 * 3656 * Returns: 3657 * On success: 0 (server accepted our request). 3658 * Note that we do not need to contact the UPNP router 3659 * for all requests. If we do not need to contact it for 3660 * the given request, we will just pretend everything is ok. 3661 * 3662 * On failure: -1. "emsg" will contain the details. 3663 */ 3664 3665 int 3666 socks_negotiate(int s, int control, socks_t *packet, route_t *route, 3667 char *emsg, const size_t emsglen); 3668 /* 3669 * "s" is the socket data will flow over. 3670 * "control" is the control connection to the socks server. 3671 * "packet" is a socks packet containing the request. 3672 * "route" is the connected route. 3673 * Negotiates method and fills the response to the request into packet->res. 3674 * 3675 * Returns: 3676 * On success: 0 (server replied to our request). 3677 * On failure: -1. Reason is stored in "emsg" and errno is set. 3678 */ 3679 3680 int 3681 serverreplyisok(const unsigned int version, const unsigned int command, 3682 const unsigned int reply, route_t *route, 3683 char *emsg, const size_t emsglen); 3684 /* 3685 * "replycode" is the reply code returned by a socks server of version 3686 * "version". 3687 * "route" is the route that was used for the socks server. 3688 * If the error code indicates a server failure, the route might be 3689 * "blacklisted". 3690 * 3691 * On success: true. 3692 * On failure: false. Reason is stored in "emsg" and errno is set. 3693 */ 3694 3695 route_t * 3696 socks_nbconnectroute(int s, int control, socks_t *packet, 3697 const sockshost_t *src, const sockshost_t *dst, 3698 char *emsg, const size_t emsglen); 3699 /* 3700 * The non-blocking version of socks_connectroute(), only used by client. 3701 * Takes one additional argument, "s", which is the socket to connect 3702 * and not necessarily the same as "control" (msproxy case). 3703 */ 3704 3705 void 3706 socks_blacklist(route_t *route, const char *reason); 3707 /* 3708 * Marks route "route" as bad. 3709 * "reason" is a short reason describing why we are blacklisting this route. 3710 */ 3711 3712 void 3713 socks_clearblacklist(route_t *route); 3714 /* 3715 * Clears bad marks on route. 3716 */ 3717 3718 int 3719 methodisvalid(const int method, objecttype_t ruletype); 3720 /* 3721 * Returns true if "method" is a valid method for rules of type 3722 * "ruletype". 3723 */ 3724 3725 int 3726 negotiate_method(int s, socks_t *packet, route_t *route, 3727 char *emsg, const size_t emsglen); 3728 /* 3729 * Negotiates a method to be used when talking with the server connected 3730 * to "s". 3731 * "packet" is the packet that will later be sent to server, and only 3732 * the "auth" element in it will be set but other elements are needed 3733 * for reading too. 3734 * "route" is the route selected for connecting to the socks-server. 3735 * 3736 * Returns: 3737 * On success: 0 3738 * On failure: -1. "emsg" will contain the details. 3739 */ 3740 3741 int 3742 clientmethod_uname(int s, const sockshost_t *host, int version, 3743 unsigned char *name, unsigned char *password, 3744 char *emsg, size_t emsglen); 3745 /* 3746 * Enters username/password negotiation with the socks server connected to 3747 * the socket "s". 3748 * "host" gives the name of the server. 3749 * "version" gives the socks version established to use. 3750 * "name", if not NULL, gives the name to use for authenticating. 3751 * "password", if not NULL, gives the name to use for authenticating. 3752 * Returns: 3753 * On success: 0 3754 * On failure: -1. "emsg" will contain the details. 3755 */ 3756 3757 #if HAVE_GSSAPI 3758 int 3759 clientmethod_gssapi(int s, int protocol, const gateway_t *gw, 3760 int version, authmethod_t *auth, 3761 char *emsg, const size_t emsglen); 3762 /* 3763 * Enters gssapi negotiation with the socks server connected to 3764 * the socket "s". 3765 * "gw" gives the name of the gateway. 3766 * "version" gives the socks version established to use. 3767 * "*auth", authentication structure 3768 * Returns: 3769 * On success: 0 3770 * On failure: -1. "emsg" will contain the details. 3771 */ 3772 3773 int 3774 gssapi_encode(const gss_buffer_t in, gssapi_state_t *gs, gss_buffer_t out); 3775 /* 3776 * gssapi encodes the data in "in", storing the encoded message 3777 * in "out", which contains a pointer to the previously allocated 3778 * memory of the specified length. 3779 * 3780 * "gs" contains details about gssapi context. 3781 * 3782 * Returns: 3783 * On success: 0 3784 * On failure: -1 3785 */ 3786 3787 int 3788 gssapi_decode(const gss_buffer_t in, gssapi_state_t *gs, gss_buffer_t out); 3789 /* 3790 * gssapi decodes the data in "in", storing the decoded message 3791 * in "out", which contains a pointer to the previously allocated 3792 * memory of the specified length. 3793 * 3794 * "gs" contains details about gssapi context. 3795 * 3796 * Returns: 3797 * On success: 0 3798 * On failure: -1 3799 */ 3800 3801 #endif /* HAVE_GSSAPI */ 3802 3803 3804 int socks_yyparse(void); 3805 int socks_yylex(void); 3806 3807 int 3808 socks_sendrequest(int s, const request_t *request, 3809 char *emsg, const size_t emsglen); 3810 /* 3811 * Sends the request "request" to the socks server connected to "s". 3812 * Returns: 3813 * On success: 0 3814 * On failure: -1. Reason is stored in "emsg" and errno is set. 3815 */ 3816 3817 int 3818 socks_recvresponse(int s, response_t *response, int version, 3819 char *emsg, const size_t emsglen); 3820 /* 3821 * Receives a socks response from the "s". "response" is filled in with 3822 * the data received. 3823 * "version" is the protocol version negotiated. 3824 * 3825 * Returns: 3826 * On success: 0 3827 * On failure: -1. Reason is stored in "emsg" and errno is set. 3828 */ 3829 3830 iobuffer_t * 3831 socks_allocbuffer(const int s, const int type); 3832 /* 3833 * Returns the iobuffer allocated to file descriptor "s", or 3834 * a new free one if none is allocated. 3835 * "type" gives the type of socket "s" is, SOCK_STREAM or SOCK_DGRAM. 3836 * 3837 * It is an error if a new buffer is allocated to "s" before the old 3838 * one has been freed. 3839 */ 3840 3841 void 3842 socks_initbuffer(const int fd, const int stype, iobuffer_t *iobuf); 3843 3844 iobuffer_t * 3845 socks_getbuffer(const int s); 3846 /* 3847 * Returns the iobuffer allocated to file descriptor "s". 3848 */ 3849 3850 void 3851 socks_freebuffer(const int s); 3852 /* 3853 * Marks the iobuffer allocated to file descriptor "s" as free. 3854 * It is not an error if no iobuffer is currently allocate dto "s". 3855 */ 3856 3857 void 3858 socks_reallocbuffer(const int old, const int new); 3859 /* 3860 * Reallocs the buffer assigned to "old", if any, to instead be assigned 3861 * to "new". 3862 */ 3863 3864 void 3865 socks_clearbuffer(const int s, const whichbuf_t type); 3866 /* 3867 * Clears the iobuffer belonging to "s". 3868 * "type" gives the buffer-type that should be cleared, READ_BUF or WRITE_BUF. 3869 */ 3870 3871 int socks_flushbuffer(const int s, const ssize_t len, 3872 sendto_info_t *sendtoflags); 3873 /* 3874 * Tries to flush the data buffered for file descriptor "s". If "s" is -1, 3875 * data for all descriptors is flushed. 3876 * 3877 * If "len" is -1, tries to flush all data on that fd, otherwise only flushes 3878 * up to "len" bytes. 3879 * 3880 * If "sendtoflags" is not NULL, it is updated appropriately. 3881 * 3882 * Returns 0 if all data, if any was flushed. 3883 * Returns -1 otherwise. 3884 */ 3885 3886 void 3887 socks_setbuffer(iobuffer_t *iobuf, const int mode, ssize_t bufsize); 3888 3889 void 3890 socks_setbufferfd(const int fd, const int mode, ssize_t bufsize); 3891 3892 /* 3893 * The above two functions perform the same operation, but one takes 3894 * a fd as the id to identify the iobuf and results in a no-op if no iobuf 3895 * is allocated to the fd, while the other takes the iobuf directly. 3896 * 3897 * Sets a flag in the iobuf belonging to "fd", indicating data should 3898 * not be be written before a flush is done, the buffer becomes full, 3899 * or "another good reason" is given, according to "mode". 3900 * "mode" can take the same values as the corresponding argument 3901 * to setvbuf(3). 3902 * 3903 * "bufsize" is the size of buffer to use. "bufsize" for the read buffer 3904 * and "bufsize" for the writebuffer. Can not be larger than SOCKD_BUFSIZE. 3905 * Use -1 for a default value (SOCKD_BUFSIZE). 3906 */ 3907 3908 size_t socks_addtobuffer(const int s, const whichbuf_t which, 3909 const int encoded, const void *data, 3910 const size_t datalen) 3911 __ATTRIBUTE__((__BOUNDED__(__buffer__, 4, 5))); 3912 /* 3913 * Adds "data", of length "datalen" to the buffer belonging to "s". 3914 * "which" must have one of the values WRITE_BUF or READ_BUF, to 3915 * indicate what part of the buffer to add the data to; 3916 * READ_BUF : data that has been read from the socket. 3917 * WRITE_BUF: data that should be written to the socket. 3918 * 3919 * Returns the number of bytes added. 3920 */ 3921 3922 size_t 3923 socks_getfrombuffer(const int s, const size_t flags, const whichbuf_t which, 3924 const int encoded, void *data, size_t datalen) 3925 __ATTRIBUTE__((__BOUNDED__(__buffer__, 5, 6))); 3926 3927 /* 3928 * Copies up to "datalen" bytes from the iobuf belonging to "s". 3929 * 3930 * Flags can be either 0 or MSG_PEEK. If MSG_PEEK, the data read 3931 * from the buffer will not be removed. 3932 * 3933 * "which" must have one of the values WRITE_BUF or READ_BUF, to 3934 * indicate what part of the buffer to copy the data from. 3935 * 3936 * Returns the number of bytes copied. 3937 */ 3938 3939 size_t 3940 socks_bytesinbuffer(const int s, const whichbuf_t which, const int encoded); 3941 /* 3942 * Returns the number of bytes currently in the iobuf belonging to "s". 3943 */ 3944 3945 int 3946 socks_bufferhasbytes(const int s, const whichbuf_t which); 3947 /* 3948 * Returns true if any of the buffers (encoded or decoded) belonging 3949 * to "s" has data in it. 3950 * Intended to be faster than calling socks_bytesinbuffer() twice, 3951 * once for each buffer (encoded/decoded). 3952 */ 3953 3954 size_t 3955 socks_freeinbuffer(const int s, const whichbuf_t which); 3956 /* 3957 * Returns the number of bytes free in the iobuf belonging to "s". 3958 */ 3959 3960 size_t 3961 socks_buffersize(const int s, const whichbuf_t which); 3962 /* 3963 * Returns the total size of the buffer belonging to "s". 3964 */ 3965 3966 3967 #if HAVE_LIVEDEBUG 3968 3969 void 3970 socks_flushrb(void); 3971 /* 3972 * Flushes the ringbuffer to log(s). 3973 */ 3974 3975 #endif /* HAVE_LIVEDEBUG */ 3976 3977 3978 fd_set * 3979 allocate_maxsize_fdset(void); 3980 /* 3981 * Allocate a fd_set big enough to hold the highest file descriptor 3982 * we could possibly use. 3983 * Returns a pointer to the allocated fd_set, or exits on failure. 3984 */ 3985 3986 rlim_t 3987 getmaxofiles(limittype_t type); 3988 /* 3989 * Return max number of open files for process. 3990 * If type is softlimit, the current limit is returned. 3991 * If type is hardlimit, the absolute maximum value is returned. 3992 */ 3993 3994 char * 3995 socks_getusername(const sockshost_t *host, char *buf, size_t buflen) 3996 __ATTRIBUTE__((__BOUNDED__(__string__, 2, 3))); 3997 /* 3998 * Tries to determine the username of the current user, to be used 3999 * when negotiating with the server "host". 4000 * The NUL-terminated username is written to "buf", which is of size 4001 * "buflen". 4002 * Returns: 4003 * On success: pointer to "buf" with the username. 4004 * On failure: NULL. 4005 */ 4006 4007 char * 4008 socks_getpassword(const sockshost_t *host, const char *user, 4009 char *buf, size_t buflen); 4010 /* 4011 * Tries to determine the password of user "user", to be used 4012 * when negotiating with the server "host". 4013 * The NUL-terminated password is written to "buf", which is of length 4014 * "buflen" 4015 * Returns: 4016 * On success: pointer to "buf" with the password. 4017 * On failure: NULL. 4018 */ 4019 4020 char * 4021 socks_getenv(const char *name, value_t value); 4022 /* 4023 * Depending on how the program was ./configured and on what 4024 * platform it runs, getenv(3) may or may not be disabled for 4025 * some names, for security reasons. 4026 * 4027 * This wrapper will return NULL if getenv(3) is disabled, 4028 * otherwise it will return the result of getenv(3). 4029 * 4030 * In addition, if "value" is not "dontcare", the function will 4031 * also compare the value returned by getenv(3), if any, to 4032 * see it it matches the value described by "value". If they don't 4033 * match, the function will return NULL. 4034 */ 4035 4036 int 4037 socks_msghaserrors(const char *prefix, const struct msghdr *msg); 4038 /* 4039 * Checks if "msg", as received via recvmsg(2), was truncated or 4040 * had other detectable errors, and reports it if so. 4041 * If reporting, "prefix" should contain information about where 4042 * the message was received. 4043 * 4044 * Returns true if "msg" has errors, "false" if not. 4045 */ 4046 4047 void seconds2days(unsigned long *seconds, unsigned long *days, 4048 unsigned long *hours, unsigned long *minutes); 4049 /* 4050 * Converts "seconds" to the corresponding number of days, hours, minutes, 4051 * and seconds. 4052 * Upon return, the days, hours, minutes, and seconds are stored in the 4053 * passed arguments. 4054 */ 4055 4056 void 4057 showconfig(const struct config *config); 4058 /* 4059 * prints out config "config". 4060 */ 4061 4062 void 4063 sockopts_dump(void); 4064 /* 4065 * list all known socket option information 4066 */ 4067 4068 const sockopt_t * 4069 optname2sockopt(char *optname); 4070 /* 4071 * return pointer to the socket option with the given name or NULL on failure. 4072 */ 4073 4074 const sockopt_t * 4075 optval2sockopt(int level, int optval); 4076 /* 4077 * return pointer to the socket option with the the name "optname" 4078 * at the socket level "level", or NULL if no such option is known at 4079 * the given socket level. 4080 */ 4081 4082 const sockopt_t * 4083 optid2sockopt(size_t optid); 4084 /* 4085 * return a pointer to the sockopt_t entry identified by "optid". 4086 */ 4087 4088 const sockoptvalsym_t * 4089 optval2valsym(size_t optid, char *name); 4090 /* 4091 * returns a pointer to the sockoptvalsym entry if "name" is a valid symbolic 4092 * name for the socketoption indicated by "optid", or NULL if no matching 4093 * entry is found. 4094 */ 4095 4096 #if HAVE_SOCKS_HOSTID 4097 unsigned char 4098 getsockethostid(const int s, const size_t addrc, struct in_addr addrv[]); 4099 /* 4100 * Gets the hostids set on socket "s" and stores them in "addrv", which must 4101 * be big enough to hold at least "addrc" elements. 4102 * 4103 * Returns the number of hostids set on socket "s". 4104 * If none are set, 0 is returned. 4105 */ 4106 4107 int 4108 setsockethostid(const int s, const size_t addrc, struct in_addr addrv[]); 4109 /* 4110 * Sets the hostids in "addrv", which contains "addrc" hostids, on socket 4111 * "s". 4112 * 4113 * Returns 0 on success, -1 on failure. 4114 */ 4115 #endif /* HAVE_SOCKS_HOSTID */ 4116 4117 4118 #if COVENANT 4119 char *socks_decode_base64(char *in, char *out, size_t outlen); 4120 char *socks_strcasestr(const char *a, const char *b); 4121 #endif /* COVENANT */ 4122 4123 #if HAVE_GETNAMEINFO && HAVE_PRELOAD 4124 4125 HAVE_PROT_GETNAMEINFO_0 4126 sys_getnameinfo(HAVE_PROT_GETNAMEINFO_1 sa, HAVE_PROT_GETNAMEINFO_2 salen, 4127 HAVE_PROT_GETNAMEINFO_3 host, HAVE_PROT_GETNAMEINFO_4 hostlen, 4128 HAVE_PROT_GETNAMEINFO_5 serv, HAVE_PROT_GETNAMEINFO_6 servlen, 4129 HAVE_PROT_GETNAMEINFO_7 flags); 4130 4131 #endif /* HAVE_GETNAMEINFO && HAVE_PRELOAD */ 4132 4133 #if SOCKS_CLIENT 4134 4135 #include "socks.h" 4136 4137 #else /* SOCKS_SERVER */ 4138 4139 #include "sockd.h" 4140 4141 #endif /* SOCKS_SERVER */ 4142 4143 #include "interposition.h" 4144 #include "tostring.h" 4145 #include "fmt.h" 4146 4147 #if HAVE_GSSAPI 4148 #include "socks_gssapi.h" 4149 #endif /* HAVE_GSSAPI */ 4150 4151 #if HAVE_KRB5 4152 4153 #if !SOCKS_CLIENT 4154 4155 #include "socks_krb5.h" 4156 4157 #endif /* !SOCKS_CLIENT */ 4158 4159 #endif /* HAVE_KRB5 */ 4160 4161 void 4162 slogstack(void); 4163 /* 4164 * Prints the current stack. 4165 */ 4166 4167 int 4168 socks_getifaddrs(struct ifaddrs **ifap); 4169 /* 4170 * Wrapper around getifaddrs(3) that does some extra work that should 4171 * not cause any problems. 4172 */ 4173 4174 4175 int 4176 socks_inet_pton(const int af, const void *src, void *dst, uint32_t *dstscope); 4177 /* 4178 * Like inet_pton(3), but calls getaddrinfo(3) to get the address instead 4179 * if "src" contains something that looks like a scope id (%id). If so, 4180 * the scopeid is stored in "dstscope", provided "dstscope" is not NULL. 4181 * 4182 * Returns the same values as inet_pton(). 4183 */ 4184 4185 void 4186 set_hints_ai_family(int *ai_family); 4187 /* 4188 * Sets the "ai_family" member of a strut addrinfo "hints" object 4189 * appropriately for our use, according to whether we have usable 4190 * IPv6 addresses configured or not. 4191 */ 4192 4193 int 4194 makedummyfd(const sa_family_t safamily, const int socktype); 4195 /* 4196 * Creates a dummy socket of the appropriate type, or the easiest/fastest 4197 * type if both safamily and socktype are zero. 4198 */ 4199 4200 4201 /* 4202 * Makes a dummy filedescriptor and returns it's index, or -1 on failure. 4203 */ 4204 4205 #if DEBUG 4206 4207 void 4208 printsocketopts(const int s); 4209 /* 4210 * prints socket options and other flags set on the socket "s". 4211 */ 4212 4213 int 4214 fd_isset(int fd, fd_set *fdset); 4215 /* function version of FD_ISSET() */ 4216 4217 #endif /* DEBUG */ 4218 4219 #endif /* !_COMMON_H_ */ 4220