aboutsummaryrefslogtreecommitdiff
path: root/src/pinger.c
blob: 2517781ab8bb062a8a77fa122071132f1a962baa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
/* This file is part of Ping903
   Copyright (C) 2020 Sergey Poznyakoff
  
   Ping903 is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.
  
   Ping903 is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with Ping903.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/stat.h>

#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <limits.h>
#include <poll.h>
#include "ping903.h"
#include "json.h"
#include "defs.h"

unsigned long probe_interval = 60;
unsigned long ping_interval = 1;
unsigned long ping_count = 10;
unsigned long ping_tolerance = 3;

static double
nabs(double a)
{
	return (a < 0) ? -a : a;
}

static double
nsqrt(double a, double prec)
{
	double x0, x1;

	if (a < 0)
		return 0;
	if (a < prec)
		return 0;
	x1 = a / 2;
	do {
		x0 = x1;
		x1 = (x0 + a / x0) / 2;
	} while (nabs(x1 - x0) > prec);
	return x1;
}

static inline int
timeval_is_null(struct timeval const *tv)
{
	return tv->tv_sec == 0 && tv->tv_usec == 0;
}

static inline double
timeval_to_double(struct timeval const *tv)
{
	return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
}

enum { NANOSEC_IN_SEC = 1000000000 };

static inline void
timespec_add(struct timespec const *a, struct timespec const *b,
	     struct timespec *res)
{
	res->tv_sec = a->tv_sec + b->tv_sec;
	res->tv_nsec = a->tv_nsec + b->tv_nsec;
	if (res->tv_nsec >= NANOSEC_IN_SEC) {
		++res->tv_sec;
		res->tv_nsec -= NANOSEC_IN_SEC;
	}
}

static inline void
timespec_incr(struct timespec *a, struct timespec const *b)
{
	struct timespec t = *a;
	timespec_add(&t, b, a);
}

static HOSTPING *hostping_head, *hostping_tail;
static size_t hostping_count;
static pthread_rwlock_t hostping_rwlock = PTHREAD_RWLOCK_INITIALIZER;
static size_t conf_hostping_count;
static int hostping_updated;

void
hostping_add(char const *name, struct sockaddr *addr, socklen_t addrlen)
{
	HOSTPING *hp = emalloc(sizeof(*hp));
	
	memset(hp, 0, sizeof(*hp));
	hp->name = estrdup(name);
	hp->addr = emalloc(addrlen);
	memcpy(hp->addr, addr, addrlen);
	hp->addrlen =addrlen;
	pthread_mutex_init(&hp->mutex, NULL);

	hp->next = NULL;
	hp->prev = hostping_tail;
	if (hostping_tail)
		hostping_tail->next = hp;
	else
		hostping_head = hp;
	hostping_tail = hp;
	
	hostping_count++;
	hostping_updated = 1;
}

void
hostping_delete(HOSTPING *hp)
{
	if (hp->prev)
		hp->prev->next = hp->next;
	else
		hostping_head = hp->next;
	if (hp->next)
		hp->next->prev = hp->prev;
	else
		hostping_tail = hp->prev;
	hostping_count--;
	hostping_updated = 1;
	
	free(hp->name);
	free(hp->addr);
	pthread_mutex_destroy(&hp->mutex);
	free(hp);
}

#define FOR_EACH_HOSTPING(hp) for (hp = hostping_head; hp; hp = hp->next)

static inline void
hostping_lock(HOSTPING *host)
{
	pthread_mutex_lock(&host->mutex);
}

static inline void
hostping_unlock(HOSTPING *host)
{
	pthread_mutex_unlock(&host->mutex);
}

static void
hostping_extract_stat(HOSTPING *host, struct host_stat *st)
{
	memcpy(&st->start_tv, &host->start_tv,
	       sizeof(host->stat_last.start_tv));
	memcpy(&st->stop_tv,
	       timeval_is_null(&host->recv_tv)
	         ? &host->xmit_tv : &host->recv_tv,
	       sizeof(host->stat_last.stop_tv));
	st->xmit_count = host->xmit_count;
	st->recv_count = host->recv_count;
	st->tmin       = host->tmin;            
	st->tmax       = host->tmax;
	if (host->recv_count > 0) {
		double total = host->recv_count; //FIXME: repeat count?
		double avg = host->tsum / total;
		double vari = host->tsumsq / total - avg * avg;
	
		st->avg    = avg;
		st->stddev = nsqrt(vari, 0.0005);
	}
}

static void
hostping_commit(HOSTPING *host)
{	
	if (host->stat_last.status != HOST_STAT_VALID) {
		hostping_extract_stat(host, &host->stat_last);
		host->stat_last.status = HOST_STAT_VALID;
	}
}

/* Reset runtime statistics counters */
static void
hostping_reset(HOSTPING *host)
{
	hostping_lock(host);
	if (host->xmit_count > 0)
		hostping_commit(host);
	host->xmit_count = 0;
	host->recv_count = 0;
	host->tmin = 999999999.0;
	host->tmax = 0;
	host->tsum = 0;
	host->tsumsq = 0;
	switch (host->stat_last.status) {
	case HOST_STAT_INIT:
		break;
	case HOST_STAT_VALID:
		host->stat_last.status = HOST_STAT_PENDING;
		break;
	case HOST_STAT_PENDING:
		host->stat_last.status = HOST_STAT_INVALID;
		break;
	case HOST_STAT_INVALID:
		break;
	}
	hostping_unlock(host);
}

