summaryrefslogtreecommitdiff
path: root/arping.c
blob: 80acad06ba990b9eed974d27e30b5ddae66d9dc3 (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
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
/*
 * arping.c
 *
 *		This program 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
 *		2 of the License, or (at your option) any later version.
 *
 * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
 * 		YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org>
 */

#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <net/if.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <net/if_arp.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#ifdef HAVE_LIBCAP
#include <sys/prctl.h>
#include <sys/capability.h>
#endif

#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#ifdef USE_SYSFS
#include <sys/types.h>
#include <dirent.h>
#endif

#include <ifaddrs.h>

#ifdef USE_IDN
#include <locale.h>

#ifndef AI_IDN
#define AI_IDN 0x0040
#endif
#ifndef AI_CANONIDN
#define AI_CANONIDN 0x0080
#endif
#endif

static void usage(void) __attribute__((noreturn));

#ifdef DEFAULT_DEVICE
# define DEFAULT_DEVICE_STR	DEFAULT_DEVICE
#else
# define DEFAULT_DEVICE		NULL
#endif

struct device {
	char *name;
	int ifindex;
	struct ifaddrs *ifa;
#ifdef USE_SYSFS
	struct sysfs_devattr_values *sysfs;
#endif
};

int quit_on_reply=0;
struct device device = {
	.name = DEFAULT_DEVICE,
};
char *source;
struct in_addr gsrc, gdst;
char *target;
int dad, unsolicited, advert;
int quiet;
int count = -1;
int timeout;
unsigned int interval = 1;
int unicasting;
int socketfd;
int broadcast_only;

struct sockaddr_storage me;
struct sockaddr_storage he;

struct timespec start, last;

int sent, brd_sent;
int received, brd_recv, req_recv;

#ifndef HAVE_LIBCAP
static uid_t euid;
#endif

#define MS_TDIFF(tv1,tv2) ( ((tv1).tv_sec-(tv2).tv_sec)*1000 + \
			   ((tv1).tv_usec-(tv2).tv_usec)/1000 )

#define OFFSET_OF(name,ele)	((size_t)(((name *)0)->ele))

static inline socklen_t sll_len(size_t halen)
{
	socklen_t len = OFFSET_OF(struct sockaddr_ll, sll_addr) + halen;
	if (len < sizeof(struct sockaddr_ll))
		len = sizeof(struct sockaddr_ll);
	return len;
}

#define SLL_LEN(hln)		sll_len(hln)

void usage(void)
{
	fprintf(stderr,
		"\nUsage:\n"
		"  arping [options] <destination>\n"
		"\nOptions:\n"
		"  -f            quit on first reply\n"
		"  -q            be quiet\n"
		"  -b            keep on broadcasting, do not unicast\n"
		"  -D            duplicate address detection mode\n"
		"  -U            unsolicited ARP mode, update your neighbours\n"
		"  -A            ARP answer mode, update your neighbours\n"
		"  -V            print version and exit\n"
		"  -c <count>    how many packets to send\n"
		"  -w <timeout>  how long to wait for a reply\n"
		"  -i <interval> set interval between packets (default: 1 second)\n"
		"  -I <device>   which ethernet device to use"
#ifdef DEFAULT_DEVICE_STR
				"(" DEFAULT_DEVICE_STR ")"
#endif
				"\n"
		"  -s <source>   source ip address\n"
		"  <destination> dns name or ip address\n"
		"\nFor more details see arping(8).\n"
	);
	exit(2);
}

void set_signal(int signo, void (*handler)(void))
{
	struct sigaction sa;

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = (void (*)(int))handler;
	sa.sa_flags = SA_RESTART;
	sigaction(signo, &sa, NULL);
}

#ifdef HAVE_LIBCAP
static const cap_value_t caps[] = { CAP_NET_RAW, };
static cap_flag_value_t cap_raw = CAP_CLEAR;
#endif

void limit_capabilities(void)
{
#ifdef HAVE_LIBCAP
	cap_t cap_p;

	cap_p = cap_get_proc();
	if (!cap_p) {
		perror("arping: cap_get_proc");
		exit(-1);
	}

	cap_get_flag(cap_p, CAP_NET_RAW, CAP_PERMITTED, &cap_raw);

	if (cap_raw != CAP_CLEAR) {
		if (cap_clear(cap_p) < 0) {
			perror("arping: cap_clear");
			exit(-1);
		}

		cap_set_flag(cap_p, CAP_PERMITTED, 1, caps, CAP_SET);

		if (cap_set_proc(cap_p) < 0) {
			perror("arping: cap_set_proc");
			if (errno != EPERM)
				exit(-1);
		}
	}

	if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
		perror("arping: prctl");
		exit(-1);
	}

	if (setuid(getuid()) < 0) {
		perror("arping: setuid");
		exit(-1);
	}

	if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
		perror("arping: prctl");
		exit(-1);
	}

	cap_free(cap_p);
