bug fix
[l2tpns.git] / util.c
1 /* Misc util functions */
2
3 char const *cvs_id_util = "$Id: util.c,v 1.12 2005/06/28 14:48:28 bodea Exp $";
4
5 #include <unistd.h>
6 #include <errno.h>
7 #include <sched.h>
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
11 #include <string.h>
12 #include <sys/mman.h>
13
14 #include "l2tpns.h"
15 #ifdef BGP
16 #include "bgp.h"
17 #endif
18
19 // format ipv4 addr as a dotted-quad; n chooses one of 4 static buffers
20 // to use
21 char *fmtaddr(in_addr_t addr, int n)
22 {
23 static char addrs[4][16];
24 struct in_addr in;
25
26 if (n < 0 || n >= 4) return "";
27 in.s_addr = addr;
28 return strcpy(addrs[n], inet_ntoa(in));
29 }
30
31 void *shared_malloc(unsigned int size)
32 {
33 void * p;
34 p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
35
36 if (p == MAP_FAILED)
37 p = NULL;
38
39 return p;
40 }
41
42 extern int forked;
43 extern int cluster_sockfd, tunfd, udpfd, controlfd, daefd, snoopfd, ifrfd, ifr6fd, rand_fd;
44 extern int *radfds;
45
46 pid_t fork_and_close()
47 {
48 pid_t pid = fork();
49 int i;
50
51 if (pid)
52 return pid;
53
54 forked++;
55 if (config->scheduler_fifo)
56 {
57 struct sched_param params = {0};
58 params.sched_priority = 0;
59 if (sched_setscheduler(0, SCHED_OTHER, &params))
60 {
61 LOG(0, 0, 0, "Error setting scheduler to OTHER after fork: %s\n", strerror(errno));
62 LOG(0, 0, 0, "This is probably really really bad.\n");
63 }
64 }
65
66 signal(SIGPIPE, SIG_DFL);
67 signal(SIGCHLD, SIG_DFL);
68 signal(SIGHUP, SIG_DFL);
69 signal(SIGUSR1, SIG_DFL);
70 signal(SIGQUIT, SIG_DFL);
71 signal(SIGKILL, SIG_DFL);
72 signal(SIGALRM, SIG_DFL);
73 signal(SIGTERM, SIG_DFL);
74
75 // Close sockets
76 if (clifd != -1) close(clifd);
77 if (cluster_sockfd != -1) close(cluster_sockfd);
78 if (tunfd != -1) close(tunfd);
79 if (udpfd != -1) close(udpfd);
80 if (controlfd != -1) close(controlfd);
81 if (daefd != -1) close(daefd);
82 if (snoopfd != -1) close(snoopfd);
83 if (ifrfd != -1) close(ifrfd);
84 if (ifr6fd != -1) close(ifr6fd);
85 if (rand_fd != -1) close(rand_fd);
86 if (epollfd != -1) close(epollfd);
87
88 for (i = 0; radfds && i < RADIUS_FDS; i++)
89 close(radfds[i]);
90 #ifdef BGP
91 for (i = 0; i < BGP_NUM_PEERS; i++)
92 if (bgp_peers[i].sock != -1)
93 close(bgp_peers[i].sock);
94 #endif /* BGP */
95
96 return pid;
97 }