- fix case where ll_delete removes the last entry
[l2tpns.git] / util.c
1 /* Misc util functions */
2
3 char const *cvs_id_util = "$Id: util.c,v 1.6 2004/11/16 07:54:32 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 char *inet_toa(unsigned long addr)
20 {
21 struct in_addr in;
22 memcpy(&in, &addr, sizeof(unsigned long));
23 return inet_ntoa(in);
24 }
25
26 void *shared_malloc(unsigned int size)
27 {
28 void * p;
29 p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
30
31 if (p == MAP_FAILED)
32 p = NULL;
33
34 return p;
35 }
36
37 extern int udpfd, controlfd, tunfd, snoopfd, ifrfd, cluster_sockfd;
38 extern int *radfds;
39
40 pid_t fork_and_close()
41 {
42 pid_t pid = fork();
43 int i;
44
45 if (pid)
46 return pid;
47
48 if (config->scheduler_fifo)
49 {
50 struct sched_param params = {0};
51 params.sched_priority = 0;
52 if (sched_setscheduler(0, SCHED_OTHER, &params))
53 {
54 LOG(0, 0, 0, 0, "Error setting scheduler to OTHER after fork: %s\n", strerror(errno));
55 LOG(0, 0, 0, 0, "This is probably really really bad.\n");
56 }
57 }
58
59 signal(SIGPIPE, SIG_DFL);
60 signal(SIGCHLD, SIG_DFL);
61 signal(SIGHUP, SIG_DFL);
62 signal(SIGUSR1, SIG_DFL);
63 signal(SIGQUIT, SIG_DFL);
64 signal(SIGKILL, SIG_DFL);
65 signal(SIGALRM, SIG_DFL);
66 signal(SIGTERM, SIG_DFL);
67
68 // Close sockets
69 if (tunfd != -1) close(tunfd);
70 if (udpfd != -1) close(udpfd);
71 if (controlfd != -1) close(controlfd);
72 if (snoopfd != -1) close(snoopfd);
73 if (ifrfd != -1) close(ifrfd);
74 if (cluster_sockfd != -1) close(cluster_sockfd);
75 if (clifd != -1) close(clifd);
76
77 for (i = 0; radfds && i < config->num_radfds; i++)
78 close(radfds[i]);
79 #ifdef BGP
80 for (i = 0; i < BGP_NUM_PEERS; i++)
81 if (bgp_peers[i].sock != -1)
82 close(bgp_peers[i].sock);
83 #endif /* BGP */
84
85 return pid;
86 }