#else
	euid = geteuid();
#endif
}

int modify_capability_raw(int on)
{
#ifdef HAVE_LIBCAP
	cap_t cap_p;

	if (cap_raw != CAP_SET)
		return on ? -1 : 0;

	cap_p = cap_get_proc();
	if (!cap_p) {
		perror("arping: cap_get_proc");
		return -1;
	}

	cap_set_flag(cap_p, CAP_EFFECTIVE, 1, caps, on ? CAP_SET : CAP_CLEAR);

	if (cap_set_proc(cap_p) < 0) {
		perror("arping: cap_set_proc");
		return -1;
	}

	cap_free(cap_p);
#else
	if (setuid(on ? euid : getuid())) {
		perror("arping: setuid");
		return -1;
	}
#endif
	return 0;
}

static inline int enable_capability_raw(void)
{
	return modify_capability_raw(1);
}

static inline int disable_capability_raw(void)
{
	return modify_capability_raw(0);
}

void drop_capabilities(void)
{
#ifdef HAVE_LIBCAP
	cap_t cap_p = cap_init();

	if (!cap_p) {
		perror("arping: cap_init");
		exit(-1);
	}

	if (cap_set_proc(cap_p) < 0) {
		perror("arping: cap_set_proc");
		exit(-1);
	}

	cap_free(cap_p);
#else
	if (setuid(getuid()) < 0) {
		perror("arping: setuid");
		exit(-1);
	}
#endif
}

int send_pack(int s, struct in_addr src, struct in_addr dst,
	      struct sockaddr_ll *ME, struct sockaddr_ll *HE)
{
	int err;
	struct timespec now;
	unsigned char buf[256];
	struct arphdr *ah = (struct arphdr*)buf;
	unsigned char *p = (unsigned char *)(ah+1);

	ah->ar_hrd = htons(ME->sll_hatype);
	if (ah->ar_hrd == htons(ARPHRD_FDDI))
		ah->ar_hrd = htons(ARPHRD_ETHER);
	ah->ar_pro = htons(ETH_P_IP);
	ah->ar_hln = ME->sll_halen;
	ah->ar_pln = 4;
	ah->ar_op  = advert ? htons(ARPOP_REPLY) : htons(ARPOP_REQUEST);

	memcpy(p, &ME->sll_addr, ah->ar_hln);
	p+=ME->sll_halen;

	memcpy(p, &src, 4);
	p+=4;

	if (advert)
		memcpy(p, &ME->sll_addr, ah->ar_hln);
	else
		memcpy(p, &HE->sll_addr, ah->ar_hln);
	p+=ah->ar_hln;

	memcpy(p, &dst, 4);
	p+=4;

	clock_gettime(CLOCK_MONOTONIC, &now);
	err = sendto(s, buf, p-buf, 0, (struct sockaddr*)HE, SLL_LEN(ah->ar_hln));
	if (err == p-buf) {
		last = now;
		sent++;
		if (!unicasting)
			brd_sent++;
	}
	return err;
}

void finish(void)
{
	if (!quiet) {
		printf("Sent %d probes (%d broadcast(s))\n", sent, brd_sent);
		printf("Received %d response(s)", received);
		if (brd_recv || req_recv) {
			printf(" (");
			if (req_recv)
				printf("%d request(s)", req_recv);
			if (brd_recv)
				printf("%s%d broadcast(s)",
				       req_recv ? ", " : "",
				       brd_recv);
			printf(")");
		}
		printf("\n");
		fflush(stdout);
	}
	if (dad)
		exit(!!received);
	if (unsolicited)
		exit(0);
	exit(!received);
}

static void timespec_sub(struct timespec *a, struct timespec *b,
			 struct timespec *res)
{
	res->tv_sec = a->tv_sec - b->tv_sec;
	res->tv_nsec = a->tv_nsec - b->tv_nsec;
	if (a->tv_nsec < b->tv_nsec) {
		res->tv_sec--;
		res->tv_nsec += 1000000000;
	}
}

