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