]> git.tdb.fi Git - netmon.git/blob - main.c
Move trigger into its own subsystem
[netmon.git] / main.c
1 /*
2 netmon - a simple network connectivity monitor
3 Copyright © 2008-2016 Mikko Rasa, Mikkosoft Productions
4 Distributed under the GPL
5 */
6
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <errno.h>
13 #include <syslog.h>
14 #include <sys/poll.h>
15 #include <sys/socket.h>
16 #include <sys/time.h>
17 #include <sys/wait.h>
18 #include <net/ethernet.h>
19 #include <netinet/in.h>
20 #include <netinet/ip.h>
21 #include <netinet/ip_icmp.h>
22 #include <netinet/ip6.h>
23 #include <netdb.h>
24 #include <arpa/inet.h>
25 #include <pcap/pcap.h>
26
27 typedef unsigned long long Time;
28
29 typedef struct
30 {
31         struct sockaddr_storage address;
32         struct sockaddr_storage mask;
33 } Address;
34
35 typedef struct
36 {
37         char *interface_name;
38         pcap_t *pcap;
39         unsigned n_addresses;
40         Address *addresses;
41         Time last_receive;
42         Time last_transmit;
43         int connection_status;
44         Time connection_down_time;
45 } Monitor;
46
47 typedef struct
48 {
49         Monitor *monitor;
50         Time delay;
51         Time interval;
52         const char *command;
53         Time next;
54         pid_t child_pid;
55 } Trigger;
56
57 typedef struct
58 {
59         const char *target_name;
60         struct sockaddr_in target_addr;
61         int socket;
62         struct pollfd pfd;
63         Time next;
64         uint16_t id;
65         uint16_t seq;
66         uint16_t pending;
67         unsigned count;
68         unsigned lost;
69 } Pinger;
70
71 Time current_time();
72 int monitor_init(Monitor *);
73 void monitor_check(Monitor *, Time);
74 void capture_handler(uint8_t *, const struct pcap_pkthdr *, const uint8_t *);
75 int trigger_init(Trigger *);
76 void trigger_check(Trigger *, Time);
77 int get_inet_scope(uint32_t, const Address *);
78 int get_inet6_scope(const struct in6_addr *, const Address *);
79 int pinger_init(Pinger *);
80 void pinger_check(Pinger *, Time);
81 unsigned checksum(const char *, unsigned);
82 void send_ping(Pinger *);
83 pid_t run_command(const char *);
84
85 int no_daemon;
86 int verbose;
87
88 int main(int argc, char **argv)
89 {
90         Monitor monitor;
91         Trigger trigger;
92         Pinger pinger;
93         int o;
94         char *endp;
95         Time stats_interval = 1800000000ULL;
96
97         no_daemon = 0;
98         verbose = 0;
99         monitor.interface_name = NULL;
100         trigger.monitor = &monitor;
101         trigger.delay = 60000000ULL;
102         trigger.interval = 600000000ULL;
103         pinger.target_name = NULL;
104
105         /* Parse options */
106         while((o = getopt(argc, argv, "fvs:t:c:i:p:"))!=-1)
107                 switch(o)
108                 {
109                 case 'f':
110                         no_daemon = 1;
111                         break;
112                 case 'v':
113                         verbose = 1;
114                         break;
115                 case 's':
116                         stats_interval = strtoul(optarg, NULL, 10)*1000000;
117                         break;
118                 case 't':
119                         trigger.delay = strtoul(optarg, &endp, 10)*1000000;
120                         if(*endp==',')
121                                 trigger.interval = strtoul(endp+1, NULL, 10)*1000000;
122                         else
123                                 trigger.interval = trigger.delay;
124                         break;
125                 case 'c':
126                         trigger.command = optarg;
127                         break;
128                 case 'i':
129                         monitor.interface_name = strdup(optarg);
130                         break;
131                 case 'p':
132                         pinger.target_name = strdup(optarg);
133                         break;
134                 }
135
136         if(monitor.interface_name)
137         {
138                 monitor_init(&monitor);
139
140                 if(trigger.command)
141                         trigger_init(&trigger);
142         }
143
144         if(pinger.target_name)
145                 pinger_init(&pinger);
146
147         if(!no_daemon && daemon(1, 0)==-1)
148                 perror("daemon");
149
150         openlog("netmon", 0, LOG_LOCAL7);
151
152         Time next_stats = current_time()+stats_interval;
153         while(1)
154         {
155                 Time time = current_time();
156
157                 if(monitor.interface_name)
158                 {
159                         monitor_check(&monitor, time);
160
161                         if(trigger.command)
162                                 trigger_check(&trigger, time);
163                 }
164
165                 if(pinger.target_name)
166                 {
167                         pinger_check(&pinger, time);
168
169                         if(time>=next_stats)
170                         {
171                                 if(pinger.count)
172                                 {
173                                         float loss_ratio = (float)pinger.lost/pinger.count;
174                                         if(no_daemon)
175                                                 printf("Packet loss: %.2f%%\n", loss_ratio*100);
176                                         else
177                                                 syslog(LOG_INFO, "Packet loss: %.2f%%", loss_ratio*100);
178                                 }
179
180                                 pinger.count = 0;
181                                 pinger.lost = 0;
182                                 next_stats += stats_interval;
183                         }
184                 }
185         }
186
187         closelog();
188
189         return 0;
190 }
191
192 Time current_time()
193 {
194         struct timeval tv;
195         gettimeofday(&tv, NULL);
196         return tv.tv_sec*1000000ULL+tv.tv_usec;
197 }
198
199 int monitor_init(Monitor *monitor)
200 {
201         char err[PCAP_ERRBUF_SIZE];
202         pcap_if_t *devs;
203         if(pcap_findalldevs(&devs, err)==-1)
204         {
205                 fprintf(stderr, "pcap_findalldevs: %s\n", err);
206                 return -1;
207         }
208
209         monitor->pcap = pcap_open_live(monitor->interface_name, 64, 0, 10, err);
210         if(!monitor->pcap)
211         {
212                 fprintf(stderr, "pcap_findalldevs: %s\n", err);
213                 return -1;
214         }
215
216         if(pcap_setnonblock(monitor->pcap, 1, err)==-1)
217         {
218                 fprintf(stderr, "pcap_findalldevs: %s\n", err);
219                 return -1;
220         }
221
222         monitor->n_addresses = 0;
223         monitor->addresses = NULL;
224         for(pcap_if_t *d=devs; d; d=d->next)
225                 for(pcap_addr_t *a=d->addresses; a; a=a->next)
226                         if(a->addr->sa_family==AF_INET || a->addr->sa_family==AF_INET6)
227                         {
228                                 monitor->addresses = (Address *)realloc(monitor->addresses, (monitor->n_addresses+1)*sizeof(Address));
229                                 unsigned size = (a->addr->sa_family==AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
230                                 memcpy(&monitor->addresses[monitor->n_addresses].address, a->addr, size);
231                                 memcpy(&monitor->addresses[monitor->n_addresses].mask, a->netmask, size);
232                                 ++monitor->n_addresses;
233                         }
234
235         pcap_freealldevs(devs);
236
237         monitor->last_receive = 0;
238         monitor->last_transmit = 0;
239         monitor->connection_status = 1;
240
241         return 0;
242 }
243
244 void monitor_check(Monitor *monitor, Time timestamp)
245 {
246         pcap_dispatch(monitor->pcap, -1, &capture_handler, (uint8_t *)monitor);
247
248         if(monitor->last_transmit && monitor->last_receive)
249         {
250                 /* If packets have been transmitted more recently than received, there
251                 might be a problem */
252                 if(monitor->last_transmit>monitor->last_receive)
253                 {
254                         if(monitor->connection_status && timestamp>=monitor->last_receive+10000000)
255                         {
256                                 monitor->connection_status = 0;
257                                 monitor->connection_down_time = monitor->last_receive;
258                                 if(no_daemon)
259                                         printf("Connection is down\n");
260                                 else
261                                         syslog(LOG_INFO, "Connection is down");
262                         }
263                 }
264                 else if(!monitor->connection_status)
265                 {
266                         Time duration = timestamp-monitor->connection_down_time;
267                         monitor->connection_status = 1;
268                         if(no_daemon)
269                                 printf("Connection is up (was down for %lld seconds)\n", duration/1000000);
270                         else
271                                 syslog(LOG_INFO, "Connection is up (was down for %lld seconds)", duration/1000000);
272                 }
273         }
274 }
275
276 void capture_handler(uint8_t *user, const struct pcap_pkthdr *header, const uint8_t *data)
277 {
278         Monitor *monitor = (Monitor *)user;
279         const struct ether_header *eth = (const struct ether_header *)(data);
280
281         int src_scope = 0;
282         int dst_scope = 0;
283         int proto = ntohs(eth->ether_type);
284         if(proto==ETHERTYPE_IP)
285         {
286                 const struct ip *ip = (const struct ip *)(eth+1);
287                 if(ntohl(ip->ip_dst.s_addr)>>28==14)
288                         dst_scope = 3;
289
290                 for(unsigned i=0; i<monitor->n_addresses; ++i)
291                         if(monitor->addresses[i].address.ss_family==AF_INET)
292                         {
293                                 int s = get_inet_scope(ip->ip_src.s_addr, &monitor->addresses[i]);
294                                 if(s>src_scope)
295                                         src_scope = s;
296
297                                 s = get_inet_scope(ip->ip_dst.s_addr, &monitor->addresses[i]);
298                                 if(s>dst_scope)
299                                         dst_scope = s;
300                         }
301         }
302         else if(proto==ETHERTYPE_IPV6)
303         {
304                 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)(eth+1);
305                 for(unsigned i=0; i<monitor->n_addresses; ++i)
306                         if(monitor->addresses[i].address.ss_family==AF_INET6)
307                         {
308                                 int s = get_inet6_scope(&ip6->ip6_src, &monitor->addresses[i]);
309                                 if(s>src_scope)
310                                         src_scope = s;
311
312                                 s = get_inet6_scope(&ip6->ip6_dst, &monitor->addresses[i]);
313                                 if(s>dst_scope)
314                                         dst_scope = s;
315                         }
316         }
317
318         Time timestamp = header->ts.tv_sec*1000000ULL+header->ts.tv_usec;
319         if(src_scope==0 && dst_scope>0)
320                 monitor->last_receive = timestamp;
321         else if(src_scope>0 && dst_scope==0)
322                 monitor->last_transmit = timestamp;
323 }
324
325 int trigger_init(Trigger *trigger)
326 {
327         trigger->next = trigger->delay;
328         trigger->child_pid = 0;
329
330         return 0;
331 }
332
333 void trigger_check(Trigger *trigger, Time time)
334 {
335         Monitor *monitor = trigger->monitor;
336
337         if(monitor->connection_status)
338                 trigger->next = trigger->delay;
339         else if(time>=monitor->last_receive+trigger->next)
340         {
341                 if(no_daemon)
342                         printf("Running %s\n", trigger->command);
343                 else
344                         syslog(LOG_INFO, "Running %s", trigger->command);
345                 trigger->child_pid = run_command(trigger->command);
346                 trigger->next += trigger->interval;
347         }
348
349         /* Reap any finished child process */
350         if(trigger->child_pid)
351         {
352                 if(waitpid(trigger->child_pid, NULL, WNOHANG)==trigger->child_pid)
353                         trigger->child_pid = 0;
354         }
355 }
356
357 int get_inet_scope(uint32_t addr, const Address *local_addr)
358 {
359         uint32_t diff = addr^((struct sockaddr_in *)&local_addr->address)->sin_addr.s_addr;
360         if(!diff)
361                 return 2;
362         else if(!(diff&((struct sockaddr_in *)&local_addr->mask)->sin_addr.s_addr))
363                 return 1;
364         else
365                 return 0;
366 }
367
368 int get_inet6_scope(const struct in6_addr *addr, const Address *local_addr)
369 {
370         int result = 2;
371         for(unsigned i=0; i<16; ++i)
372         {
373                 uint8_t diff = addr->s6_addr[i]^((struct sockaddr_in6 *)&local_addr->address)->sin6_addr.s6_addr[i];
374                 if(diff)
375                 {
376                         diff &= ((struct sockaddr_in6 *)&local_addr->mask)->sin6_addr.s6_addr[i];
377                         if(diff)
378                                 return 0;
379                         else
380                                 result = 1;
381                 }
382         }
383
384         return result;
385 }
386
387 int pinger_init(Pinger *pinger)
388 {
389         if(!pinger->target_name)
390                 return -1;
391
392         struct hostent *host;
393
394         host = gethostbyname(pinger->target_name);
395         if(!host)
396         {
397                 herror("gethostbyname");
398                 return -1;
399         }
400
401         if(host->h_addrtype!=AF_INET)
402         {
403                 fprintf(stderr, "Got a hostent, but it doesn't have an IPv4 address");
404                 return -1;
405         }
406
407         pinger->target_addr.sin_family = AF_INET;
408         pinger->target_addr.sin_addr = *(struct in_addr *)host->h_addr_list[0];
409
410         if(verbose)
411         {
412                 char buf[64];
413                 inet_ntop(AF_INET, &pinger->target_addr.sin_addr, buf, sizeof(buf));
414                 printf("Ping target is %s\n", buf);
415         }
416
417         pinger->socket = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP);
418         if(pinger->socket==-1)
419         {
420                 perror("socket");
421                 return -1;
422         }
423
424         pinger->next = 0;
425         pinger->id = getpid();
426         pinger->seq = 1;
427         pinger->pending = 0;
428         pinger->count = 0;
429         pinger->lost = 0;
430
431         pinger->pfd.fd = pinger->socket;
432         pinger->pfd.events = POLLIN;
433
434         return 0;
435 }
436
437 void pinger_check(Pinger *pinger, Time time)
438 {
439         if(poll(&pinger->pfd, 1, 10)>0)
440         {
441                 struct sockaddr_in addr;
442                 socklen_t alen = sizeof(addr);
443
444                 /* Receive a packet */
445                 char data[1500];
446                 int len = recvfrom(pinger->socket, data, sizeof(data), 0, (struct sockaddr *)&addr, &alen);
447                 if(len==-1)
448                         fprintf(stderr, "recvfrom error: %s\n", strerror(errno));
449                 else
450                 {
451                         struct ip *ip = (struct ip *)data;
452                         if(ip->ip_p==IPPROTO_ICMP)
453                         {
454                                 struct icmp *icmp = (struct icmp *)(ip+1);
455                                 if(icmp->icmp_type==ICMP_ECHOREPLY && icmp->icmp_id==pinger->id)
456                                 {
457                                         /* It's an ICMP echo reply and ours, process it */
458                                         if(verbose)
459                                         {
460                                                 char buf[64];
461                                                 inet_ntop(AF_INET, &addr.sin_addr, buf, sizeof(buf));
462                                                 printf("Ping reply from %s\n", buf);
463                                         }
464
465                                         if(icmp->icmp_seq==pinger->pending)
466                                                 pinger->pending = 0;
467                                         else if(verbose)
468                                                 printf("Sequence %d, expected %d\n", icmp->icmp_seq, pinger->pending);
469                                 }
470                         }
471                 }
472         }
473
474         if(time>=pinger->next)
475         {
476                 if(pinger->pending)
477                 {
478                         ++pinger->lost;
479                         if(verbose)
480                                 printf("Lost ping\n");
481                 }
482
483                 send_ping(pinger);
484                 pinger->next = time+1000000;
485         }
486 }
487
488 unsigned checksum(const char *data, unsigned len)
489 {
490         unsigned        sum = 0;
491         for(unsigned i=0; i<len; i+=2)
492                 sum += *(const unsigned short *)(data+i);
493         while(sum>0xFFFF)
494                 sum = (sum>>16)+(sum&0xFFFF);
495
496         return ~sum;
497 }
498
499 void send_ping(Pinger *pinger)
500 {
501         char data[64];
502         for(unsigned i=0; i<sizeof(data); ++i)
503                 data[i] = i;
504
505         struct icmp *hdr = (struct icmp *)data;
506         hdr->icmp_type = ICMP_ECHO;
507         hdr->icmp_code = 0;
508         hdr->icmp_cksum = 0;
509         hdr->icmp_id = pinger->id;
510         hdr->icmp_seq = pinger->seq;
511         hdr->icmp_cksum = checksum(data, sizeof(data));
512
513         if(sendto(pinger->socket, data, sizeof(data), 0, (struct sockaddr *)&pinger->target_addr, sizeof(struct sockaddr_in))==-1)
514                 fprintf(stderr, "sendto error: %s\n", strerror(errno));
515
516         pinger->pending = pinger->seq++;
517         if(!pinger->seq)
518                 ++pinger->seq;
519         ++pinger->count;
520 }
521
522 pid_t run_command(const char *cmd)
523 {
524         pid_t pid;
525
526         pid = fork();
527         if(pid==0)
528         {
529                 const char *argv[2];
530                 argv[0] = cmd;
531                 argv[1] = 0;
532                 execv(cmd, (char *const *)argv);
533                 exit(127);
534         }
535         else
536                 return pid;
537 }