static int timespec_later(struct timespec *a, struct timespec *b)
{
	return (a->tv_sec > b->tv_sec) ||
		((a->tv_sec == b->tv_sec) && (a->tv_nsec > b->tv_nsec));
}

void catcher(void)
{
	struct timespec ts, ts_s, ts_o;

	clock_gettime(CLOCK_MONOTONIC, &ts);

	if (start.tv_sec==0)
		start = ts;

	timespec_sub(&ts, &start, &ts_s);
	ts_o.tv_sec = timeout;
	ts_o.tv_nsec = 500 * 1000000;

	if (timeout && timespec_later(&ts_s, &ts_o))
		finish();

	timespec_sub(&ts, &last, &ts_s);
	ts_o.tv_sec = 0;

	if (last.tv_sec==0 || timespec_later(&ts_s, &ts_o)) {
		if (!timeout && (sent == count))
			finish();
		send_pack(socketfd, gsrc, gdst,
			  (struct sockaddr_ll *)&me, (struct sockaddr_ll *)&he);
		if ((sent == count) && unsolicited)
			/* We usually wait for an extra iteration
			 * after sending the last request to see if we
			 * get a reply, but we don't need to in
			 * unsolicited mode */
			finish();
	}
	alarm(interval);
}

void print_hex(unsigned char *p, int len)
{
	int i;
	for (i=0; i<len; i++) {
		printf("%02X", p[i]);
		if (i != len-1)
			printf(":");
	}
}

int recv_pack(unsigned char *buf, ssize_t len, struct sockaddr_ll *FROM,
	      struct in_addr src, struct in_addr dst)
{
	struct timespec ts;
	struct arphdr *ah = (struct arphdr*)buf;
	unsigned char *p = (unsigned char *)(ah+1);
	struct in_addr src_ip, dst_ip;

	clock_gettime(CLOCK_MONOTONIC, &ts);

	/* Filter out wild packets */
	if (FROM->sll_pkttype != PACKET_HOST &&
	    FROM->sll_pkttype != PACKET_BROADCAST &&
	    FROM->sll_pkttype != PACKET_MULTICAST)
		return 0;

	/* Only these types are recognised */
	if (ah->ar_op != htons(ARPOP_REQUEST) &&
	    ah->ar_op != htons(ARPOP_REPLY))
		return 0;

	/* ARPHRD check and this darned FDDI hack here :-( */
	if (ah->ar_hrd != htons(FROM->sll_hatype) &&
	    (FROM->sll_hatype != ARPHRD_FDDI || ah->ar_hrd != htons(ARPHRD_ETHER)))
		return 0;

	/* Protocol must be IP. */
	if (ah->ar_pro != htons(ETH_P_IP))
		return 0;
	if (ah->ar_pln != 4)
		return 0;
	if (ah->ar_hln != ((struct sockaddr_ll *)&me)->sll_halen)
		return 0;
	if (len < (ssize_t) sizeof(*ah) + 2*(4 + ah->ar_hln))
		return 0;
	memcpy(&src_ip, p+ah->ar_hln, 4);
	memcpy(&dst_ip, p+ah->ar_hln+4+ah->ar_hln, 4);
	if (!dad) {
		if (src_ip.s_addr != dst.s_addr)
			return 0;
		if (src.s_addr != dst_ip.s_addr)
			return 0;
		if (memcmp(p+ah->ar_hln+4, ((struct sockaddr_ll *)&me)->sll_addr, ah->ar_hln))
			return 0;
	} else {
		/* DAD packet was:
		   src_ip = 0 (or some src)
		   src_hw = ME
		   dst_ip = tested address
		   dst_hw = <unspec>

		   We fail, if receive request/reply with:
		   src_ip = tested_address
		   src_hw != ME
		   if src_ip in request was not zero, check
		   also that it matches to dst_ip, otherwise
		   dst_ip/dst_hw do not matter.
		 */
		if (src_ip.s_addr != dst.s_addr)
			return 0;
		if (memcmp(p, ((struct sockaddr_ll *)&me)->sll_addr, ((struct sockaddr_ll *)&me)->sll_halen) == 0)
			return 0;
		if (src.s_addr && src.s_addr != dst_ip.s_addr)
			return 0;
	}
	if (!quiet) {
		int s_printed = 0;
		printf("%s ", FROM->sll_pkttype==PACKET_HOST ? "Unicast" : "Broadcast");
		printf("%s from ", ah->ar_op == htons(ARPOP_REPLY) ? "reply" : "request");
		printf("%s [", inet_ntoa(src_ip));
		print_hex(p, ah->ar_hln);
		printf("] ");
		if (dst_ip.s_addr != src.s_addr) {
			printf("for %s ", inet_ntoa(dst_ip));
			s_printed = 1;
		}
		if (memcmp(p+ah->ar_hln+4, ((struct sockaddr_ll *)&me)->sll_addr, ah->ar_hln)) {
			if (!s_printed)
				printf("for ");
			printf("[");
			print_hex(p+ah->ar_hln+4, ah->ar_hln);
			printf("]");
		}
		if (last.tv_sec) {
			long usecs = (ts.tv_sec-last.tv_sec) * 1000000 +
				(ts.tv_nsec-last.tv_nsec+500) / 1000;
			long msecs = (usecs+500)/1000;
			usecs -= msecs*1000 - 500;
			printf(" %ld.%03ldms\n", msecs, usecs);
		} else {
			printf(" UNSOLICITED?\n");
		}
		fflush(stdout);
	}
	received++;
	if (timeout && (received == count))
		finish();
	if (FROM->sll_pkttype != PACKET_HOST)
		brd_recv++;
	if (ah->ar_op == htons(ARPOP_REQUEST))
		req_recv++;
	if (quit_on_reply || (count == 0 && received == sent))
		finish();
	if(!broadcast_only) {
		memcpy(((struct sockaddr_ll *)&he)->sll_addr, p, ((struct sockaddr_ll *)&me)->sll_halen);
		unicasting=1;
	}
	return 1;
}