static int
get_hostping_stat(HOSTPING *host, struct json_value **retval)
{
	struct json_value *obj, *v;
	struct host_stat const *st;
	struct host_stat stbuf;
	static char const *host_stat_status[] = {
		"init",
		"valid",
		"pending",
		"invalid"
	};
	int validity;
	double ts;

	hostping_lock(host);
	if (!(obj = json_new_object()))
		goto err;

	if (!(v = json_new_string(host->name))
	    || json_object_set(obj, "name", v))
		goto err;

	if (host_stat_is_valid(&host->stat_last)) {
		st = &host->stat_last;
		validity = 1;
	} else if (host->stat_last.status == HOST_STAT_INIT
		   && host->xmit_count > ping_tolerance) {
		hostping_extract_stat(host, &stbuf);
		stbuf.status = HOST_STAT_PENDING;
		st = &stbuf;
		validity = 1;
	} else {
		st = NULL;
		validity = 0;
	}

	if (!(v = json_new_bool(validity))
	    || json_object_set(obj, "validity", v))
		goto err;

	if (!(v = json_new_string(host_stat_status[host->stat_last.status]))
	    || json_object_set(obj, "status", v))
		goto err;	
	ts = timeval_to_double(&host->xmit_tv);
	if (!(v = json_new_number(ts))
	    || json_object_set(obj, "xmit-timestamp", v))
			goto err;

	if (st) {
		int is_alive = st->xmit_count - st->recv_count
			        < ping_tolerance;
	
		if (!(v = json_new_string(host_stat_status[st->status]))
		    || json_object_set(obj, "status", v))
			goto err;	

		ts = timeval_to_double(&st->start_tv);
		if (!(v = json_new_number(ts))
		    || json_object_set(obj, "start-timestamp", v))
			goto err;
		ts = timeval_to_double(&st->stop_tv);
		if (!(v = json_new_number(ts))
		    || json_object_set(obj, "stop-timestamp", v))
			goto err;
		if (!(v = json_new_bool(is_alive))
		    || json_object_set(obj, "alive", v))
			goto err;
		if (!(v = json_new_number(st->xmit_count))
		    || json_object_set(obj, "xmit", v))
			goto err;		
		if (!(v = json_new_number(st->recv_count))
		    || json_object_set(obj, "recv", v))
			goto err;
		if (!(v = json_new_number((double) 100
					  * (st->xmit_count - st->recv_count)
					  / st->xmit_count))
		    || json_object_set(obj, "loss", v))
			goto err;
		
		if (st->recv_count > 0) {
			if (!(v = json_new_number(st->tmin))
			    || json_object_set(obj, "tmin", v))
				goto err;
			if (!(v = json_new_number(st->tmax))
			    || json_object_set(obj, "tmax", v))
				goto err;
			if (!(v = json_new_number(st->avg))
			    || json_object_set(obj, "avg", v))
				goto err;
			if (!(v = json_new_number(st->stddev))
			    || json_object_set(obj, "stddev", v))
				goto err;
		}
	} else {
		if (!(v = json_new_string(host_stat_status[host->stat_last.status]))
		    || json_object_set(obj, "status", v))
		goto err;	
	}

	hostping_unlock(host);

	*retval = obj;
	return 0;
	
  err:
	hostping_unlock(host);
	error("out of memory when formatting statistics for %s", host->name);
	json_value_free(v);
	json_value_free(obj);

	return -1;
}

