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