#ifdef USE_SYSFS
union sysfs_devattr_value {
	unsigned long	ulong;
	void		*ptr;
};

enum {
	SYSFS_DEVATTR_IFINDEX,
	SYSFS_DEVATTR_FLAGS,
	SYSFS_DEVATTR_ADDR_LEN,
	SYSFS_DEVATTR_BROADCAST,
	SYSFS_DEVATTR_NUM
};

struct sysfs_devattr_values
{
	char *ifname;
	union sysfs_devattr_value	value[SYSFS_DEVATTR_NUM];
};

static int sysfs_devattr_ulong_dec(char *ptr, struct sysfs_devattr_values *v, unsigned idx);
static int sysfs_devattr_ulong_hex(char *ptr, struct sysfs_devattr_values *v, unsigned idx);
static int sysfs_devattr_macaddr(char *ptr, struct sysfs_devattr_values *v, unsigned idx);

struct sysfs_devattrs {
	const char *name;
	int (*handler)(char *ptr, struct sysfs_devattr_values *v, unsigned int idx);
	int free;
} sysfs_devattrs[SYSFS_DEVATTR_NUM] = {
	[SYSFS_DEVATTR_IFINDEX] = {
		.name		= "ifindex",
		.handler	= sysfs_devattr_ulong_dec,
	},
	[SYSFS_DEVATTR_ADDR_LEN] = {
		.name		= "addr_len",
		.handler	= sysfs_devattr_ulong_dec,
	},
	[SYSFS_DEVATTR_FLAGS] = {
		.name		= "flags",
		.handler	= sysfs_devattr_ulong_hex,
	},
	[SYSFS_DEVATTR_BROADCAST] = {
		.name		= "broadcast",
		.handler	= sysfs_devattr_macaddr,
		.free		= 1,
	},
};
#endif

/*
 * find_device()
 *
 * This function checks 1) if the device (if given) is okay for ARP,
 * or 2) find fist appropriate device on the system.
 *
 * Return value:
 *	>0	: Succeeded, and appropriate device not found.
 *		  device.ifindex remains 0.
 *	0	: Succeeded, and approptiate device found.
 *		  device.ifindex is set.
 *	<0	: Failed.  Support not found, or other
 *		: system error.  Try other method.
 *
 * If an appropriate device found, it is recorded inside the
 * "device" variable for later reference.
 *
 * We have several implementations for this.
 *	by_ifaddrs():	requires getifaddr() in glibc, and rtnetlink in
 *			kernel. default and recommended for recent systems.
 *	by_sysfs():	requires libsysfs , and sysfs in kernel.
 *	by_ioctl():	unable to list devices without ipv4 address; this
 *			means, you need to supply the device name for
 *			DAD purpose.
 */
