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