63
62
main_initialize(argc>1 ? argv[1] : NULL, argc>2 ? argv[2] : NULL);
65
64
signal(SIGPIPE, SIG_IGN); /* avoid 'broken pipe' signal */
66
signal(SIGTERM, signal_handler);
67
signal(SIGQUIT, signal_handler);
68
signal(SIGINT, signal_handler);
69
signal(SIGHUP, signal_handler);
65
if(signal(SIGTERM, SIG_IGN)!=SIG_IGN)
66
signal(SIGTERM, signal_handler);
67
if(signal(SIGQUIT, SIG_IGN)!=SIG_IGN)
68
signal(SIGQUIT, signal_handler);
69
if(signal(SIGINT, SIG_IGN)!=SIG_IGN)
70
signal(SIGINT, signal_handler);
71
if(signal(SIGHUP, SIG_IGN)!=SIG_IGN)
72
signal(SIGHUP, signal_handler);
70
73
/* signal(SIGSEGV, signal_handler); */
145
152
if(set_socket_options(opt->fd, 0)<0)
147
memset(&addr, 0, sizeof(addr));
148
addr.sin_family=AF_INET;
149
addr.sin_addr.s_addr=*opt->localnames;
150
addr.sin_port=opt->localport;
151
safe_ntoa(opt->local_address, addr.sin_addr);
152
if(bind(opt->fd, (struct sockaddr *)&addr, sizeof(addr))) {
153
log(LOG_ERR, "Error binding %s to %s:%d", opt->servname,
154
opt->local_address, ntohs(addr.sin_port));
154
s_ntop(opt->local_address, &addr);
155
if(bind(opt->fd, &addr.sa, addr_len(addr))) {
156
s_log(LOG_ERR, "Error binding %s to %s",
157
opt->servname, opt->local_address);
155
158
sockerror("bind");
158
log(LOG_DEBUG, "%s bound to %s:%d", opt->servname,
159
opt->local_address, ntohs(addr.sin_port));
161
s_log(LOG_DEBUG, "%s bound to %s", opt->servname, opt->local_address);
160
162
if(listen(opt->fd, 5)) {
161
163
sockerror("listen");
194
memcpy(¤t_set, &base_set, sizeof(fd_set));
195
if(sselect(n+1, ¤t_set, NULL, NULL, NULL)<0)
196
/* non-critical error */
197
log_error(LOG_INFO, get_last_socket_error(), "main loop select");
190
if(s_poll_wait(&fds, -1)<0) /* non-critical error */
191
log_error(LOG_INFO, get_last_socket_error(),
192
"daemon_loop: s_poll_wait");
199
194
for(opt=local_options.next; opt; opt=opt->next)
200
if(FD_ISSET(opt->fd, ¤t_set))
195
if(s_poll_canread(&fds, opt->fd))
201
196
accept_connection(opt);
203
log(LOG_ERR, "INTERNAL ERROR: End of infinite loop 8-)");
198
s_log(LOG_ERR, "INTERNAL ERROR: End of infinite loop 8-)");
206
201
static void accept_connection(LOCAL_OPTIONS *opt) {
207
struct sockaddr_in addr;
208
int err, s, addrlen=sizeof(addr);
203
char from_address[IPLEN];
204
int s, addrlen=sizeof(SOCKADDR_UNION);
211
s=accept(opt->fd, (struct sockaddr *)&addr, &addrlen);
213
err=get_last_socket_error();
214
} while(s<0 && err==EINTR);
206
while((s=accept(opt->fd, &addr.sa, &addrlen))<0) {
207
switch(get_last_socket_error()) {
216
sleep(1); /* temporarily out of resources - short delay */
230
enter_critical_section(CRIT_NTOA); /* inet_ntoa is not mt-safe */
231
log(LOG_DEBUG, "%s accepted FD=%d from %s:%d", opt->servname, s,
232
inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
233
leave_critical_section(CRIT_NTOA);
234
if(num_clients>=max_clients) {
235
log(LOG_WARNING, "Connection rejected: too many clients (>=%d)",
222
s_ntop(from_address, &addr);
223
s_log(LOG_DEBUG, "%s accepted FD=%d from %s",
224
opt->servname, s, from_address);
225
if(max_clients && num_clients>=max_clients) {
226
s_log(LOG_WARNING, "Connection rejected: too many clients (>=%d)",
255
246
static void get_limits(void) {
258
log(LOG_NOTICE, "WIN32 platform: %d clients allowed", max_clients);
249
s_log(LOG_NOTICE, "No limit detected for the number of clients");
251
max_fds=0; /* unlimited */
262
253
#if defined HAVE_SYSCONF
263
fds_ulimit=sysconf(_SC_OPEN_MAX);
254
max_fds=sysconf(_SC_OPEN_MAX);
265
256
ioerror("sysconf");
266
257
#elif defined HAVE_GETRLIMIT
267
258
struct rlimit rlim;
268
259
if(getrlimit(RLIMIT_NOFILE, &rlim)<0)
269
260
ioerror("getrlimit");
271
fds_ulimit=rlim.rlim_cur;
272
if(fds_ulimit==RLIM_INFINITY)
275
max_fds=fds_ulimit<FD_SETSIZE ? fds_ulimit : FD_SETSIZE;
276
if(max_fds<16) /* stunnel needs at least 16 file desriptors to work */
262
max_fds=rlim.rlim_cur;
263
if(max_fds==RLIM_INFINITY)
264
max_fds=0; /* RLIM_INFINITY should be equal to zero, anyway */
266
s_log(LOG_INFO, "file ulimit = %d%s (can be changed with 'ulimit -n')",
267
max_fds, max_fds ? "" : " (unlimited)");
269
s_log(LOG_INFO, "poll() used - no FD_SETSIZE limit for file descriptors");
272
"FD_SETSIZE = %d (some systems allow to increase this value)",
274
if(!max_fds || max_fds>FD_SETSIZE)
277
if(max_fds && max_fds<16) /* stunnel needs at least 16 file desriptors */
278
max_clients=max_fds>=256 ? max_fds*125/256 : (max_fds-6)/2;
279
log(LOG_NOTICE, "FD_SETSIZE=%d, file ulimit=%d%s -> %d clients allowed",
280
FD_SETSIZE, fds_ulimit, fds_ulimit<0?" (unlimited)":"", max_clients);
280
max_clients=max_fds>=256 ? max_fds*125/256 : (max_fds-6)/2;
281
s_log(LOG_NOTICE, "%d clients allowed", max_clients);
284
s_log(LOG_NOTICE, "No limit detected for the number of clients");
399
404
/* silently remove old pid file */
400
405
unlink(options.pidfile);
401
406
if((pf=open(options.pidfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL,0644))==-1) {
402
log(LOG_ERR, "Cannot create pid file %s", options.pidfile);
407
s_log(LOG_ERR, "Cannot create pid file %s", options.pidfile);
403
408
ioerror("create");
406
411
sprintf(pid, "%lu\n", options.dpid);
407
412
write(pf, pid, strlen(pid));
409
log(LOG_DEBUG, "Created pid file %s", options.pidfile);
414
s_log(LOG_DEBUG, "Created pid file %s", options.pidfile);
410
415
atexit(delete_pid);
413
418
static void delete_pid(void) {
414
log(LOG_DEBUG, "removing pid file %s", options.pidfile);
419
s_log(LOG_DEBUG, "removing pid file %s", options.pidfile);
415
420
if((unsigned long)getpid()!=options.dpid)
416
421
return; /* current process is not main daemon process */
417
422
if(unlink(options.pidfile)<0)
418
423
ioerror(options.pidfile); /* not critical */
420
#endif /* defined USE_WIN32 */
422
int set_socket_options(int s, int type) {
424
extern SOCK_OPT sock_opts[];
425
static char *type_str[3]={"accept", "local", "remote"};
428
for(ptr=sock_opts;ptr->opt_str;ptr++) {
429
if(!ptr->opt_val[type])
430
continue; /* default */
431
switch(ptr->opt_type) {
433
opt_size=sizeof(struct linger); break;
435
opt_size=sizeof(struct timeval); break;
437
opt_size=strlen(ptr->opt_val[type]->c_val)+1; break;
439
opt_size=sizeof(int); break;
441
if(setsockopt(s, ptr->opt_level, ptr->opt_name,
442
(void *)ptr->opt_val[type], opt_size)) {
443
sockerror(ptr->opt_str);
444
return -1; /* FAILED */
446
log(LOG_DEBUG, "%s option set on %s socket",
447
ptr->opt_str, type_str[type]);
453
void ioerror(char *txt) { /* input/output error handler */
454
log_error(LOG_ERR, get_last_error(), txt);
457
void sockerror(char *txt) { /* socket error handler */
458
log_error(LOG_ERR, get_last_socket_error(), txt);
461
void log_error(int level, int error, char *txt) { /* generic error logger */
462
log(level, "%s: %s (%d)", txt, my_strerror(error), error);
465
char *my_strerror(int errnum) {
469
return "Interrupted system call (WSAEINTR)";
471
return "Bad file number (WSAEBADF)";
473
return "Permission denied (WSAEACCES)";
475
return "Bad address (WSAEFAULT)";
477
return "Invalid argument (WSAEINVAL)";
479
return "Too many open files (WSAEMFILE)";
481
return "Operation would block (WSAEWOULDBLOCK)";
483
return "Operation now in progress (WSAEINPROGRESS)";
485
return "Operation already in progress (WSAEALREADY)";
487
return "Socket operation on non-socket (WSAENOTSOCK)";
489
return "Destination address required (WSAEDESTADDRREQ)";
491
return "Message too long (WSAEMSGSIZE)";
493
return "Protocol wrong type for socket (WSAEPROTOTYPE)";
495
return "Bad protocol option (WSAENOPROTOOPT)";
497
return "Protocol not supported (WSAEPROTONOSUPPORT)";
499
return "Socket type not supported (WSAESOCKTNOSUPPORT)";
501
return "Operation not supported on socket (WSAEOPNOTSUPP)";
503
return "Protocol family not supported (WSAEPFNOSUPPORT)";
505
return "Address family not supported by protocol family (WSAEAFNOSUPPORT)";
507
return "Address already in use (WSAEADDRINUSE)";
509
return "Can't assign requested address (WSAEADDRNOTAVAIL)";
511
return "Network is down (WSAENETDOWN)";
513
return "Network is unreachable (WSAENETUNREACH)";
515
return "Net dropped connection or reset (WSAENETRESET)";
517
return "Software caused connection abort (WSAECONNABORTED)";
519
return "Connection reset by peer (WSAECONNRESET)";
521
return "No buffer space available (WSAENOBUFS)";
523
return "Socket is already connected (WSAEISCONN)";
525
return "Socket is not connected (WSAENOTCONN)";
527
return "Can't send after socket shutdown (WSAESHUTDOWN)";
529
return "Too many references, can't splice (WSAETOOMANYREFS)";
531
return "Connection timed out (WSAETIMEDOUT)";
533
return "Connection refused (WSAECONNREFUSED)";
535
return "Too many levels of symbolic links (WSAELOOP)";
537
return "File name too long (WSAENAMETOOLONG)";
539
return "Host is down (WSAEHOSTDOWN)";
541
return "No Route to Host (WSAEHOSTUNREACH)";
543
return "Directory not empty (WSAENOTEMPTY)";
545
return "Too many processes (WSAEPROCLIM)";
547
return "Too many users (WSAEUSERS)";
549
return "Disc Quota Exceeded (WSAEDQUOT)";
551
return "Stale NFS file handle (WSAESTALE)";
553
return "Network SubSystem is unavailable (WSASYSNOTREADY)";
555
return "WINSOCK DLL Version out of range (WSAVERNOTSUPPORTED)";
557
return "Successful WSASTARTUP not yet performed (WSANOTINITIALISED)";
559
return "Too many levels of remote in path (WSAEREMOTE)";
561
return "Host not found (WSAHOST_NOT_FOUND)";
563
return "Non-Authoritative Host not found (WSATRY_AGAIN)";
565
return "Non-Recoverable errors: FORMERR, REFUSED, NOTIMP (WSANO_RECOVERY)";
567
return "Valid name, no data record of requested type (WSANO_DATA)";
569
case 11004: /* typically, only WSANO_DATA is reported */
570
return "No address, look for MX record (WSANO_ADDRESS)";
572
#endif /* defined USE_WIN32 */
574
return strerror(errnum);
580
426
static void signal_handler(int sig) { /* signal handler */
581
log(sig==SIGTERM ? LOG_NOTICE : LOG_ERR,
427
s_log(sig==SIGTERM ? LOG_NOTICE : LOG_ERR,
582
428
"Received signal %d; terminating", sig);
586
431
#endif /* !defined USE_WIN32 */
588
433
char *stunnel_info(void) {
609
int alloc_fd(int sock) {
613
"File descriptor out of range (%d>=%d)", sock, max_fds);
618
setnonblock(sock, 1);
622
/* Try to use non-POSIX O_NDELAY on obsolete BSD systems */
623
#if !defined O_NONBLOCK && defined O_NDELAY
624
#define O_NONBLOCK O_NDELAY
627
static void setnonblock(int sock, unsigned long l) {
628
#if defined F_GETFL && defined F_SETFL && defined O_NONBLOCK
631
flags=fcntl(sock, F_GETFL, 0);
632
}while(flags<0 && errno==EINTR);
633
flags=l ? flags|O_NONBLOCK : flags&(~O_NONBLOCK);
635
retval=fcntl(sock, F_SETFL, flags);
636
}while(retval<0 && errno==EINTR);
639
if(ioctlsocket(sock, FIONBIO, &l)<0)
641
sockerror("nonblocking"); /* non-critical */
643
log(LOG_DEBUG, "FD %d in %sblocking mode", sock,
647
char *safe_ntoa(char *text, struct in_addr in) {
648
enter_critical_section(CRIT_NTOA); /* inet_ntoa is not mt-safe */
649
strncpy(text, inet_ntoa(in), 15);
650
leave_critical_section(CRIT_NTOA);
655
469
/* End of stunnel.c */