/* Common check for ifa->ifa_flags */
static int check_ifflags(unsigned int ifflags, int fatal)
{
	if (!(ifflags & IFF_UP)) {
		if (fatal) {
			if (!quiet)
				printf("Interface \"%s\" is down\n", device.name);
			exit(2);
		}
		return -1;
	}
	if (ifflags & (IFF_NOARP | IFF_LOOPBACK)) {
		if (fatal) {
			if (!quiet)
				printf("Interface \"%s\" is not ARPable\n", device.name);
			exit(dad ? 0 : 2);
		}
		return -1;
	}
	return 0;
}

static int find_device_by_ifaddrs(void)
{
	int rc;
	struct ifaddrs *ifa0, *ifa;
	int n = 0;

	rc = getifaddrs(&ifa0);
	if (rc) {
		perror("getifaddrs");
		return -1;
	}

	for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
		if (!ifa->ifa_addr)
			continue;
		if (ifa->ifa_addr->sa_family != AF_PACKET)
			continue;
		if (device.name && ifa->ifa_name && strcmp(ifa->ifa_name, device.name))
			continue;

		if (check_ifflags(ifa->ifa_flags, device.name != NULL) < 0)
			continue;

		if (!((struct sockaddr_ll *)ifa->ifa_addr)->sll_halen)
			continue;
		if (!ifa->ifa_broadaddr)
			continue;

		device.ifa = ifa;

		if (n++)
			break;
	}

	if (n == 1 && device.ifa) {
		device.ifindex = if_nametoindex(device.ifa->ifa_name);
		if (!device.ifindex) {
			perror("arping: if_nametoindex");
			freeifaddrs(ifa0);
			return -1;
		}
		device.name  = device.ifa->ifa_name;
		return 0;
	}
	return 1;
}

#ifdef USE_SYSFS
static void sysfs_devattr_values_init(struct sysfs_devattr_values *v, int do_free)
{
	int i;
	if (do_free) {
		free(v->ifname);
		for (i = 0; i < SYSFS_DEVATTR_NUM; i++) {
			if (sysfs_devattrs[i].free)
				free(v->value[i].ptr);
		}
	}
	memset(v, 0, sizeof(*v));
}

static int sysfs_devattr_ulong(char *ptr, struct sysfs_devattr_values *v, unsigned int idx,
				     unsigned int base)
{
	unsigned long *p;
	char *ep;

	if (!ptr || !v)
		return -1;

	p = &v->value[idx].ulong;
	errno = 0;
	*p = strtoul(ptr, &ep, base);
	if ((*ptr && isspace(*ptr & 0xff)) || errno || (*ep != '\0' && *ep != '\n'))
		goto out;

	return 0;
out:
	return -1;
}

static int sysfs_devattr_ulong_dec(char *ptr, struct sysfs_devattr_values *v, unsigned int idx)
{
	int rc = sysfs_devattr_ulong(ptr, v, idx, 10);
	return rc;
}

static int sysfs_devattr_ulong_hex(char *ptr, struct sysfs_devattr_values *v, unsigned int idx)
{
	int rc = sysfs_devattr_ulong(ptr, v, idx, 16);
	return rc;
}

static int sysfs_devattr_macaddr(char *ptr, struct sysfs_devattr_values *v, unsigned int idx)
{
	unsigned char *m;
	unsigned int i;
	unsigned int addrlen;

	if (!ptr || !v)
		return -1;

	addrlen = v->value[SYSFS_DEVATTR_ADDR_LEN].ulong;
	m = malloc(addrlen);

	for (i = 0; i < addrlen; i++) {
		if (i && *(ptr + i * 3 - 1) != ':')
			goto out;
		if (sscanf(ptr + i * 3, "%02hhx", &m[i]) != 1)
			goto out;
	}

	v->value[idx].ptr = m;
	return 0;
out:
	free(m);
	return -1;
}
#endif