int
get_hostname_stat(char const *name, struct json_value **retval)
{
	HOSTPING *hp;
	int rc = 0;
	
	*retval = NULL;
	pthread_rwlock_rdlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		if (strcmp(hp->name, name) == 0) {
			rc = get_hostping_stat(hp, retval);
			break;
		}
	}
	pthread_rwlock_unlock(&hostping_rwlock);
	return rc;
}

int
get_ipaddr_stat(struct sockaddr *sa, int salen, struct json_value **retval)
{
	HOSTPING *hp;
	int rc;
	
	*retval = NULL;
	pthread_rwlock_rdlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		if (hp->addrlen == salen
		    && memcmp(hp->addr, sa, salen) == 0) {
			rc = get_hostping_stat(hp, retval);
			break;
		}
	}
	pthread_rwlock_unlock(&hostping_rwlock);
	return 0;
}

int
get_all_host_stat(struct json_value **retval)
{
	struct json_value *ar;
	HOSTPING *hp;
	int rc = 0;
	
	if (!(ar = json_new_array()))
		return -1;
	pthread_rwlock_rdlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		struct json_value *v;
		if (get_hostping_stat(hp, &v)) {
			rc = -1;
			break;
		}
		if (json_array_append(ar, v)) {
			json_value_free(v);
			rc = -1;
			break;
		}
	}
	pthread_rwlock_unlock(&hostping_rwlock);
	if (rc == 0)
		*retval = ar;
	else
		json_value_free(ar);
	return rc;
}

int
get_all_hosts(struct json_value **retval)
{
	struct json_value *ar;
	HOSTPING *hp;
	int rc = 0;
	
	if (!(ar = json_new_array()))
		return -1;
	pthread_rwlock_rdlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		struct json_value *jv;
		jv = json_new_string(hp->name);
		if (!jv) {
			rc = -1;
			break;
		}
		if (json_array_append(ar, jv)) {
			json_value_free(jv);
			rc = -1;
			break;
		}
	}
	pthread_rwlock_unlock(&hostping_rwlock);
	if (rc == 0)
		*retval = ar;
	else
		json_value_free(ar);
	return rc;
}

int 
get_host_matches(struct addrinfo **aip, struct json_value **retval)
{
	struct json_value *ar;
	HOSTPING *hp;
	struct addrinfo *ai_head = NULL, *ai_tail = NULL;
	struct addrinfo *ai = *aip;
	int ret = -1;
	
	if (!(ar = json_new_array()))
		return -1;
	pthread_rwlock_rdlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		struct addrinfo *prev = NULL, *p;
		if (!ai)
			break;
		p = ai;
		while (p) {
			struct addrinfo *next = p->ai_next;
			if (p->ai_addrlen == hp->addrlen
			    && memcmp(hp->addr, p->ai_addr,
				      hp->addrlen) == 0) {
				struct json_value *jv;

				jv = json_new_string(hp->name);
				if (!jv)
					goto err;
				if (json_array_append(ar, jv)) {
					json_value_free(jv);
					goto err;
				}

				if (prev)
					prev->ai_next = next;
				else
					ai = next;

				p->ai_next = NULL;
				if (ai_tail)
					ai_tail->ai_next = p;
				else
					ai_head = p;
				ai_tail = p;
				
				break;
			} else {
				prev = p;
				p = next;
			}
		}
	}

	ret = 0;
	*retval = ar;
	ar = NULL;
