cppcheck sliencing
[exim.git] / src / src / os.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2021 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10 #ifdef STAND_ALONE
11 # include <signal.h>
12 # include <stdio.h>
13 # include <time.h>
14 #else
15 # define DEBUG(x) if (debug_selector & (x))
16 #endif
17
18 #ifndef CS
19 # define CS (char *)
20 # define US (unsigned char *)
21 #endif
22
23 /* This source file contains "default" system-dependent functions which
24 provide functionality (or lack of it) in cases where the OS-specific os.c
25 file has not. Some of them are tailored by macros defined in os.h files. */
26
27
28 #ifndef OS_RESTARTING_SIGNAL
29 /*************************************************
30 *          Set up restarting signal              *
31 *************************************************/
32
33 /* This function has the same functionality as the ANSI C signal() function,
34 except that it arranges that, if the signal happens during a system call, the
35 system call gets restarted. (Also, it doesn't return a result.) Different
36 versions of Unix have different defaults, and different ways of setting up a
37 restarting signal handler. If the functionality is not available, the signal
38 should be set to be ignored. This function is used only for catching SIGUSR1.
39 */
40
41 void
42 os_restarting_signal(int sig, void (*handler)(int))
43 {
44 /* Many systems have the SA_RESTART sigaction for specifying that a signal
45 should restart system calls. These include SunOS5, AIX, BSDI, IRIX, FreeBSD,
46 OSF1, Linux and HP-UX 10 (but *not* HP-UX 9). */
47
48 #ifdef SA_RESTART
49 struct sigaction act;
50 act.sa_handler = handler;
51 sigemptyset(&(act.sa_mask));
52 act.sa_flags = SA_RESTART;
53 sigaction(sig, &act, NULL);
54
55 # ifdef STAND_ALONE
56 printf("Used SA_RESTART\n");
57 # endif
58
59 /* SunOS4 and Ultrix default to non-interruptable signals, with SV_INTERRUPT
60 for making them interruptable. This seems to be a dying fashion. */
61
62 #elif defined SV_INTERRUPT
63 signal(sig, handler);
64
65 # ifdef STAND_ALONE
66 printf("Used default signal()\n");
67 # endif
68
69
70 /* If neither SA_RESTART nor SV_INTERRUPT is available we don't know how to
71 set up a restarting signal, so simply suppress the facility. */
72
73 #else
74 signal(sig, SIG_IGN);
75
76 # ifdef STAND_ALONE
77 printf("Used SIG_IGN\n");
78 # endif
79
80 #endif
81 }
82
83 #endif  /* OS_RESTARTING_SIGNAL */
84
85
86 #ifndef OS_NON_RESTARTING_SIGNAL
87 /*************************************************
88 *          Set up non-restarting signal          *
89 *************************************************/
90
91 /* This function has the same functionality as the ANSI C signal() function,
92 except that it arranges that, if the signal happens during a system call, the
93 system call gets interrupted. (Also, it doesn't return a result.) Different
94 versions of Unix have different defaults, and different ways of setting up a
95 non-restarting signal handler. For systems for which we don't know what to do,
96 just use the normal signal() function and hope for the best. */
97
98 void
99 os_non_restarting_signal(int sig, void (*handler)(int))
100 {
101 /* Many systems have the SA_RESTART sigaction for specifying that a signal
102 should restart system calls. These include SunOS5, AIX, BSDI, IRIX, FreeBSD,
103 OSF1, Linux and HP-UX 10 (but *not* HP-UX 9). */
104
105 #ifdef SA_RESTART
106 struct sigaction act;
107 act.sa_handler = handler;
108 sigemptyset(&(act.sa_mask));
109 act.sa_flags = 0;
110 sigaction(sig, &act, NULL);
111
112 #ifdef STAND_ALONE
113 printf("Used sigaction() with flags = 0\n");
114 #endif
115
116 /* SunOS4 and Ultrix default to non-interruptable signals, with SV_INTERRUPT
117 for making them interruptable. This seems to be a dying fashion. */
118
119 #elif defined SV_INTERRUPT
120 struct sigvec sv;
121 sv.sv_handler = handler;
122 sv.sv_flags = SV_INTERRUPT;
123 sv.sv_mask = -1;
124 sigvec(sig, &sv, NULL);
125
126 #ifdef STAND_ALONE
127 printf("Used sigvec() with flags = SV_INTERRUPT\n");
128 #endif
129
130 /* If neither SA_RESTART nor SV_INTERRUPT is available we don't know how to
131 set up a restarting signal, so just use the standard signal() function. */
132
133 #else
134 signal(sig, handler);
135
136 #ifdef STAND_ALONE
137 printf("Used default signal()\n");
138 #endif
139
140 #endif
141 }
142
143 #endif  /* OS_NON_RESTARTING_SIGNAL */
144
145
146
147 #ifdef STRERROR_FROM_ERRLIST
148 /*************************************************
149 *     Provide strerror() for non-ANSI libraries  *
150 *************************************************/
151
152 /* Some old-fashioned systems still around (e.g. SunOS4) don't have strerror()
153 in their libraries, but can provide the same facility by this simple
154 alternative function. */
155
156 char *
157 strerror(int n)
158 {
159 if (n < 0 || n >= sys_nerr) return "unknown error number";
160 return sys_errlist[n];
161 }
162 #endif /* STRERROR_FROM_ERRLIST */
163
164
165
166 #ifndef OS_STRSIGNAL
167 /*************************************************
168 *      Provide strsignal() for systems without   *
169 *************************************************/
170
171 /* Some systems have strsignal() to turn signal numbers into names; others
172 may have other means of doing this. This function is used for those systems
173 that have nothing. It provides a basic translation for the common standard
174 signal numbers. I've been extra cautious with the ifdef's here. Probably more
175 than is necessary... */
176
177 const char *
178 os_strsignal(const int n)
179 {
180 switch (n)
181   {
182   #ifdef SIGHUP
183   case SIGHUP:  return "hangup";
184   #endif
185
186   #ifdef SIGINT
187   case SIGINT:  return "interrupt";
188   #endif
189
190   #ifdef SIGQUIT
191   case SIGQUIT: return "quit";
192   #endif
193
194   #ifdef SIGILL
195   case SIGILL:  return "illegal instruction";
196   #endif
197
198   #ifdef SIGTRAP
199   case SIGTRAP: return "trace trap";
200   #endif
201
202   #ifdef SIGABRT
203   case SIGABRT: return "abort";
204   #endif
205
206   #ifdef SIGEMT
207   case SIGEMT:  return "EMT instruction";
208   #endif
209
210   #ifdef SIGFPE
211   case SIGFPE:  return "arithmetic exception";
212   #endif
213
214   #ifdef SIGKILL
215   case SIGKILL: return "killed";
216   #endif
217
218   #ifdef SIGBUS
219   case SIGBUS:  return "bus error";
220   #endif
221
222   #ifdef SIGSEGV
223   case SIGSEGV: return "segmentation fault";
224   #endif
225
226   #ifdef SIGSYS
227   case SIGSYS:  return "bad system call";
228   #endif
229
230   #ifdef SIGPIPE
231   case SIGPIPE: return "broken pipe";
232   #endif
233
234   #ifdef SIGALRM
235   case SIGALRM: return "alarm";
236   #endif
237
238   #ifdef SIGTERM
239   case SIGTERM: return "terminated";
240   #endif
241
242   #ifdef SIGUSR1
243   case SIGUSR1: return "user signal 1";
244   #endif
245
246   #ifdef SIGUSR2
247   case SIGUSR2: return "user signal 2";
248   #endif
249
250   #ifdef SIGCHLD
251   case SIGCHLD: return "child stop or exit";
252   #endif
253
254   #ifdef SIGPWR
255   case SIGPWR:  return "power fail/restart";
256   #endif
257
258   #ifdef SIGURG
259   case SIGURG:  return "urgent condition on I/O channel";
260   #endif
261
262   #ifdef SIGSTOP
263   case SIGSTOP: return "stop";
264   #endif
265
266   #ifdef SIGTSTP
267   case SIGTSTP: return "stop from tty";
268   #endif
269
270   #ifdef SIGXCPU
271   case SIGXCPU: return "exceeded CPU limit";
272   #endif
273
274   #ifdef SIGXFSZ
275   case SIGXFSZ: return "exceeded file size limit";
276   #endif
277
278   default:      return "unrecognized signal number";
279   }
280 }
281 #endif /* OS_STRSIGNAL */
282
283
284
285 #ifndef OS_STREXIT
286 /*************************************************
287 *      Provide strexit() for systems without     *
288 *************************************************/
289
290 /* Actually, I don't know of any system that has a strexit() function to turn
291 exit codes into text, but this function is implemented this way so that if any
292 OS does have such a thing, it could be used instead of this build-in one. */
293
294 const char *
295 os_strexit(const int n)
296 {
297 switch (n)
298   {
299   /* On systems without sysexits.h we can assume only those exit codes
300   that are given a default value in exim.h. */
301
302   #ifndef NO_SYSEXITS
303   case EX_USAGE:       return "(could mean usage or syntax error)";
304   case EX_DATAERR:     return "(could mean error in input data)";
305   case EX_NOINPUT:     return "(could mean input data missing)";
306   case EX_NOUSER:      return "(could mean user nonexistent)";
307   case EX_NOHOST:      return "(could mean host nonexistent)";
308   case EX_SOFTWARE:    return "(could mean internal software error)";
309   case EX_OSERR:       return "(could mean internal operating system error)";
310   case EX_OSFILE:      return "(could mean system file missing)";
311   case EX_IOERR:       return "(could mean input/output error)";
312   case EX_PROTOCOL:    return "(could mean protocol error)";
313   case EX_NOPERM:      return "(could mean permission denied)";
314   #endif
315
316   case EX_EXECFAILED:  return "(could mean unable to exec or command does not exist)";
317   case EX_UNAVAILABLE: return "(could mean service or program unavailable)";
318   case EX_CANTCREAT:   return "(could mean can't create output file)";
319   case EX_TEMPFAIL:    return "(could mean temporary error)";
320   case EX_CONFIG:      return "(could mean configuration error)";
321   default:             return "";
322   }
323 }
324 #endif /* OS_STREXIT */
325
326
327
328
329 /***********************************************************
330 *                   Load average function                  *
331 ***********************************************************/
332
333 /* Although every Unix seems to have a different way of getting the load
334 average, a number of them have things in common. Some common variants are
335 provided below, but if an OS has unique requirements it can be handled in
336 a specific os.c file. What is required is a function called os_getloadavg
337 which takes no arguments and passes back the load average * 1000 as an int,
338 or -1 if no data is available. */
339
340
341 /* ----------------------------------------------------------------------- */
342 /* If the OS has got a BSD getloadavg() function, life is very easy. */
343
344 #if !defined(OS_LOAD_AVERAGE) && defined(HAVE_BSD_GETLOADAVG)
345 #define OS_LOAD_AVERAGE
346
347 int
348 os_getloadavg(void)
349 {
350 double avg;
351 int loads = getloadavg (&avg, 1);
352 if (loads != 1) return -1;
353 return (int)(avg * 1000.0);
354 }
355 #endif
356 /* ----------------------------------------------------------------------- */
357
358
359
360 /* ----------------------------------------------------------------------- */
361 /* Only SunOS5 has the kstat functions as far as I know, but put the code
362 here as there is the -hal variant, and other systems might follow this road one
363 day. */
364
365 #if !defined(OS_LOAD_AVERAGE) && defined(HAVE_KSTAT)
366 # define OS_LOAD_AVERAGE
367
368 # include <kstat.h>
369
370 int
371 os_getloadavg(void)
372 {
373 int avg;
374 kstat_ctl_t *kc;
375 kstat_t *ksp;
376 kstat_named_t *kn;
377
378 if ((kc = kstat_open()) == NULL ||
379     (ksp = kstat_lookup(kc, LOAD_AVG_KSTAT_MODULE, 0, LOAD_AVG_KSTAT))
380         == NULL ||
381      kstat_read(kc, ksp, NULL) < 0 ||
382     (kn = kstat_data_lookup(ksp, LOAD_AVG_SYMBOL)) == NULL)
383   return -1;
384
385 avg = (int)(((double)(kn->LOAD_AVG_FIELD)/FSCALE) * 1000.0);
386
387 kstat_close(kc);
388 return avg;
389 }
390
391 #endif
392 /* ----------------------------------------------------------------------- */
393
394
395
396 /* ----------------------------------------------------------------------- */
397 /* Handle OS where a kernel symbol has to be read from /dev/kmem */
398
399 #if !defined(OS_LOAD_AVERAGE) && defined(HAVE_DEV_KMEM)
400 #define OS_LOAD_AVERAGE
401
402 # include <nlist.h>
403
404 static int  avg_kd = -1;
405 static long avg_offset;
406
407 int
408 os_getloadavg(void)
409 {
410 LOAD_AVG_TYPE avg;
411
412 if (avg_kd < 0)
413   {
414   struct nlist nl[2];
415   nl[0].n_name = LOAD_AVG_SYMBOL;
416   nl[1].n_name = "";
417   nlist (KERNEL_PATH, nl);
418   avg_offset = (long)nl[0].n_value;
419   avg_kd = open ("/dev/kmem", 0);
420   if (avg_kd < 0) return -1;
421   (void) fcntl(avg_kd, F_SETFD, FD_CLOEXEC);
422   }
423
424 if (lseek (avg_kd, avg_offset, 0) == -1L
425     || read (avg_kd, CS (&avg), sizeof (avg)) != sizeof(avg))
426   return -1;
427
428 return (int)(((double)avg/FSCALE)*1000.0);
429 }
430
431 #endif
432 /* ----------------------------------------------------------------------- */
433
434
435
436 /* ----------------------------------------------------------------------- */
437 /* If nothing is known about this OS, then the load average facility is
438 not available. */
439
440 #ifndef OS_LOAD_AVERAGE
441
442 int
443 os_getloadavg(void)
444 {
445 return -1;
446 }
447
448 #endif
449
450 /* ----------------------------------------------------------------------- */
451
452
453
454 #if !defined FIND_RUNNING_INTERFACES
455 /*************************************************
456 *     Find all the running network interfaces    *
457 *************************************************/
458
459 /* Finding all the running interfaces is something that has os-dependent
460 tweaks, even in the IPv4 case, and it gets worse for IPv6, which is why this
461 code is now in the os-dependent source file. There is a common function which
462 works on most OS (except IRIX) for IPv4 interfaces, and, with some variations
463 controlled by macros, on at least one OS for IPv6 and IPv4 interfaces. On Linux
464 with IPv6, the common function is used for the IPv4 interfaces and additional
465 code used for IPv6. Consequently, the real function is called
466 os_common_find_running_interfaces() so that it can be called from the Linux
467 function. On non-Linux systems, the macro for os_find_running_interfaces just
468 calls the common function; on Linux it calls the Linux function.
469
470 This function finds the addresses of all the running interfaces on the machine.
471 A chain of blocks containing the textual form of the addresses is returned.
472
473 getifaddrs() provides a sane consistent way to query this on modern OSs,
474 otherwise fall back to a maze of twisty ioctl() calls
475
476 Arguments:    none
477 Returns:      a chain of ip_address_items, each pointing to a textual
478               version of an IP address, with the port field set to zero
479 */
480
481
482 #ifndef NO_FIND_INTERFACES
483
484 #ifdef HAVE_GETIFADDRS
485
486 # include <ifaddrs.h>
487
488 ip_address_item *
489 os_common_find_running_interfaces(void)
490 {
491 struct ifaddrs *ifalist = NULL;
492 ip_address_item *yield = NULL;
493 ip_address_item *last = NULL;
494 ip_address_item  *next;
495
496 if (getifaddrs(&ifalist) != 0)
497   log_write(0, LOG_PANIC_DIE, "Unable to call getifaddrs: %d %s",
498     errno, strerror(errno));
499
500 for (struct ifaddrs * ifa = ifalist; ifa; ifa = ifa->ifa_next)
501   {
502   struct sockaddr * ifa_addr = ifa->ifa_addr;
503   if (!ifa_addr) continue;
504   if (ifa_addr->sa_family != AF_INET
505 #if HAVE_IPV6
506     && ifa_addr->sa_family != AF_INET6
507 #endif /* HAVE_IPV6 */
508     )
509     continue;
510
511   if ( !(ifa->ifa_flags & IFF_UP) ) /* Only want 'UP' interfaces */
512     continue;
513
514   /* Create a data block for the address, fill in the data, and put it on the
515   chain. */
516
517   next = store_get(sizeof(ip_address_item), GET_UNTAINTED);
518   next->next = NULL;
519   next->port = 0;
520   (void)host_ntoa(-1, ifa_addr, next->address, NULL);
521
522   if (!yield)
523     yield = last = next;
524   else
525     {
526     last->next = next;
527     last = next;
528     }
529
530   DEBUG(D_interface) debug_printf("Actual local interface address is %s (%s)\n",
531     last->address, ifa->ifa_name);
532   }
533
534 /* free the list of addresses, and return the chain of data blocks. */
535
536 freeifaddrs (ifalist);
537 return yield;
538 }
539
540 #else /* HAVE_GETIFADDRS */
541
542 /*
543 Problems:
544
545   (1) Solaris 2 has the SIOGIFNUM call to get the number of interfaces, but
546   other OS (including Solaris 1) appear not to. So just screw in a largeish
547   fixed number, defined by MAX_INTERFACES. This is in the config.h file and
548   can be changed in Local/Makefile. Unfortunately, the www addressing scheme
549   means that some hosts have a very large number of virtual interfaces. Such
550   hosts are recommended to set local_interfaces to avoid problems with this.
551
552   (2) If the standard code is run on IRIX, it does not return any alias
553   interfaces. There is special purpose code for that operating system, which
554   uses the sysctl() function. The code is in OS/os.c-IRIX, and this code isn't
555   used on that OS.
556
557   (3) Some experimental/developing OS (e.g. GNU/Hurd) do not have any means
558   of finding the interfaces. If NO_FIND_INTERFACES is set, a fudge-up is used
559   instead.
560
561   (4) Some operating systems set the IP address in what SIOCGIFCONF returns;
562   others do not, and require SIOCGIFADDR to be called to get it. For most of
563   the former, calling the latter does no harm, but it causes grief on Linux and
564   BSD systems in the case of IP aliasing, so a means of cutting it out is
565   provided.
566 */
567
568 /* If there is IPv6 support, and SIOCGLIFCONF is defined, define macros to
569 use these new, longer versions of the old IPv4 interfaces. Otherwise, define
570 the macros to use the historical versions. */
571
572 #if HAVE_IPV6 && defined SIOCGLIFCONF
573 #define V_ifconf        lifconf
574 #define V_ifreq         lifreq
575 #define V_GIFADDR       SIOCGLIFADDR
576 #define V_GIFCONF       SIOCGLIFCONF
577 #define V_GIFFLAGS      SIOCGLIFFLAGS
578 #define V_ifc_buf       lifc_buf
579 #define V_ifc_family    lifc_family
580 #define V_ifc_flags     lifc_flags
581 #define V_ifc_len       lifc_len
582 #define V_ifr_addr      lifr_addr
583 #define V_ifr_flags     lifr_flags
584 #define V_ifr_name      lifr_name
585 #define V_FAMILY_QUERY  AF_UNSPEC
586 #define V_family        ss_family
587 #else
588 #define V_ifconf        ifconf
589 #define V_ifreq         ifreq
590 #define V_GIFADDR       SIOCGIFADDR
591 #define V_GIFCONF       SIOCGIFCONF
592 #define V_GIFFLAGS      SIOCGIFFLAGS
593 #define V_ifc_buf       ifc_buf
594 #define V_ifc_family    ifc_family
595 #define V_ifc_flags     ifc_flags
596 #define V_ifc_len       ifc_len
597 #define V_ifr_addr      ifr_addr
598 #define V_ifr_flags     ifr_flags
599 #define V_ifr_name      ifr_name
600 #define V_family        sa_family
601 #endif
602
603 /* In all cases of IPv6 support, use an IPv6 socket. Otherwise (at least on
604 Solaris 8) the call to read the flags doesn't work for IPv6 interfaces. If
605 we find we can't actually make an IPv6 socket, the code will revert to trying
606 an IPv4 socket. */
607
608 #if HAVE_IPV6
609 #define FAMILY          AF_INET6
610 #else
611 #define FAMILY          AF_INET
612 #endif
613
614 /* OK, after all that preliminary stuff, here's the code. */
615
616 ip_address_item *
617 os_common_find_running_interfaces(void)
618 {
619 struct V_ifconf ifc;
620 struct V_ifreq ifreq;
621 int vs;
622 ip_address_item *yield = NULL;
623 ip_address_item *last = NULL;
624 ip_address_item  *next;
625 char buf[MAX_INTERFACES*sizeof(struct V_ifreq)];
626 struct sockaddr *addrp;
627 size_t len = 0;
628 char addrbuf[512];
629
630 /* We have to create a socket in order to do ioctls on it to find out
631 what we want to know. */
632
633 if ((vs = socket(FAMILY, SOCK_DGRAM, 0)) < 0)
634   {
635 #if HAVE_IPV6
636   DEBUG(D_interface)
637     debug_printf("Unable to create IPv6 socket to find interface addresses:\n  "
638       "error %d %s\nTrying for an IPv4 socket\n", errno, strerror(errno));
639   vs = socket(AF_INET, SOCK_DGRAM, 0);
640   if (vs < 0)
641 #endif
642   log_write(0, LOG_PANIC_DIE, "Unable to create IPv4 socket to find interface "
643     "addresses: %d %s", errno, strerror(errno));
644   }
645
646 /* Get the interface configuration. Some additional data is required when the
647 new structures are in use. */
648
649 ifc.V_ifc_len = sizeof(buf);
650 ifc.V_ifc_buf = buf;
651
652 #ifdef V_FAMILY_QUERY
653 ifc.V_ifc_family = V_FAMILY_QUERY;
654 ifc.V_ifc_flags = 0;
655 #endif
656
657 if (ioctl(vs, V_GIFCONF, CS &ifc) < 0)
658   log_write(0, LOG_PANIC_DIE, "Unable to get interface configuration: %d %s",
659     errno, strerror(errno));
660
661 /* If the buffer is big enough, the ioctl sets the value of ifc.V_ifc_len to
662 the amount actually used. If the buffer isn't big enough, at least on some
663 operating systems, ifc.V_ifc_len still gets set to correspond to the total
664 number of interfaces, even though they don't all fit in the buffer. */
665
666 if (ifc.V_ifc_len > sizeof(buf))
667   {
668   ifc.V_ifc_len = sizeof(buf);
669   DEBUG(D_interface)
670     debug_printf("more than %d interfaces found: remainder not used\n"
671       "(set MAX_INTERFACES in Local/Makefile and rebuild if you want more)\n",
672       MAX_INTERFACES);
673   }
674
675 /* For each interface, check it is an IP interface, get its flags, and see if
676 it is up; if not, skip.
677
678 BSD systems differ from others in what SIOCGIFCONF returns. Other systems
679 return a vector of ifreq structures whose size is as defined by the structure.
680 BSD systems allow sockaddrs to be longer than their sizeof, which in turn makes
681 the ifreq structures longer than their sizeof. The code below has its origins
682 in amd and ifconfig; it uses the sa_len field of each sockaddr to determine
683 each item's length.
684
685 This is complicated by the fact that, at least on BSD systems, the data in the
686 buffer is not guaranteed to be aligned. Thus, we must first copy the basic
687 struct to some aligned memory before looking at the field in the fixed part to
688 find its length, and then recopy the correct length. */
689
690 for (char * cp = buf; cp < buf + ifc.V_ifc_len; cp += len)
691   {
692   memcpy(CS &ifreq, cp, sizeof(ifreq));
693
694   #ifndef HAVE_SA_LEN
695   len = sizeof(struct V_ifreq);
696
697   #else
698   len = ((ifreq.ifr_addr.sa_len > sizeof(ifreq.ifr_addr))?
699           ifreq.ifr_addr.sa_len : sizeof(ifreq.ifr_addr)) +
700          sizeof(ifreq.V_ifr_name);
701   if (len > sizeof(addrbuf))
702     log_write(0, LOG_PANIC_DIE, "Address for %s interface is absurdly long",
703         ifreq.V_ifr_name);
704
705   #endif
706
707   /* If not an IP interface, skip */
708
709   if (ifreq.V_ifr_addr.V_family != AF_INET
710   #if HAVE_IPV6
711     && ifreq.V_ifr_addr.V_family != AF_INET6
712   #endif
713     ) continue;
714
715   /* Get the interface flags, and if the interface is down, continue. Formerly,
716   we treated the inability to get the flags as a panic-die error. However, it
717   seems that on some OS (Solaris 9 being the case noted), it is possible to
718   have an interface in this list for which this call fails because the
719   interface hasn't been "plumbed" to any protocol (IPv4 or IPv6). Therefore,
720   we now just treat this case as "down" as well. */
721
722   if (ioctl(vs, V_GIFFLAGS, CS &ifreq) < 0)
723     {
724     continue;
725     /*************
726     log_write(0, LOG_PANIC_DIE, "Unable to get flags for %s interface: %d %s",
727       ifreq.V_ifr_name, errno, strerror(errno));
728     *************/
729     }
730   if ((ifreq.V_ifr_flags & IFF_UP) == 0) continue;
731
732   /* On some operating systems we have to get the IP address of the interface
733   by another call. On others, it's already there, but we must copy the full
734   length because we only copied the basic length above, and anyway,
735   GIFFLAGS may have wrecked the data. */
736
737   #ifndef SIOCGIFCONF_GIVES_ADDR
738   if (ioctl(vs, V_GIFADDR, CS &ifreq) < 0)
739     log_write(0, LOG_PANIC_DIE, "Unable to get IP address for %s interface: "
740       "%d %s", ifreq.V_ifr_name, errno, strerror(errno));
741   addrp = &ifreq.V_ifr_addr;
742
743   #else
744   memcpy(addrbuf, cp + offsetof(struct V_ifreq, V_ifr_addr),
745     len - sizeof(ifreq.V_ifr_name));
746   addrp = (struct sockaddr *)addrbuf;
747   #endif
748
749   /* Create a data block for the address, fill in the data, and put it on the
750   chain. */
751
752   next = store_get(sizeof(ip_address_item), GET_UNTAINTED);
753   next->next = NULL;
754   next->port = 0;
755   (void)host_ntoa(-1, addrp, next->address, NULL);
756
757   if (yield == NULL) yield = last = next; else
758     {
759     last->next = next;
760     last = next;
761     }
762
763   DEBUG(D_interface) debug_printf("Actual local interface address is %s (%s)\n",
764     last->address, ifreq.V_ifr_name);
765   }
766
767 /* Close the socket, and return the chain of data blocks. */
768
769 (void)close(vs);
770 return yield;
771 }
772
773 #endif /* HAVE_GETIFADDRS */
774
775 #else  /* NO_FIND_INTERFACES */
776
777 /* Some experimental or developing OS (e.g. GNU/Hurd) do not have the ioctls,
778 and there is no other way to get a list of the (IP addresses of) local
779 interfaces. We just return the loopback address(es). */
780
781 ip_address_item *
782 os_common_find_running_interfaces(void)
783 {
784 ip_address_item *yield = store_get(sizeof(address_item), GET_UNTAINTED);
785 yield->address = US"127.0.0.1";
786 yield->port = 0;
787 yield->next = NULL;
788
789 #if HAVE_IPV6
790 yield->next = store_get(sizeof(address_item), GET_UNTAINTED);
791 yield->next->address = US"::1";
792 yield->next->port = 0;
793 yield->next->next = NULL;
794 #endif
795
796 DEBUG(D_interface) debug_printf("Unable to find local interface addresses "
797   "on this OS: returning loopback address(es)\n");
798 return yield;
799 }
800
801 #endif /* NO_FIND_INTERFACES */
802 #endif /* FIND_RUNNING_INTERFACES */
803
804
805
806
807 /* ----------------------------------------------------------------------- */
808
809 /***********************************************************
810 *                 DNS Resolver Base Finder                 *
811 ***********************************************************/
812
813 /* We need to be able to set options for the system resolver(5), historically
814 made available as _res.  At least one OS (NetBSD) now no longer provides this
815 directly, instead making you call a function per thread to get a handle.
816 Other OSs handle thread-safe resolver differently, in ways which fail if the
817 programmer creates their own structs. */
818
819 #if !defined(OS_GET_DNS_RESOLVER_RES) && !defined(COMPILE_UTILITY)
820
821 # include <resolv.h>
822
823 /* confirmed that res_state is typedef'd as a struct* on BSD and Linux, will
824 find out how unportable it is on other OSes, but most resolver implementations
825 should be descended from ISC's bind.
826
827 Linux and BSD do:
828   define _res (*__res_state())
829 identically.  We just can't rely on __foo functions.  It's surprising that use
830 of _res has been as portable as it has, for so long.
831
832 So, since _res works everywhere, and everything can decode the struct, I'm
833 going to gamble that res_state is a typedef everywhere and use that as the
834 return type.
835 */
836
837 res_state
838 os_get_dns_resolver_res(void)
839 {
840 return &_res;
841 }
842
843 #endif /* OS_GET_DNS_RESOLVER_RES */
844
845 /* ----------------------------------------------------------------------- */
846
847 /***********************************************************
848 *                 unsetenv()                               *
849 ***********************************************************/
850
851 /* Most modern systems define int unsetenv(const char*),
852 * some don't. */
853
854 #if !defined(OS_UNSETENV)
855 int
856 os_unsetenv(const unsigned char * name)
857 {
858 return unsetenv(CS name);
859 }
860 #endif
861
862 /* ----------------------------------------------------------------------- */
863
864 /***********************************************************
865 *               getcwd()                                   *
866 ***********************************************************/
867
868 /* Glibc allows getcwd(NULL, 0) to do auto-allocation. Some systems
869 do auto-allocation, but need the size of the buffer, and others
870 may not even do this. If the OS supports getcwd(NULL, 0) we'll use
871 this, for all other systems we provide our own getcwd() */
872
873 #if !defined(OS_GETCWD)
874 unsigned char *
875 os_getcwd(unsigned char * buffer, size_t size)
876 {
877 return US  getcwd(CS buffer, size);
878 }
879 #else
880 #ifndef PATH_MAX
881 # define PATH_MAX 4096
882 #endif
883 unsigned char *
884 os_getcwd(unsigned char * buffer, size_t size)
885 {
886 char * b = CS buffer;
887
888 if (!size) size = PATH_MAX;
889 if (!b && !(b = malloc(size))) return NULL;
890 if (!(b = getcwd(b, size))) return NULL;
891 return buffer ? buffer : realloc(b, strlen(b) + 1);
892 }
893 #endif
894
895 /* ----------------------------------------------------------------------- */
896
897
898
899
900 /*************************************************
901 **************************************************
902 *             Stand-alone test program           *
903 **************************************************
904 *************************************************/
905
906
907 #ifdef STAND_ALONE
908
909 #ifdef CLOCKS_PER_SEC
910 #define REAL_CLOCK_TICK CLOCKS_PER_SEC
911 #else
912   #ifdef CLK_TCK
913   #define REAL_CLOCK_TICK CLK_TCK
914   #else
915   #define REAL_CLOCK_TICK 1000000   /* SunOS4 */
916   #endif
917 #endif
918
919
920 int main(int argc, char **argv)
921 {
922 char buffer[128];
923 int fd = fileno(stdin);
924 int rc;
925
926 printf("Testing restarting signal; wait for handler message, then type a line\n");
927 strcpy(buffer, "*** default ***\n");
928 os_restarting_signal(SIGALRM, sigalrm_handler);
929 ALARM(2);
930 if ((rc = read(fd, buffer, sizeof(buffer))) < 0)
931   printf("No data read\n");
932 else
933   {
934   buffer[rc] = 0;
935   printf("Read: %s", buffer);
936   }
937 ALARM_CLR(0);
938
939 printf("Testing non-restarting signal; should read no data after handler message\n");
940 strcpy(buffer, "*** default ***\n");
941 os_non_restarting_signal(SIGALRM, sigalrm_handler);
942 ALARM(2);
943 if ((rc = read(fd, buffer, sizeof(buffer))) < 0)
944   printf("No data read\n");
945 else
946   {
947   buffer[rc] = 0;
948   printf("Read: %s", buffer);
949   }
950 ALARM_CLR(0);
951
952 printf("Testing load averages (last test - ^C to kill)\n");
953 for (;;)
954   {
955   int avg;
956   clock_t used;
957   clock_t before = clock();
958   avg = os_getloadavg();
959   used = clock() - before;
960   printf("cpu time = %.2f ", (double)used/REAL_CLOCK_TICK);
961   if (avg < 0)
962     {
963     printf("load average not available\n");
964     break;
965     }
966   printf("load average = %.2f\n", (double)avg/1000.0);
967   sleep(2);
968   }
969 return 0;
970 }
971
972 #endif
973
974 /* End of os.c */