int find_device_by_sysfs(void)
{
	int rc = -1;
#ifdef USE_SYSFS
	DIR *dir;
	struct dirent *dirp;
	struct sysfs_devattr_values sysfs_devattr_values;
	int n = 0;

	if (!device.sysfs) {
		device.sysfs = malloc(sizeof(*device.sysfs));
		sysfs_devattr_values_init(device.sysfs, 0);
	}
	dir = opendir("/sys/class/net");

	sysfs_devattr_values_init(&sysfs_devattr_values, 0);

	while ((dirp = readdir(dir)) != NULL) {
		int i;
		int ret = -1;

		if (!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, ".."))
			continue;
		if (device.name && strcmp(dirp->d_name, device.name))
			goto do_next;

		sysfs_devattr_values_init(&sysfs_devattr_values, 1);

		for (i = 0; i < SYSFS_DEVATTR_NUM; i++) {
			char path[PATH_MAX];
			char str[256];
			FILE *f;

			sprintf(path, "/sys/class/net/%s/%s", dirp->d_name, sysfs_devattrs[i].name);
			f = fopen(path, "r");
			if (!f)
				continue;
			if (fscanf(f, "%255s", str) != 1)
				str[0] = '\0';
			fclose(f);
			ret = sysfs_devattrs[i].handler(str, &sysfs_devattr_values, i);

			if (ret < 0)
				break;
		}

		if (ret < 0)
			goto do_next;

		if (check_ifflags(sysfs_devattr_values.value[SYSFS_DEVATTR_FLAGS].ulong,
				  device.name != NULL) < 0)
			goto do_next;

		if (!sysfs_devattr_values.value[SYSFS_DEVATTR_ADDR_LEN].ulong)
			goto do_next;

		if (device.sysfs->value[SYSFS_DEVATTR_IFINDEX].ulong) {
			if (device.sysfs->value[SYSFS_DEVATTR_FLAGS].ulong & IFF_RUNNING)
				goto do_next;
		}

		sysfs_devattr_values.ifname = strdup(dirp->d_name);
		if (!sysfs_devattr_values.ifname) {
			perror("malloc");
			goto out;
		}

		sysfs_devattr_values_init(device.sysfs, 1);
		memcpy(device.sysfs, &sysfs_devattr_values, sizeof(*device.sysfs));
		sysfs_devattr_values_init(&sysfs_devattr_values, 0);

		if (n++)
			break;

		continue;
do_next:
		sysfs_devattr_values_init(&sysfs_devattr_values, 1);
	}

	if (n == 1) {
		device.ifindex = device.sysfs->value[SYSFS_DEVATTR_IFINDEX].ulong;
		device.name = device.sysfs->ifname;
	}
	rc = !device.ifindex;
out:
	closedir(dir);
#endif
	return rc;
}

static int check_device_by_ioctl(int s, struct ifreq *ifr)
{
	if (ioctl(s, SIOCGIFFLAGS, ifr) < 0) {
		perror("ioctl(SIOCGIFINDEX");
		return -1;
	}

	if (check_ifflags(ifr->ifr_flags, device.name != NULL) < 0)
		return 1;

	if (ioctl(s, SIOCGIFINDEX, ifr) < 0) {
		perror("ioctl(SIOCGIFINDEX");
		return -1;
	}

	return 0;
}

static int find_device_by_ioctl(void)
{
	int s;
	struct ifreq *ifr0, *ifr, *ifr_end;
	size_t ifrsize = sizeof(*ifr);
	struct ifconf ifc;
	static struct ifreq ifrbuf;
	int n = 0;

	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0) {
		perror("socket");
		return -1;
	}

	memset(&ifrbuf, 0, sizeof(ifrbuf));

	if (device.name) {
		strncpy(ifrbuf.ifr_name, device.name, sizeof(ifrbuf.ifr_name) - 1);
		if (check_device_by_ioctl(s, &ifrbuf))
			goto out;
		n++;
	} else {
		do {
			int rc;
			ifr0 = malloc(ifrsize);
			if (!ifr0) {
				perror("malloc");
				goto out;
			}

			ifc.ifc_buf = (char *)ifr0;
			ifc.ifc_len = ifrsize;

			rc = ioctl(s, SIOCGIFCONF, &ifc);
			if (rc < 0) {
				perror("ioctl(SIOCFIFCONF");
				goto out;
			}

			if (ifc.ifc_len + sizeof(*ifr0) + sizeof(struct sockaddr_storage) - sizeof(struct sockaddr) <= ifrsize)
				break;
			ifrsize *= 2;
			free(ifr0);
			ifr0 = NULL;
		} while(ifrsize < INT_MAX / 2);

		if (!ifr0) {
			fprintf(stderr, "arping: too many interfaces!?\n");
			goto out;
		}

		ifr_end = (struct ifreq *)(((char *)ifr0) + ifc.ifc_len - sizeof(*ifr0));
		for (ifr = ifr0; ifr <= ifr_end; ifr++) {
			if (check_device_by_ioctl(s, &ifrbuf))
				continue;
			memcpy(&ifrbuf.ifr_name, ifr->ifr_name, sizeof(ifrbuf.ifr_name));
			if (n++)
				break;
		}
	}

	close(s);

	if (n == 1) {
		device.ifindex = ifrbuf.ifr_ifindex;
		device.name = ifrbuf.ifr_name;
	}
	return !device.ifindex;