err:	
	pthread_rwlock_unlock(&hostping_rwlock);
	if (ai_tail) {
		ai_tail->ai_next = ai;
		*aip = ai_head;
	}
	json_value_free(ar);
	return ret;
}

int
hostping_delete_by_name(char const *name)
{
	HOSTPING *hp;
	int rc = -1;
	
	pthread_rwlock_wrlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		if (strcmp(hp->name, name) == 0) {
			hostping_delete(hp);
			rc = 0;
			break;
		}
	}
	pthread_rwlock_unlock(&hostping_rwlock);
	return rc;
}

int
hostping_add_name(char const *name)
{
	int rc = 0;
	struct addrinfo hints, *res;
	HOSTPING *hp;
	
	pthread_rwlock_rdlock(&hostping_rwlock);
	FOR_EACH_HOSTPING(hp) {
		if (strcmp(hp->name, name) == 0) {
			rc = -1;
			break;
		}
	}
	pthread_rwlock_unlock(&hostping_rwlock);
	if (rc)
		return rc;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_protocol = IPPROTO_TCP;
	rc = getaddrinfo(name, NULL, &hints, &res);
	if (rc) {
		return -2;
	}
	
	pthread_rwlock_wrlock(&hostping_rwlock);
	hostping_add(name, res->ai_addr, res->ai_addrlen);
	pthread_rwlock_unlock(&hostping_rwlock);
	freeaddrinfo(res);
	return 0;
}

static int ping_fd;

static pthread_mutex_t sendq_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t sendq_cond = PTHREAD_COND_INITIALIZER;
static int send_p;

static unsigned xmit_total;
static unsigned recv_total;

#define ICMP_HEADER_LEN (offsetof(struct icmp, icmp_data))
#define PING_DATALEN (64 - ICMP_HEADER_LEN)

size_t data_length = PING_DATALEN;
static unsigned char *data_buffer;

static int ping_ident;

#define MAX_PING_TIMEOUT 10
enum {
	MAX_SEQNO = USHRT_MAX,
	MOD_SEQNO = MAX_SEQNO + 1
};

struct seqidx {
	HOSTPING *host;
	struct timeval tv;
	int replied;
};

static struct seqidx *seqidx;
static unsigned short next_seqno;

static int
seqno_alloc(HOSTPING *addr, struct timeval *tv)
{
	int n = next_seqno;
	do {
		if (tv->tv_sec - seqidx[n].tv.tv_sec > MAX_PING_TIMEOUT) {
			memcpy(&seqidx[n].tv, tv, sizeof(*tv));
			seqidx[n].host = addr;
			seqidx[n].replied = 0;
			next_seqno = (n + 1) % MOD_SEQNO;
			return n;
		}
		n = (n + 1) % MOD_SEQNO;
	} while (n != next_seqno);
	error("no free sequence numbers");
	return -1;
}

static HOSTPING *
hostping_from_seqno(int seq)
{
	HOSTPING *host = seqidx[seq].host;
	if (seqidx[seq].replied)
		info("%s:%d: DUP!", host->name, seq);
	seqidx[seq].replied++;
	hostping_lock(host);
	return host;
}

void
p903_init(void)
{
        struct protoent *proto;
	int i;
	FILE *fp;
	
	conf_hostping_count = hostping_count;
	fp = fopen(LOCAL_IP_LIST_FILE, "r");
	if (fp) {
		int rc = file_read_ip_list(fp, LOCAL_IP_LIST_FILE);
		if (rc == CF_RET_FAIL) 
			exit(1);
		fclose(fp);
	} else if (errno != ENOENT) {
		fatal("can't open %s: %s", LOCAL_IP_LIST_FILE,
		      strerror(errno));
		exit(1);
	}
	
	if (hostping_count == 0) {
		info("no IP addresses configured, starting anyway");
	}
	hostping_updated = 0;
	
	proto = getprotobyname("icmp");
	if (!proto) {
		fatal("no entry for icmp in the system protocol database");
		exit(1);
	}
        ping_fd = socket(AF_INET, SOCK_RAW, proto->p_proto);
        if (ping_fd < 0) {
                fatal("can't create ICMP socket: %s", strerror(errno));
		exit(1);
        }

	ping_ident = getpid() & 0xffff;
	
	data_buffer = emalloc(data_length);
	for (i = 0; i < data_length; i++)
		data_buffer[i] = i;

	seqidx = calloc(MAX_SEQNO + 1, sizeof(seqidx[0]));
	if (!seqidx)
		emalloc_die();	
}

