Debian Codegraph @

src/network.c

raw
1 /*
2 * stunnel TLS offloading and load-balancing proxy
3 * Copyright (C) 1998-2026 Michal Trojnara <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, see <http://www.gnu.org/licenses>.
17 *
18 * Linking stunnel statically or dynamically with other modules is making
19 * a combined work based on stunnel. Thus, the terms and conditions of
20 * the GNU General Public License cover the whole combination.
21 *
22 * In addition, as a special exception, the copyright holder of stunnel
23 * gives you permission to combine stunnel with free software programs or
24 * libraries that are released under the GNU LGPL and with code included
25 * in the standard release of OpenSSL under the OpenSSL License (or
26 * modified versions of such code, with unchanged license). You may copy
27 * and distribute such a system following the terms of the GNU GPL for
28 * stunnel and the licenses of the other code concerned.
29 *
30 * Note that people who make modified versions of stunnel are not obligated
31 * to grant this special exception for their modified versions; it is their
32 * choice whether to do so. The GNU General Public License gives permission
33 * to release a modified version without this exception; this exception
34 * also makes it possible to release a modified version which carries
35 * forward this exception.
36 */
37
38 #if defined(_WIN32) || defined(_WIN32_WCE)
39 /* bypass automatic index bound checks in the FD_SET() macro */
40 #define FD_SETSIZE 1000000
41 #endif
42
43 #include "prototypes.h"
44
45 #define FDS_INITIAL_CAPACITY 4
46 /* #define DEBUG_UCONTEXT */
47
48 NOEXPORT void s_poll_realloc(s_poll_set *, unsigned);
49 #ifndef USE_UCONTEXT
50 NOEXPORT void check_terminate(s_poll_set *);
51 #endif
52
53 /**************************************** s_poll functions */
54
55 #ifdef USE_POLL
56
57 s_poll_set *s_poll_alloc(void) {
58 /* it needs to be filled with zeros */
59 return str_alloc(sizeof(s_poll_set));
60 }
61
62 void s_poll_free(s_poll_set *fds) {
63 if(fds) {
64 str_free(fds->ufds);
65 str_free(fds);
66 }
67 }
68
69 void s_poll_init(s_poll_set *fds, int main_thread) {
70 fds->nfds=0;
71 s_poll_realloc(fds, FDS_INITIAL_CAPACITY);
72 fds->main_thread=main_thread;
73 #ifdef USE_TERMINATE_PIPE
74 s_poll_add(fds, main_thread ? signal_pipe[0] : terminate_pipe[0], 1, 0);
75 #else
76 if(main_thread)
77 s_poll_add(fds, signal_pipe[0], 1, 0);
78 #endif
79 }
80
81 void s_poll_add(s_poll_set *fds, SOCKET fd, int rd, int wr) {
82 unsigned i;
83
84 for(i=0; i<fds->nfds && fds->ufds[i].fd!=fd; i++)
85 ;
86 if(i==fds->nfds) { /* not found */
87 if(i==fds->capacity)
88 s_poll_realloc(fds, i+1);
89 fds->ufds[i].fd=fd;
90 fds->ufds[i].events=0;
91 fds->nfds++;
92 }
93 if(rd) {
94 fds->ufds[i].events|=POLLIN;
95 #ifdef POLLRDHUP
96 fds->ufds[i].events|=POLLRDHUP;
97 #endif
98 }
99 if(wr)
100 fds->ufds[i].events|=POLLOUT;
101 }
102
103 void s_poll_remove(s_poll_set *fds, SOCKET fd) {
104 unsigned i;
105
106 for(i=0; i<fds->nfds && fds->ufds[i].fd!=fd; i++)
107 ;
108 if(i<fds->nfds) { /* found */
109 memmove(fds->ufds+i, fds->ufds+i+1,
110 (fds->nfds-i-1)*sizeof(struct pollfd));
111 fds->nfds--;
112 }
113 }
114
115 int s_poll_canread(s_poll_set *fds, SOCKET fd) {
116 unsigned i;
117
118 for(i=0; i<fds->nfds; i++)
119 if(fds->ufds[i].fd==fd)
120 return fds->ufds[i].revents&(POLLIN|POLLERR);
121 return 0; /* not listed in fds */
122 }
123
124 int s_poll_canwrite(s_poll_set *fds, SOCKET fd) {
125 unsigned i;
126
127 for(i=0; i<fds->nfds; i++)
128 if(fds->ufds[i].fd==fd)
129 return fds->ufds[i].revents&(POLLOUT|POLLERR);
130 return 0; /* not listed in fds */
131 }
132
133 /* best doc: http://lxr.free-electrons.com/source/net/ipv4/tcp.c#L456 */
134
135 int s_poll_hup(s_poll_set *fds, SOCKET fd) {
136 unsigned i;
137
138 for(i=0; i<fds->nfds; i++)
139 if(fds->ufds[i].fd==fd)
140 return fds->ufds[i].revents&POLLHUP; /* read and write closed */
141 return 0; /* not listed in fds */
142 }
143
144 int s_poll_rdhup(s_poll_set *fds, SOCKET fd) {
145 unsigned i;
146
147 for(i=0; i<fds->nfds; i++)
148 if(fds->ufds[i].fd==fd)
149 #ifdef POLLRDHUP
150 return fds->ufds[i].revents&POLLRDHUP; /* read closed */
151 #else
152 return fds->ufds[i].revents&POLLHUP; /* read and write closed */
153 #endif
154 return 0; /* not listed in fds */
155 }
156
157 int s_poll_err(s_poll_set *fds, SOCKET fd) {
158 unsigned i;
159
160 for(i=0; i<fds->nfds; i++)
161 if(fds->ufds[i].fd==fd)
162 return fds->ufds[i].revents&POLLERR;
163 return 0; /* not listed in fds */
164 }
165
166 NOEXPORT void s_poll_realloc(s_poll_set *fds, unsigned capacity) {
167 fds->capacity=capacity;
168 fds->ufds=str_realloc(fds->ufds, capacity*sizeof(struct pollfd));
169 }
170
171 void s_poll_dump(s_poll_set *fds, int level) {
172 unsigned i;
173
174 for(i=0; i<fds->nfds; i++)
175 s_log(level, "FD=%ld events=0x%X revents=0x%X",
176 (long)fds->ufds[i].fd, fds->ufds[i].events, fds->ufds[i].revents);
177 }
178
179 #ifdef USE_UCONTEXT
180
181 /* move ready contexts from waiting queue to ready queue */
182 NOEXPORT void scan_waiting_queue(void) {
183 int retval;
184 CONTEXT *context, *prev;
185 int min_timeout;
186 unsigned nfds, i;
187 time_t now;
188 static unsigned max_nfds=0;
189 static struct pollfd *ufds=NULL;
190
191 time(&now);
192 /* count file descriptors */
193 min_timeout=-1; /* infinity */
194 nfds=0;
195 for(context=waiting_head; context; context=context->next) {
196 nfds+=context->fds->nfds;
197 if(context->finish>=0) /* finite time */
198 if(min_timeout<0 || min_timeout>context->finish-now)
199 min_timeout=
200 (int)(context->finish-now<0 ? 0 : context->finish-now);
201 }
202 /* setup ufds structure */
203 if(nfds>max_nfds) { /* need to allocate more memory */
204 ufds=str_realloc(ufds, nfds*sizeof(struct pollfd));
205 max_nfds=nfds;
206 }
207 nfds=0;
208 for(context=waiting_head; context; context=context->next)
209 for(i=0; i<context->fds->nfds; i++) {
210 ufds[nfds].fd=context->fds->ufds[i].fd;
211 ufds[nfds].events=context->fds->ufds[i].events;
212 nfds++;
213 }
214
215 #ifdef DEBUG_UCONTEXT
216 s_log(LOG_DEBUG, "Waiting %d second(s) for %d file descriptor(s)",
217 min_timeout, nfds);
218 #endif
219 do { /* skip "Interrupted system call" errors */
220 retval=poll(ufds, nfds, min_timeout<0 ? -1 : 1000*min_timeout);
221 } while(retval<0 && get_last_socket_error()==S_EINTR);
222 time(&now);
223 /* process the returned data */
224 nfds=0;
225 prev=NULL; /* previous element of the waiting queue */
226 context=waiting_head;
227 while(context) {
228 context->ready=0;
229 /* count ready file descriptors in each context */
230 for(i=0; i<context->fds->nfds; i++) {
231 context->fds->ufds[i].revents=ufds[nfds].revents;
232 #ifdef DEBUG_UCONTEXT
233 s_log(LOG_DEBUG, "CONTEXT %ld, FD=%ld,%s%s ->%s%s%s%s%s",
234 context->id, (long)ufds[nfds].fd,
235 (ufds[nfds].events & POLLIN) ? " IN" : "",
236 (ufds[nfds].events & POLLOUT) ? " OUT" : "",
237 (ufds[nfds].revents & POLLIN) ? " IN" : "",
238 (ufds[nfds].revents & POLLOUT) ? " OUT" : "",
239 (ufds[nfds].revents & POLLERR) ? " ERR" : "",
240 (ufds[nfds].revents & POLLHUP) ? " HUP" : "",
241 (ufds[nfds].revents & POLLNVAL) ? " NVAL" : "");
242 #endif
243 if(ufds[nfds].revents)
244 context->ready++;
245 nfds++;
246 }
247 if(context->ready || (context->finish>=0 && context->finish<=now)) {
248 /* remove context from the waiting queue */
249 if(prev)
250 prev->next=context->next;
251 else
252 waiting_head=context->next;
253 if(!context->next) /* same as context==waiting_tail */
254 waiting_tail=prev;
255
256 /* append context context to the ready queue */
257 context->next=NULL;
258 if(ready_tail)
259 ready_tail->next=context;
260 ready_tail=context;
261 if(!ready_head)
262 ready_head=context;
263 } else { /* leave the context context in the waiting queue */
264 prev=context;
265 }
266 context=prev ? prev->next : waiting_head;
267 }
268 }
269
270 int s_poll_wait(s_poll_set *fds, int sec, int msec) {
271 CONTEXT *context; /* current context */
272 static CONTEXT *to_free=NULL; /* delayed memory deallocation */
273
274 /* FIXME: msec parameter is currently ignored with UCONTEXT threads */
275 (void)msec; /* squash the unused parameter warning */
276
277 /* remove the current context from ready queue */
278 context=ready_head;
279 ready_head=ready_head->next;
280 if(!ready_head) /* the queue is empty */
281 ready_tail=NULL;
282 /* it is safe to s_log() after new ready_head is set */
283
284 /* it is illegal to deallocate the stack of the current context */
285 if(to_free) { /* a delayed deallocation is scheduled */
286 #ifdef DEBUG_UCONTEXT
287 s_log(LOG_DEBUG, "Releasing context %ld", to_free->id);
288 #endif
289 str_free(to_free->stack);
290 str_free(to_free);
291 to_free=NULL;
292 }
293
294 /* manage the current thread */
295 if(fds) { /* something to wait for -> swap the context */
296 context->fds=fds; /* set file descriptors to wait for */
297 context->finish=sec<0 ? -1 : time(NULL)+sec;
298
299 /* append the current context to the waiting queue */
300 context->next=NULL;
301 if(waiting_tail)
302 waiting_tail->next=context;
303 waiting_tail=context;
304 if(!waiting_head)
305 waiting_head=context;
306 } else { /* nothing to wait for -> drop the context */
307 to_free=context; /* schedule for delayed deallocation */
308 }
309
310 while(!ready_head) /* wait until there is a thread to switch to */
311 scan_waiting_queue();
312
313 /* switch threads */
314 if(fds) { /* swap the current context */
315 if(context->id!=ready_head->id) {
316 #ifdef DEBUG_UCONTEXT
317 s_log(LOG_DEBUG, "Context swap: %ld -> %ld",
318 context->id, ready_head->id);
319 #endif
320 swapcontext(&context->context, &ready_head->context);
321 #ifdef DEBUG_UCONTEXT
322 s_log(LOG_DEBUG, "Current context: %ld", ready_head->id);
323 #endif
324 }
325 return ready_head->ready;
326 } else { /* drop the current context */
327 #ifdef DEBUG_UCONTEXT
328 s_log(LOG_DEBUG, "Context set: %ld (dropped) -> %ld",
329 context->id, ready_head->id);
330 #endif
331 setcontext(&ready_head->context);
332 ioerror("setcontext"); /* should not ever happen */
333 return 0;
334 }
335 }
336
337 #else /* USE_UCONTEXT */
338
339 int s_poll_wait(s_poll_set *fds, int sec, int msec) {
340 int retval;
341
342 if(!fds)
343 fatal("NULL fds is only allowed with UCONTEXT threads");
344 do { /* skip "Interrupted system call" errors */
345 retval=poll(fds->ufds, fds->nfds, sec<0 ? -1 : 1000*sec+msec);
346 } while(retval<0 && get_last_socket_error()==S_EINTR);
347 if(retval>0)
348 check_terminate(fds);
349 return retval;
350 }
351
352 #endif /* USE_UCONTEXT */
353
354 #else /* select */
355
356 s_poll_set *s_poll_alloc(void) {
357 /* it needs to be filled with zeros */
358 return str_alloc(sizeof(s_poll_set));
359 }
360
361 void s_poll_free(s_poll_set *fds) {
362 if(fds) {
363 str_free(fds->irfds);
364 str_free(fds->orfds);
365 str_free(fds->iwfds);
366 str_free(fds->owfds);
367 #ifndef USE_WIN32
368 str_free(fds->ixfds);
369 str_free(fds->oxfds);
370 #endif
371 str_free(fds);
372 }
373 }
374
375 void s_poll_init(s_poll_set *fds, int main_thread) {
376 s_poll_realloc(fds, FDS_INITIAL_CAPACITY);
377 FD_ZERO(fds->irfds);
378 FD_ZERO(fds->iwfds);
379 #ifndef USE_WIN32
380 FD_ZERO(fds->ixfds);
381 #endif
382 fds->max=0; /* no file descriptors */
383 fds->main_thread=main_thread;
384 #ifdef USE_TERMINATE_PIPE
385 s_poll_add(fds, main_thread ? signal_pipe[0] : terminate_pipe[0], 1, 0);
386 #else
387 if(main_thread)
388 s_poll_add(fds, signal_pipe[0], 1, 0);
389 #endif
390 }
391
392 void s_poll_add(s_poll_set *fds, SOCKET fd, int rd, int wr) {
393 #ifdef USE_WIN32
394 unsigned max_count=fds->irfds->fd_count > fds->iwfds->fd_count ?
395 fds->irfds->fd_count : fds->iwfds->fd_count;
396
397 if(max_count>=fds->capacity)
398 s_poll_realloc(fds, max_count+1);
399 #endif
400 if(rd)
401 FD_SET(fd, fds->irfds);
402 if(wr)
403 FD_SET(fd, fds->iwfds);
404 #ifndef USE_WIN32
405 /* expect errors (and the Spanish Inquisition) except for WIN32,
406 * which signals tons of non-error events on exceptfds */
407 FD_SET(fd, fds->ixfds);
408 #endif
409 if(fd>fds->max)
410 fds->max=fd;
411 }
412
413 void s_poll_remove(s_poll_set *fds, SOCKET fd) {
414 FD_CLR(fd, fds->irfds);
415 FD_CLR(fd, fds->iwfds);
416 #ifndef USE_WIN32
417 FD_CLR(fd, fds->ixfds);
418 #endif
419 }
420
421 int s_poll_canread(s_poll_set *fds, SOCKET fd) {
422 #ifdef USE_WIN32
423 return FD_ISSET(fd, fds->orfds);
424 #else
425 return FD_ISSET(fd, fds->orfds) || FD_ISSET(fd, fds->oxfds);
426 #endif
427 }
428
429 int s_poll_canwrite(s_poll_set *fds, SOCKET fd) {
430 #ifdef USE_WIN32
431 return FD_ISSET(fd, fds->owfds);
432 #else
433 return FD_ISSET(fd, fds->owfds) || FD_ISSET(fd, fds->oxfds);
434 #endif
435 }
436
437 int s_poll_hup(s_poll_set *fds, SOCKET fd) {
438 (void)fds; /* squash the unused parameter warning */
439 (void)fd; /* squash the unused parameter warning */
440 return 0; /* FIXME: how to detect the HUP condition with select()? */
441 }
442
443 int s_poll_rdhup(s_poll_set *fds, SOCKET fd) {
444 (void)fds; /* squash the unused parameter warning */
445 (void)fd; /* squash the unused parameter warning */
446 return 0; /* FIXME: how to detect the RDHUP condition with select()? */
447 }
448
449 int s_poll_err(s_poll_set *fds, SOCKET fd) {
450 #ifdef USE_WIN32
451 (void)fds; /* squash the unused parameter warning */
452 (void)fd; /* squash the unused parameter warning */
453 return 0;
454 #else
455 return FD_ISSET(fd, fds->oxfds);
456 #endif
457 }
458
459 #ifdef USE_WIN32
460 #define FD_SIZE(fds) (offsetof(fd_set, fd_array)+(fds)->capacity*sizeof(SOCKET))
461 #else
462 #define FD_SIZE(fds) (sizeof(fd_set))
463 #endif
464
465 int s_poll_wait(s_poll_set *fds, int sec, int msec) {
466 int retval;
467 struct timeval tv, *tv_ptr;
468
469 if(!fds)
470 fatal("NULL fds is only allowed with UCONTEXT threads");
471 do { /* skip "Interrupted system call" errors */
472 memcpy(fds->orfds, fds->irfds, FD_SIZE(fds));
473 memcpy(fds->owfds, fds->iwfds, FD_SIZE(fds));
474 #ifndef USE_WIN32
475 memcpy(fds->oxfds, fds->ixfds, FD_SIZE(fds));
476 #endif
477 if(sec<0) { /* infinite timeout */
478 tv_ptr=NULL;
479 } else {
480 tv.tv_sec=sec;
481 tv.tv_usec=1000*msec;
482 tv_ptr=&tv;
483 }
484 #ifdef USE_WIN32
485 retval=select((int)fds->max+1,
486 fds->orfds, fds->owfds, NULL, tv_ptr);
487 #else
488 retval=select((int)fds->max+1,
489 fds->orfds, fds->owfds, fds->oxfds, tv_ptr);
490 #endif
491 } while(retval<0 && get_last_socket_error()==S_EINTR);
492 if(retval>0)
493 check_terminate(fds);
494 return retval;
495 }
496
497 NOEXPORT void s_poll_realloc(s_poll_set *fds, unsigned capacity) {
498 #ifdef USE_WIN32
499 fds->capacity=capacity;
500 #else
501 (void)capacity; /* squash the unused parameter warning */
502 #endif
503 fds->irfds=str_realloc(fds->irfds, FD_SIZE(fds));
504 fds->orfds=str_realloc(fds->orfds, FD_SIZE(fds));
505 fds->iwfds=str_realloc(fds->iwfds, FD_SIZE(fds));
506 fds->owfds=str_realloc(fds->owfds, FD_SIZE(fds));
507 #ifndef USE_WIN32
508 fds->ixfds=str_realloc(fds->ixfds, FD_SIZE(fds));
509 fds->oxfds=str_realloc(fds->oxfds, FD_SIZE(fds));
510 #endif
511 }
512
513 void s_poll_dump(s_poll_set *fds, int level) {
514 SOCKET fd;
515 int ir, or, iw, ow;
516 #ifndef USE_WIN32
517 int ix, ox;
518 #endif
519
520 for(fd=0; fd<fds->max+1; fd++) {
521 ir=FD_ISSET(fd, fds->irfds);
522 iw=FD_ISSET(fd, fds->iwfds);
523 #ifndef USE_WIN32
524 ix=FD_ISSET(fd, fds->ixfds);
525 #endif
526 or=FD_ISSET(fd, fds->orfds);
527 ow=FD_ISSET(fd, fds->owfds);
528 #ifndef USE_WIN32
529 ox=FD_ISSET(fd, fds->oxfds);
530 if(ir || iw || ix || or || ow || ox)
531 s_log(level, "FD=%ld ifds=%c%c%c ofds=%c%c%c", (long)fd,
532 ir?'r':'-', iw?'w':'-', ix?'x':'-',
533 or?'r':'-', ow?'w':'-', ox?'x':'-');
534 #else
535 if(ir || iw || or || ow)
536 s_log(level, "FD=%ld ifds=%c%c ofds=%c%c", (long)fd,
537 ir?'r':'-', iw?'w':'-', or?'r':'-', ow?'w':'-');
538 #endif
539 }
540 }
541
542 #endif /* USE_POLL */
543
544 void s_poll_sleep(int sec, int msec) {
545 #ifdef USE_WIN32
546 Sleep(1000*(DWORD)sec+(DWORD)msec);
547 #else
548 s_poll_set *fds=s_poll_alloc();
549 s_poll_init(fds, 0);
550 s_poll_wait(fds, sec, msec);
551 s_poll_free(fds);
552 #endif
553 }
554
555 #ifndef USE_UCONTEXT
556 NOEXPORT void check_terminate(s_poll_set *fds) {
557 #ifdef USE_TERMINATE_PIPE
558 if(!fds->main_thread && s_poll_canread(fds, terminate_pipe[0])) {
559 #ifdef USE_PTHREAD
560 pthread_exit(NULL);
561 #endif /* USE_PTHREAD */
562 #if defined(USE_WIN32) || defined(USE_OS2)
563 #if defined(_WIN32_WCE)
564 /* FIXME */
565 #else /* !_WIN32_WCE */
566 _endthreadex(0);
567 #endif /* _WIN32_WCE */
568 #endif /* USE_WIN32 || USE_OS2 */
569 #ifdef USE_UCONTEXT
570 /* currently unused */
571 s_poll_wait(NULL, 0, 0); /* wait on poll() */
572 #endif /* USE_UCONTEXT */
573 #ifdef USE_FORK
574 exit(0);
575 #endif /* USE_FORK */
576 }
577 #else /* USE_TERMINATE_PIPE */
578 (void)fds; /* squash the unused parameter warning */
579 #endif /* USE_TERMINATE_PIPE */
580 }
581 #endif
582
583 /**************************************** fd management */
584
585 int socket_options_set(SERVICE_OPTIONS *service, SOCKET s, int type) {
586 SOCK_OPT *ptr;
587 static const char *type_str[3]={"accept", "local", "remote"};
588 socklen_t opt_size;
589 int retval=0; /* no error found */
590
591 s_log(LOG_DEBUG, "Setting %s socket options (FD=%ld)",
592 type_str[type], (long)s);
593 for(ptr=service->sock_opts; ptr->opt_str; ptr++) {
594 if(!ptr->opt_val[type])
595 continue; /* default */
596 switch(ptr->opt_type) {
597 case TYPE_LINGER:
598 opt_size=sizeof(struct linger);
599 break;
600 case TYPE_TIMEVAL:
601 opt_size=sizeof(struct timeval);
602 break;
603 case TYPE_STRING:
604 opt_size=(socklen_t)strlen(ptr->opt_val[type]->c_val)+1;
605 break;
606 default:
607 opt_size=sizeof(int);
608 }
609 if(setsockopt(s, ptr->opt_level, ptr->opt_name,
610 (void *)ptr->opt_val[type], opt_size)) {
611 if(get_last_socket_error()==S_EOPNOTSUPP) {
612 /* most likely stdin/stdout or AF_UNIX socket */
613 s_log(LOG_DEBUG,
614 "Option %s not supported on %s socket",
615 ptr->opt_str, type_str[type]);
616 } else {
617 sockerror(ptr->opt_str);
618 retval=-1; /* failed to set this option */
619 }
620 }
621 else {
622 s_log(LOG_DEBUG, "Option %s set on %s socket",
623 ptr->opt_str, type_str[type]);
624 }
625 }
626 return retval; /* returns 0 when all options succeeded */
627 }
628
629 int get_socket_error(const SOCKET fd) {
630 int err;
631 socklen_t optlen=sizeof err;
632
633 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&err, &optlen))
634 err=get_last_socket_error(); /* failed -> ask why */
635 return err==S_ENOTSOCK ? 0 : err;
636 }
637
638 /**************************************** simulate blocking I/O */
639
640 int s_connect(CLI *c, SOCKADDR_UNION *addr, socklen_t addrlen, int timeout) {
641 int error;
642 char *dst;
643
644 dst=s_ntop(addr, addrlen);
645 s_log(LOG_INFO, "s_connect: connecting %s", dst);
646
647 if(!connect(c->fd, &addr->sa, addrlen)) {
648 s_log(LOG_INFO, "s_connect: connected %s", dst);
649 str_free(dst);
650 return 0; /* no error -> success (on some OSes over the loopback) */
651 }
652 error=get_last_socket_error();
653 if(error!=S_EINPROGRESS && error!=S_EWOULDBLOCK) {
654 s_log(LOG_ERR, "s_connect: connect %s: %s (%d)",
655 dst, s_strerror(error), error);
656 str_free(dst);
657 return -1;
658 }
659
660 s_log(LOG_DEBUG, "s_connect: s_poll_wait %s: waiting %d seconds",
661 dst, timeout);
662 s_poll_init(c->fds, 0);
663 s_poll_add(c->fds, c->fd, 1, 1);
664 s_poll_dump(c->fds, LOG_DEBUG);
665 switch(s_poll_wait(c->fds, timeout, 0)) {
666 case -1:
667 error=get_last_socket_error();
668 s_log(LOG_ERR, "s_connect: s_poll_wait %s: %s (%d)",
669 dst, s_strerror(error), error);
670 str_free(dst);
671 return -1;
672 case 0:
673 s_log(LOG_ERR, "s_connect: s_poll_wait %s:"
674 " TIMEOUTconnect exceeded", dst);
675 str_free(dst);
676 return -1;
677 default:
678 error=get_socket_error(c->fd);
679 if(error) {
680 s_log(LOG_ERR, "s_connect: connect %s: %s (%d)",
681 dst, s_strerror(error), error);
682 str_free(dst);
683 return -1;
684 }
685 if(s_poll_canwrite(c->fds, c->fd)) {
686 s_log(LOG_NOTICE, "s_connect: connected %s", dst);
687 str_free(dst);
688 return 0; /* success */
689 }
690 s_log(LOG_ERR, "s_connect: s_poll_wait %s: internal error",
691 dst);
692 str_free(dst);
693 return -1;
694 }
695 }
696
697 void s_write(CLI *c, SOCKET fd, const void *buf, size_t len) {
698 /* simulate a blocking write */
699 const uint8_t *ptr=(const uint8_t *)buf;
700
701 while(len>0) {
702 ssize_t num;
703
704 s_poll_init(c->fds, 0);
705 s_poll_add(c->fds, fd, 0, 1); /* write */
706 switch(s_poll_wait(c->fds, c->opt->timeout_busy, 0)) {
707 case -1:
708 sockerror("s_write: s_poll_wait");
709 throw_exception(c, 1); /* error */
710 case 0:
711 s_log(LOG_INFO, "s_write: s_poll_wait:"
712 " TIMEOUTbusy exceeded: sending reset");
713 throw_exception(c, 1); /* timeout */
714 case 1:
715 break; /* OK */
716 default:
717 s_log(LOG_ERR, "s_write: s_poll_wait: unknown result");
718 throw_exception(c, 1); /* error */
719 }
720
721 num=writesocket(fd, (const void *)ptr, len);
722 if(num>=0) {
723 ptr+=(size_t)num;
724 len-=(size_t)num;
725 } else { /* error */
726 if(!socket_needs_retry(c, "s_write: writesocket"))
727 throw_exception(c, 1);
728 }
729 }
730 }
731
732 size_t s_read_eof(CLI *c, SOCKET fd, void *ptr, size_t len) {
733 /* simulate a blocking read */
734 /* return a value < len on EOF */
735 size_t total=0;
736
737 while(len>0) {
738 ssize_t num;
739
740 s_poll_init(c->fds, 0);
741 s_poll_add(c->fds, fd, 1, 0); /* read */
742 switch(s_poll_wait(c->fds, c->opt->timeout_busy, 0)) {
743 case -1:
744 sockerror("s_read_eof: s_poll_wait");
745 throw_exception(c, 1); /* error */
746 case 0:
747 s_log(LOG_INFO, "s_read_eof: s_poll_wait:"
748 " TIMEOUTbusy exceeded: sending reset");
749 throw_exception(c, 1); /* timeout */
750 case 1:
751 break; /* OK */
752 default:
753 s_log(LOG_ERR, "s_read_eof: s_poll_wait: unknown result");
754 throw_exception(c, 1); /* error */
755 }
756
757 num=readsocket(fd, (char *)ptr+total, len);
758 if(num>0) {
759 total+=(size_t)num;
760 len-=(size_t)num;
761 } else if(num==0) { /* EOF */
762 s_log(LOG_DEBUG, "s_read_eof: EOF");
763 break; /* EOF */
764 } else { /* error */
765 if(!socket_needs_retry(c, "s_read_eof: readsocket"))
766 break; /* EOF */
767 }
768 }
769 return total;
770 }
771
772 void s_read(CLI *c, SOCKET fd, void *ptr, size_t len) {
773 /* simulate a blocking read */
774 /* throw an exception on EOF */
775 size_t received=s_read_eof(c, fd, ptr, len);
776 if(received!=len) {
777 s_log(LOG_ERR, "s_read: Received %llu out of requested %llu byte(s)",
778 (unsigned long long)received, (unsigned long long)len);
779 throw_exception(c, 1);
780 }
781 }
782
783 void fd_putline(CLI *c, SOCKET fd, const char *line) {
784 char *tmpline;
785 const char crlf[]="\r\n";
786 size_t len;
787
788 tmpline=str_printf("%s%s", line, crlf);
789 len=strlen(tmpline);
790 s_write(c, fd, tmpline, len);
791 str_free(tmpline);
792 s_log(LOG_DEBUG, " -> %s", line);
793 }
794
795 char *fd_getline(CLI *c, SOCKET fd) {
796 char *line;
797 size_t ptr=0, allocated=32;
798
799 line=str_alloc(allocated);
800 for(;;) {
801 if(ptr>65536) { /* >64KB --> DoS protection */
802 s_log(LOG_ERR, "fd_getline: Line too long");
803 str_free(line);
804 throw_exception(c, 1);
805 }
806 if(allocated<ptr+1) {
807 allocated*=2;
808 line=str_realloc(line, allocated);
809 }
810 s_read(c, fd, line+ptr, 1);
811 if(line[ptr]=='\r')
812 continue;
813 if(line[ptr]=='\n')
814 break;
815 if(line[ptr]=='\0')
816 break;
817 ++ptr;
818 }
819 line[ptr]='\0';
820 s_log(LOG_DEBUG, " <- %s", line);
821 return line;
822 }
823
824 void fd_printf(CLI *c, SOCKET fd, const char *format, ...) {
825 va_list ap;
826 char *line;
827
828 va_start(ap, format);
829 line=str_vprintf(format, ap);
830 va_end(ap);
831 if(!line) {
832 s_log(LOG_ERR, "fd_printf: str_vprintf failed");
833 throw_exception(c, 1);
834 }
835 fd_putline(c, fd, line);
836 str_free(line);
837 }
838
839 void s_ssl_write(CLI *c, const void *buf, int len) {
840 /* simulate a blocking SSL_write */
841 const uint8_t *ptr=(const uint8_t *)buf;
842
843 while(len>0) {
844 int num, err;
845
846 s_poll_init(c->fds, 0);
847 s_poll_add(c->fds, c->ssl_wfd->fd, 0, 1); /* write */
848 switch(s_poll_wait(c->fds, c->opt->timeout_busy, 0)) {
849 case -1:
850 sockerror("s_ssl_write: s_poll_wait");
851 throw_exception(c, 1); /* error */
852 case 0:
853 s_log(LOG_INFO, "s_ssl_write: s_poll_wait:"
854 " TIMEOUTbusy exceeded: sending reset");
855 throw_exception(c, 1); /* timeout */
856 case 1:
857 break; /* OK */
858 default:
859 s_log(LOG_ERR, "s_ssl_write: s_poll_wait: unknown result");
860 throw_exception(c, 1); /* error */
861 }
862
863 num=SSL_write(c->ssl, (const void *)ptr, len);
864 err=SSL_get_error(c->ssl, num);
865 if(err==SSL_ERROR_NONE) {
866 ptr+=num;
867 len-=num;
868 } else if(err==SSL_ERROR_WANT_WRITE) {
869 s_log(LOG_DEBUG, "s_ssl_write: SSL_ERROR_WANT_WRITE: Retrying");
870 } else if(err==SSL_ERROR_SSL) {
871 ssl_error(c, "s_ssl_write: SSL_write");
872 throw_exception(c, 1);
873 } else if(err==SSL_ERROR_SYSCALL) {
874 if(!socket_needs_retry(c, "s_ssl_write: SSL_write")) {
875 SSL_set_shutdown(c->ssl,
876 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
877 break; /* EOF */
878 }
879 } else {
880 s_log(LOG_ERR, "s_ssl_write: Unhandled error %d", err);
881 throw_exception(c, 1);
882 }
883 }
884 }
885
886 size_t s_ssl_read_eof(CLI *c, void *ptr, int len) {
887 /* simulate a blocking SSL_read */
888 /* return a value < len on EOF */
889 size_t total=0;
890
891 while(len>0) {
892 int num, err;
893
894 if(!SSL_pending(c->ssl)) {
895 s_poll_init(c->fds, 0);
896 s_poll_add(c->fds, c->ssl_rfd->fd, 1, 0); /* read */
897 switch(s_poll_wait(c->fds, c->opt->timeout_busy, 0)) {
898 case -1:
899 sockerror("s_ssl_read_eof: s_poll_wait");
900 throw_exception(c, 1); /* error */
901 case 0:
902 s_log(LOG_INFO, "s_ssl_read_eof: s_poll_wait:"
903 " TIMEOUTbusy exceeded: sending reset");
904 throw_exception(c, 1); /* timeout */
905 case 1:
906 break; /* OK */
907 default:
908 s_log(LOG_ERR, "s_ssl_read_eof: s_poll_wait: unknown result");
909 throw_exception(c, 1); /* error */
910 }
911 }
912
913 num=SSL_read(c->ssl, (char *)ptr+total, len);
914 err=SSL_get_error(c->ssl, num);
915 if(err==SSL_ERROR_NONE) {
916 total+=(size_t)num;
917 len-=num;
918 } else if(err==SSL_ERROR_ZERO_RETURN) {
919 s_log(LOG_DEBUG, "s_ssl_read_eof: close_notify");
920 break; /* EOF */
921 } else if(err==SSL_ERROR_WANT_READ) {
922 s_log(LOG_DEBUG, "s_ssl_read_eof: SSL_ERROR_WANT_READ: Retrying");
923 } else if(err==SSL_ERROR_SSL) {
924 #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
925 /* OpenSSL 3.0 changed the method of reporting socket EOF */
926 if(ERR_GET_REASON(ERR_peek_error())==
927 SSL_R_UNEXPECTED_EOF_WHILE_READING) {
928 /* EOF -> buggy (e.g. Microsoft) peer:
929 * TLS socket closed without close_notify alert */
930 s_log(LOG_DEBUG, "s_ssl_read_eof: TLS socket closed");
931 SSL_set_shutdown(c->ssl,
932 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
933 break; /* EOF */
934 }
935 #endif /* SSL_R_UNEXPECTED_EOF_WHILE_READING */
936 ssl_error(c, "s_ssl_read_eof: SSL_read");
937 throw_exception(c, 1);
938 } else if(err==SSL_ERROR_SYSCALL) {
939 if(!socket_needs_retry(c, "s_ssl_read_eof: SSL_read")) {
940 SSL_set_shutdown(c->ssl,
941 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
942 break; /* EOF */
943 }
944 } else {
945 s_log(LOG_ERR, "s_ssl_read_oef: Unhandled error %d", err);
946 throw_exception(c, 1);
947 }
948 }
949 return total;
950 }
951
952 void s_ssl_read(CLI *c, void *ptr, int len) {
953 /* simulate a blocking SSL_read */
954 /* throw an exception on EOF */
955 size_t received=s_ssl_read_eof(c, ptr, len);
956 if(received!=(size_t)len) {
957 s_log(LOG_ERR, "s_ssl_read: Received %llu out of requested %d byte(s)",
958 (unsigned long long)received, len);
959 throw_exception(c, 1);
960 }
961 }
962
963 char *ssl_getstring(CLI *c) { /* get null-terminated string */
964 char *line;
965 size_t ptr=0, allocated=32;
966
967 line=str_alloc(allocated);
968 for(;;) {
969 if(ptr>65536) { /* >64KB --> DoS protection */
970 s_log(LOG_ERR, "ssl_getstring: Line too long");
971 str_free(line);
972 throw_exception(c, 1);
973 }
974 if(allocated<ptr+1) {
975 allocated*=2;
976 line=str_realloc(line, allocated);
977 }
978 s_ssl_read(c, line+ptr, 1);
979 if(line[ptr]=='\0')
980 break;
981 ++ptr;
982 }
983 return line;
984 }
985
986 char *ssl_getline(CLI *c) { /* get newline-terminated string */
987 char *line;
988 size_t ptr=0, allocated=32;
989
990 line=str_alloc(allocated);
991 for(;;) {
992 if(ptr>65536) { /* >64KB --> DoS protection */
993 s_log(LOG_ERR, "ssl_getline: Line too long");
994 str_free(line);
995 throw_exception(c, 1);
996 }
997 if(allocated<ptr+1) {
998 allocated*=2;
999 line=str_realloc(line, allocated);
1000 }
1001 s_ssl_read(c, line+ptr, 1);
1002 if(line[ptr]=='\r')
1003 continue;
1004 if(line[ptr]=='\n')
1005 break;
1006 if(line[ptr]=='\0')
1007 break;
1008 ++ptr;
1009 }
1010 line[ptr]='\0';
1011 s_log(LOG_DEBUG, " <- %s", line);
1012 return line;
1013 }
1014
1015 void ssl_putline(CLI *c, const char *line) { /* put newline-terminated string */
1016 char *tmpline;
1017 const char crlf[]="\r\n";
1018 size_t len;
1019
1020 tmpline=str_printf("%s%s", line, crlf);
1021 len=strlen(tmpline);
1022 if(len>INT_MAX) { /* paranoia */
1023 s_log(LOG_ERR, "ssl_putline: Line too long");
1024 str_free(tmpline);
1025 throw_exception(c, 1);
1026 }
1027 s_ssl_write(c, tmpline, (int)len);
1028 str_free(tmpline);
1029 s_log(LOG_DEBUG, " -> %s", line);
1030 }
1031
1032 void ssl_printf(CLI *c, const char *format, ...) {
1033 va_list ap;
1034 char *line;
1035
1036 va_start(ap, format);
1037 line=str_vprintf(format, ap);
1038 va_end(ap);
1039 if(!line) {
1040 s_log(LOG_ERR, "ssl_printf: str_vprintf failed");
1041 throw_exception(c, 1);
1042 }
1043 ssl_putline(c, line);
1044 str_free(line);
1045 }
1046
1047 /**************************************** network helpers */
1048
1049 #define INET_SOCKET_PAIR
1050
1051 int make_sockets(SOCKET fd[2]) { /* make a pair of connected ipv4 sockets */
1052 #ifdef INET_SOCKET_PAIR
1053 struct sockaddr_in addr;
1054 socklen_t addrlen;
1055 SOCKET s; /* temporary socket awaiting for connection */
1056
1057 /* create two *blocking* sockets first */
1058 s=s_socket(AF_INET, SOCK_STREAM, 0, 0, "make_sockets: s_socket#1");
1059 if(s==INVALID_SOCKET)
1060 return 1;
1061 fd[1]=s_socket(AF_INET, SOCK_STREAM, 0, 0, "make_sockets: s_socket#2");
1062 if(fd[1]==INVALID_SOCKET) {
1063 closesocket(s);
1064 return 1;
1065 }
1066
1067 addrlen=sizeof addr;
1068 memset(&addr, 0, sizeof addr);
1069 addr.sin_family=AF_INET;
1070 addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
1071 addr.sin_port=htons(0); /* dynamic port allocation */
1072 if(bind(s, (struct sockaddr *)&addr, addrlen))
1073 log_error(LOG_DEBUG, get_last_socket_error(), "make_sockets: bind#1");
1074 if(bind(fd[1], (struct sockaddr *)&addr, addrlen))
1075 log_error(LOG_DEBUG, get_last_socket_error(), "make_sockets: bind#2");
1076
1077 if(listen(s, 1)) {
1078 sockerror("make_sockets: listen");
1079 closesocket(s);
1080 closesocket(fd[1]);
1081 return 1;
1082 }
1083 if(getsockname(s, (struct sockaddr *)&addr, &addrlen)) {
1084 sockerror("make_sockets: getsockname");
1085 closesocket(s);
1086 closesocket(fd[1]);
1087 return 1;
1088 }
1089 if(connect(fd[1], (struct sockaddr *)&addr, addrlen)) {
1090 sockerror("make_sockets: connect");
1091 closesocket(s);
1092 closesocket(fd[1]);
1093 return 1;
1094 }
1095 fd[0]=s_accept(s, (struct sockaddr *)&addr, &addrlen, 1,
1096 "make_sockets: s_accept");
1097 if(fd[0]==INVALID_SOCKET) {
1098 closesocket(s);
1099 closesocket(fd[1]);
1100 return 1;
1101 }
1102 closesocket(s); /* don't care about the result */
1103 set_nonblock(fd[0], 1);
1104 set_nonblock(fd[1], 1);
1105 #else
1106 if(s_socketpair(AF_UNIX, SOCK_STREAM, 0, fd, 1, "make_sockets: socketpair"))
1107 return 1;
1108 #endif
1109 return 0;
1110 }
1111
1112 /* returns 0 on success, and -1 on error */
1113 int original_dst(const SOCKET fd, SOCKADDR_UNION *addr) {
1114 socklen_t addrlen;
1115
1116 memset(addr, 0, sizeof(SOCKADDR_UNION));
1117 addrlen=sizeof(SOCKADDR_UNION);
1118 #ifdef SO_ORIGINAL_DST
1119 #ifdef USE_IPV6
1120 if(!getsockopt(fd, SOL_IPV6, SO_ORIGINAL_DST, (char *)&addr->sa, &addrlen))
1121 return 0; /* succeeded */
1122 #endif /* USE_IPV6 */
1123 if(!getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, (char *)&addr->sa, &addrlen))
1124 return 0; /* succeeded */
1125 sockerror("getsockopt SO_ORIGINAL_DST");
1126 #else /* SO_ORIGINAL_DST */
1127 if(!getsockname(fd, &addr->sa, &addrlen))
1128 return 0; /* succeeded */
1129 sockerror("getsockname");
1130 #endif /* SO_ORIGINAL_DST */
1131 return -1; /* failed */
1132 }
1133
1134 /* returns 0 on close and 1 on non-critical errors */
1135 int socket_needs_retry(CLI *c, const char *text) {
1136 switch(get_last_socket_error()) {
1137 /* http://tangentsoft.net/wskfaq/articles/bsd-compatibility.html */
1138 case 0: /* close on read, or close on write on WIN32 */
1139 /* fall through */
1140 #ifndef USE_WIN32
1141 case EPIPE: /* close on write on Unix */
1142 /* fall through */
1143 #endif
1144 case S_ECONNABORTED:
1145 s_log(LOG_INFO, "%s: Socket is closed", text);
1146 return 0;
1147 case S_EINTR:
1148 s_log(LOG_DEBUG, "%s: Interrupted by a signal: retrying", text);
1149 return 1;
1150 case S_EWOULDBLOCK:
1151 s_log(LOG_NOTICE, "%s: Would block: retrying", text);
1152 s_poll_sleep(1, 0); /* Microsoft bug KB177346 */
1153 return 1;
1154 #if S_EAGAIN!=S_EWOULDBLOCK
1155 case S_EAGAIN:
1156 s_log(LOG_DEBUG,
1157 "%s: Temporary lack of resources: retrying", text);
1158 return 1;
1159 #endif
1160 #ifdef USE_WIN32
1161 case S_ECONNRESET:
1162 /* dying "exec" processes on Win32 cause reset instead of close */
1163 if(c->opt->exec_name) {
1164 s_log(LOG_INFO, "%s: Socket is closed (exec)", text);
1165 return 0;
1166 }
1167 #endif
1168 /* fall through */
1169 default:
1170 sockerror(text);
1171 throw_exception(c, 1);
1172 return -1; /* some C compilers require a return value */
1173 }
1174 }
1175
1176 /* end of network.c */