out:
	close(s);
	return -1;
}

static int find_device(void)
{
	int rc;
	rc = find_device_by_ifaddrs();
	if (rc >= 0)
		goto out;
	rc = find_device_by_sysfs();
	if (rc >= 0)
		goto out;
	rc = find_device_by_ioctl();
out:
	return rc;
}

/*
 * set_device_broadcast()
 *
 * This fills the device "broadcast address"
 * based on information found by find_device() funcion.
 */
static int set_device_broadcast_ifaddrs_one(struct device *dev,
					    unsigned char *ba, size_t balen,
					    int fatal)
{
	struct ifaddrs *ifa;
	struct sockaddr_ll *sll;

	if (!dev)
		return -1;

	ifa = dev->ifa;
	if (!ifa)
		return -1;

	sll = (struct sockaddr_ll *)ifa->ifa_broadaddr;

	if (sll->sll_halen != balen) {
		if (fatal) {
			if (!quiet)
				printf("Address length does not match...\n");
			exit(2);
		}
		return -1;
	}
	memcpy(ba, sll->sll_addr, sll->sll_halen);
	return 0;
}
int set_device_broadcast_sysfs(struct device *dev, unsigned char *ba, size_t balen)
{
#ifdef USE_SYSFS
	struct sysfs_devattr_values *v;
	if (!dev)
		return -1;
	v = dev->sysfs;
	if (!v)
		return -1;
	if (v->value[SYSFS_DEVATTR_ADDR_LEN].ulong != balen)
		return -1;
	memcpy(ba, v->value[SYSFS_DEVATTR_BROADCAST].ptr, balen);
	return 0;
#else
	return -1;
#endif
}

static int set_device_broadcast_fallback(unsigned char *ba, size_t balen)
{
	if (!quiet)
		fprintf(stderr, "WARNING: using default broadcast address.\n");
	memset(ba, -1, balen);
	return 0;
}

static void set_device_broadcast(struct device *dev, unsigned char *ba, size_t balen)
{
	if (!set_device_broadcast_ifaddrs_one(dev, ba, balen, 0))
		return;
	if (!set_device_broadcast_sysfs(dev, ba, balen))
		return;
	set_device_broadcast_fallback(ba, balen);
}