static unsigned short
icmp_cksum(unsigned char * addr, int len)
{
	register int sum = 0;
	unsigned short answer = 0;
	unsigned short *wp;

	for (wp = (unsigned short *) addr; len > 1; wp++, len -= 2)
		sum += *wp;

	/* Take in an odd byte if present */
	if (len == 1) {
		*(unsigned char *) & answer = *(unsigned char *) wp;
		sum += answer;
	}

	sum = (sum >> 16) + (sum & 0xffff);	/* add high 16 to low 16 */
	sum += (sum >> 16);		/* add carry */
	answer = ~sum;		/* truncate to 16 bits */
	return answer;
}

static int
icmp_generic_encode(unsigned char * buffer, size_t bufsize, int type,
		    int ident, int seqno)
{
	struct icmp *icmp;
	
	if (bufsize < ICMP_MINLEN)
		return -1;
	icmp = (struct icmp *) buffer;
	icmp->icmp_type = type;
	icmp->icmp_code = 0;
	icmp->icmp_cksum = 0;
	icmp->icmp_seq = htons(seqno);
	icmp->icmp_id = htons(ident);
	
	icmp->icmp_cksum = icmp_cksum(buffer, bufsize);
	return 0;
}

static int
icmp_generic_decode(unsigned char * buffer, size_t bufsize,
		    struct ip **ipp, struct icmp ** icmpp)
{
	size_t hlen;
	unsigned short cksum;
	struct ip *ip;
	struct icmp *icmp;
	
	/* IP header */
	ip = (struct ip *) buffer;
	hlen = ip->ip_hl << 2;
	if (bufsize < hlen + ICMP_MINLEN)
		return -1;

	/* ICMP header */
	icmp = (struct icmp *) (buffer + hlen);

	/* Prepare return values */
	*ipp = ip;
	*icmpp = icmp;

	/* Recompute checksum */
	cksum = icmp->icmp_cksum;
	icmp->icmp_cksum = 0;
	icmp->icmp_cksum = icmp_cksum((unsigned char *) icmp, bufsize - hlen);
	if (icmp->icmp_cksum != cksum)
		return 1;
	icmp->icmp_seq = ntohs(icmp->icmp_seq);
	icmp->icmp_id = ntohs(icmp->icmp_id);
	
	return 0;
}

static void
send_echo(HOSTPING *host, unsigned char *ping_buffer)
{
	struct icmp *icmp = (struct icmp *) ping_buffer;
	size_t buflen;
	ssize_t n;
	int seqno;

	hostping_lock(host);
	gettimeofday(&host->xmit_tv, NULL);
	hostping_unlock(host);
	
	memcpy(icmp->icmp_data, &host->xmit_tv, sizeof(host->xmit_tv));
	if (data_buffer)
		memcpy(icmp->icmp_data + sizeof(host->xmit_tv), data_buffer,
		       data_length - sizeof(host->xmit_tv));

	buflen = ICMP_HEADER_LEN + data_length;

	seqno = seqno_alloc(host, &host->xmit_tv);
	if (seqno == -1) {
		//FIXME
		return;
	}
	
	if (verbose > 2)
		info("sending %d bytes to %s, icmp_seq=%d", buflen, host->name,
		     seqno);
	icmp_generic_encode(ping_buffer, buflen, ICMP_ECHO, ping_ident, seqno);

	n = sendto(ping_fd, (char *) ping_buffer, buflen, 0,
		   host->addr, host->addrlen);
	if (n < 0) {
		error("%s: sendto: %s", host->name, strerror(errno));
	} else {
		hostping_lock(host);
		if (host->xmit_count == 0)
			host->start_tv = host->xmit_tv;
		host->xmit_count++;
		hostping_unlock(host);		
		xmit_total++;
		if (n != buflen)
			error("ping: wrote %s %d chars, ret=%d\n",
			      host->name, buflen, n);
	}
}

static void
start_probe(void)
{
	pthread_mutex_lock(&sendq_mutex);
	send_p = 1;
	pthread_cond_broadcast(&sendq_cond);
	pthread_mutex_unlock(&sendq_mutex);
}

static void hostping_commit(HOSTPING *host);

void *
p903_sender(void *p)
{
	size_t i;
	unsigned char *ping_buffer;
	struct pollfd pfd;
	int n;
	unsigned send_count = 0;
	double d;
	struct timespec delay;
	
	pfd.fd = ping_fd;
	pfd.events = POLLOUT;
	
	ping_buffer = emalloc(sizeof(struct icmp) + data_length);

	d = (double) ping_interval / hostping_count;
	delay.tv_sec = (int) d;
	delay.tv_nsec = (d - delay.tv_sec) * NANOSEC_IN_SEC;

	pthread_mutex_lock(&sendq_mutex);
	while (1) {
		struct timespec ts;
		HOSTPING *hp;
		
		if (!send_p) {
			while (!send_p)
				pthread_cond_wait(&sendq_cond, &sendq_mutex);
			send_count = 0;
		}
		clock_gettime(CLOCK_MONOTONIC, &ts);
		pthread_rwlock_rdlock(&hostping_rwlock);
		FOR_EACH_HOSTPING(hp) {
			struct timespec nts;
			clock_gettime(CLOCK_MONOTONIC, &nts);
			timespec_incr(&nts, &delay);
			n = poll(&pfd, 1, -1);
			if (n == 1) {
				send_echo(hp, ping_buffer);
			} else if (n == -1) {
				fatal("poll: %s", strerror(errno));
				exit(1);
			}
			if (i < hostping_count - 1)
				clock_nanosleep(CLOCK_MONOTONIC,
						TIMER_ABSTIME, &nts,
						NULL);
		}
		pthread_rwlock_unlock(&hostping_rwlock);
		send_count++;
		if (send_count == ping_count)
			send_p = 0;
		else {
			ts.tv_sec += ping_interval;
			clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts,
					NULL);
		}
	}
	pthread_mutex_unlock(&sendq_mutex);
	return NULL;
}

static void
log_echo(struct sockaddr *addr,	socklen_t addrlen,
	 struct icmp *icmp, struct ip *ip,
	 size_t datalen, double rtt)
{
	char hbuf[NI_MAXHOST];

	datalen -= ip->ip_hl << 2;
	if (getnameinfo(addr, addrlen, hbuf, sizeof(hbuf),
			NULL, 0, NI_NUMERICHOST)) {
		strcpy(hbuf, "UNKNOWN");
	}
	
	info("%d bytes from %s: icmp_seq=%u ttl=%d time=%.3f ms", datalen,
	     hbuf, icmp->icmp_seq, ip->ip_ttl, rtt);
}