int
main(int argc, char **argv)
{
	int socket_errno;
	int ch;

	limit_capabilities();

#ifdef USE_IDN
	setlocale(LC_ALL, "");
#endif

	enable_capability_raw();

	socketfd = socket(PF_PACKET, SOCK_DGRAM, 0);
	socket_errno = errno;

	disable_capability_raw();

	while ((ch = getopt(argc, argv, "h?bfDUAqc:w:i:s:I:V")) != EOF) {
		switch(ch) {
		case 'b':
			broadcast_only=1;
			break;
		case 'D':
			dad++;
			quit_on_reply=1;
			break;
		case 'U':
			unsolicited++;
			break;
		case 'A':
			advert++;
			unsolicited++;
			break;
		case 'q':
			quiet++;
			break;
		case 'c':
			count = atoi(optarg);
			break;
		case 'w':
			timeout = atoi(optarg);
			break;
		case 'i':
			interval = (unsigned int)atoi(optarg);
			break;
		case 'I':
			device.name = optarg;
			break;
		case 'f':
			quit_on_reply=1;
			break;
		case 's':
			source = optarg;
			break;
		case 'V':
			printf(IPUTILS_VERSION("arping"));
			exit(0);
		case 'h':
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 1)
		usage();

	target = *argv;

	if (device.name && !*device.name)
		device.name = NULL;

	if (socketfd < 0) {
		errno = socket_errno;
		perror("arping: socket");
		exit(2);
	}

	if (find_device() < 0)
		exit(2);

	if (!device.ifindex) {
		if (device.name) {
			fprintf(stderr, "arping: Device %s not available.\n", device.name);
			exit(2);
		}
		fprintf(stderr, "arping: Suitable device could not be determined. Please, use option -I.\n");
		usage();
	}

	if (inet_aton(target, &gdst) != 1) {
		struct addrinfo hints = {
			.ai_family = AF_INET,
			.ai_socktype = SOCK_RAW,
#ifdef USE_IDN
			.ai_flags = AI_IDN | AI_CANONIDN
#endif
		};
		struct addrinfo *result;
		int status;

		status = getaddrinfo(target, NULL, &hints, &result);
		if (status) {
			fprintf(stderr, "arping: %s: %s\n", target, gai_strerror(status));
			exit(2);
		}

		memcpy(&gdst, &((struct sockaddr_in *) result->ai_addr)->sin_addr, sizeof gdst);
		freeaddrinfo(result);
	}

	if (source && inet_aton(source, &gsrc) != 1) {
		fprintf(stderr, "arping: invalid source %s\n", source);
		exit(2);
	}

	if (!dad && unsolicited && source == NULL)
		gsrc = gdst;

	if (!dad || source) {
		struct sockaddr_in saddr;
		int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);

		if (probe_fd < 0) {
			perror("socket");
			exit(2);
		}
		if (device.name) {
			enable_capability_raw();

			if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device.name, strlen(device.name)+1) == -1)
				perror("WARNING: interface is ignored");

			disable_capability_raw();
		}
		memset(&saddr, 0, sizeof(saddr));
		saddr.sin_family = AF_INET;
		if (source || gsrc.s_addr) {
			saddr.sin_addr = gsrc;
			if (bind(probe_fd, (struct sockaddr*)&saddr, sizeof(saddr)) == -1) {
				perror("bind");
				exit(2);
			}
		} else if (!dad) {
			int on = 1;
			socklen_t alen = sizeof(saddr);

			saddr.sin_port = htons(1025);
			saddr.sin_addr = gdst;

			if (setsockopt(probe_fd, SOL_SOCKET, SO_DONTROUTE, (char*)&on, sizeof(on)) == -1)
				perror("WARNING: setsockopt(SO_DONTROUTE)");
			if (connect(probe_fd, (struct sockaddr*)&saddr, sizeof(saddr)) == -1) {
				perror("connect");
				exit(2);
			}
			if (getsockname(probe_fd, (struct sockaddr*)&saddr, &alen) == -1) {
				perror("getsockname");
				exit(2);
			}
			gsrc = saddr.sin_addr;
		}
		close(probe_fd);
	};

	((struct sockaddr_ll *)&me)->sll_family = AF_PACKET;
	((struct sockaddr_ll *)&me)->sll_ifindex = device.ifindex;
	((struct sockaddr_ll *)&me)->sll_protocol = htons(ETH_P_ARP);
	if (bind(socketfd, (struct sockaddr*)&me, sizeof(me)) == -1) {
		perror("bind");
		exit(2);
	}

	if (1) {
		socklen_t alen = sizeof(me);
		if (getsockname(socketfd, (struct sockaddr*)&me, &alen) == -1) {
			perror("getsockname");
			exit(2);
		}
	}
	if (((struct sockaddr_ll *)&me)->sll_halen == 0) {
		if (!quiet)
			printf("Interface \"%s\" is not ARPable (no ll address)\n", device.name);
		exit(dad?0:2);
	}

	he = me;

	set_device_broadcast(&device, ((struct sockaddr_ll *)&he)->sll_addr,
			     ((struct sockaddr_ll *)&he)->sll_halen);

	if (!quiet) {
		printf("ARPING %s ", inet_ntoa(gdst));
		printf("from %s %s\n",  inet_ntoa(gsrc), device.name ? device.name : "");
	}

	if (!source && !gsrc.s_addr && !dad) {
		fprintf(stderr, "arping: no source address in not-DAD mode\n");
		exit(2);
	}

	drop_capabilities();

	set_signal(SIGINT, finish);
	set_signal(SIGALRM, catcher);

	catcher();

	while(1) {
		sigset_t sset, osset;
		unsigned char packet[4096];
		struct sockaddr_storage from;
		socklen_t alen = sizeof(from);
		ssize_t cc;

		sigemptyset(&sset);
		sigaddset(&sset, SIGALRM);
		sigaddset(&sset, SIGINT);
		/* Unblock SIGALRM so that the previously called alarm()
		 * can prevent recvfrom from blocking forever in case the
		 * inherited procmask is blocking SIGALRM and no packet
		 * is received. */
		sigprocmask(SIG_UNBLOCK, &sset, &osset);

		if ((cc = recvfrom(socketfd, packet, sizeof(packet), 0,
				   (struct sockaddr *)&from, &alen)) < 0) {
			perror("arping: recvfrom");
			if (errno == ENETDOWN)
				exit(2);
			continue;
		}

		sigprocmask(SIG_BLOCK, &sset, NULL);
		recv_pack(packet, cc, (struct sockaddr_ll *)&from, gsrc, gdst);
		sigprocmask(SIG_SETMASK, &osset, NULL);
	}
}