void *
p903_receiver(void *p)
{
	size_t buflen = sizeof(struct icmp) + data_length;
	unsigned char *ping_buffer;

	ping_buffer = emalloc(buflen);
	
	while (1) {
		struct sockaddr_storage addr;
		socklen_t addrlen = sizeof(addr);
		ssize_t n;
		int rc;
		struct icmp *icmp;
		struct ip *ip;
		HOSTPING *host;

		n = recvfrom(ping_fd, ping_buffer, buflen, 0,
			     (struct sockaddr *) &addr, &addrlen);
		if (n < 0) {
			error("recvfrom: %s", strerror(errno));
			continue;
		}

		rc = icmp_generic_decode(ping_buffer, n, &ip, &icmp);
		if (rc < 0) {
			char hbuf[NI_MAXHOST];
			if (getnameinfo((struct sockaddr *) &addr,
					addrlen,
					hbuf, sizeof(hbuf),
					NULL, 0, NI_NUMERICHOST)) {
				error("packet too short (%d bytes)", n);
			} else {
				error("packet too short (%d bytes), from %s",
				      n, hbuf);
			}
			continue;
		}

		if (icmp->icmp_type != ICMP_ECHOREPLY
		    || icmp->icmp_id != ping_ident)
			continue;

		recv_total++;

		if (rc) {
			char hbuf[NI_MAXHOST];
			if (getnameinfo((struct sockaddr *) &addr,
					addrlen,
					hbuf, sizeof(hbuf),
					NULL, 0, NI_NUMERICHOST)) {
				error("checksum mismatch");
			} else {
				error("checksum mismatch from %s", hbuf);
			}
			continue;
		}

		host = hostping_from_seqno(icmp->icmp_seq);
		if (host) {
			struct timeval tv_orig, tv_diff, *tp;
			double rtt;

			gettimeofday(&host->recv_tv, NULL);
			
			tp = (struct timeval *) icmp->icmp_data;

			/* Avoid unaligned data: */
			memcpy(&tv_orig, tp, sizeof (tv_orig));
			timersub(&host->recv_tv, &tv_orig, &tv_diff);

			rtt = timeval_to_double(&tv_diff) * 1000.0;
			host->tsum += rtt;
			host->tsumsq += rtt * rtt;
			if (rtt < host->tmin)
				host->tmin = rtt;
			if (rtt > host->tmax)
				host->tmax = rtt;
			
			host->recv_count++;

			if (verbose > 1)
				log_echo((struct sockaddr *)&addr, addrlen,
					 icmp, ip, n, rtt);
			if (host->recv_count == ping_count)
				hostping_commit(host);
			hostping_unlock(host);
		} else
			fatal("no host found for sequence number %d",
			      icmp->icmp_seq);
	}
}

static int
create_dirs(char const *filename)
{
	char *namebuf;
	char *p;
	char *endp;
	struct stat st;
	size_t len;
	
	p = strrchr(filename, '/');
	if (!p)
		return -1;
	len = p - filename;
	namebuf = malloc(len + 1);
	if (!namebuf)
		return -1;
	memcpy(namebuf, filename, len);
	namebuf[len] = 0;
	endp = namebuf + len;
	
	while ((p = strrchr(namebuf, '/')) != NULL && p > namebuf) {
		*p = 0;
		if (stat(namebuf, &st)) {
			if (errno == ENOENT)
				continue;
			error("can't stat %s: %s", namebuf, strerror(errno));
			goto err;
		}
		if (S_ISDIR(st.st_mode)) {
			break;
		} else {
			error("file name component %s is not a directory",
			      namebuf);
			goto err;
		}
	}

	while (p < endp) {
		*p = '/';
		if (mkdir(namebuf, 0755)) {
			error("can't create directory %s: %s",
			      namebuf, strerror(errno));
			goto err;
		}
		p = p + strlen(p);
	}
	return 0;
err:
	free(namebuf);
	return -1;
}
	
static void
save_local_ip_list(void)
{
	FILE *fp;
	HOSTPING *hp;
	size_t i;
	
	if (!hostping_updated)
		return;
	fp = fopen(LOCAL_IP_LIST_FILE, "w");
	if (!fp) {
		if (errno == ENOENT) {
			create_dirs(LOCAL_IP_LIST_FILE);
			fp = fopen(LOCAL_IP_LIST_FILE, "w");
		}
		if (!fp) {
			fatal("can't open %s for writing: %s",
			      LOCAL_IP_LIST_FILE,
			      strerror(errno));
			return;
		}
	}
	i = 0;
	FOR_EACH_HOSTPING(hp) {
		if (i >= conf_hostping_count)
			fprintf(fp, "%s\n", hp->name);
		i++;
	}
	fclose(fp);
	
	hostping_updated = 0;
}

void *
p903_scheduler(void *p)
{
	while (1) {
		HOSTPING *hp;
		
		pthread_rwlock_rdlock(&hostping_rwlock);
		/* Reset all statistics */
		FOR_EACH_HOSTPING(hp) {
			hostping_reset(hp);
		}
		save_local_ip_list();
		pthread_rwlock_unlock(&hostping_rwlock);

		start_probe();
		sleep(probe_interval);
		if (verbose)
			info("total sent=%u, received=%u",
			     xmit_total, recv_total);
		xmit_total = recv_total = 0;
	}
}

Return to:

Send suggestions and report system problems to the System administrator.