summaryrefslogtreecommitdiffstats
path: root/sbin/natd/natd.c
blob: f1667654eec3d3d54895af80982f200985e1d623 (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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
/*
 * natd - Network Address Translation Daemon for FreeBSD.
 *
 * This software ois provided free of charge, with no 
 * warranty of any kind, either expressed or implied.
 * Use at your own risk.
 * 
 * You may copy, modify and distribute this software (natd.c) freely.
 *
 * Ari Suutari (ari@kn6-045.ktvlpr.inet.fi, ari@ps.carel.fi)
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <errno.h>
#include <signal.h>

#include <netdb.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <machine/in_cksum.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/route.h>
#include <arpa/inet.h>

#include <syslog.h>
#include <alias.h>

#include "natd.h"

/* 
 * Default values for input and output
 * divert socket ports.
 */

#define	DEFAULT_SERVICE	"natd"

/*
 * Function prototypes.
 */

static void DoAliasing (int fd);
static void DaemonMode ();
static void HandleRoutingInfo (int fd);
static void Usage ();
static void PrintPacket (struct ip*);
static void SetAliasAddressFromIfName (char* ifName);
static void InitiateShutdown ();
static void Shutdown ();
static void RefreshAddr ();
static void ParseOption (char* option, char* parms, int cmdLine);
static void ReadConfigFile (char* fileName);
static void SetupPermanentLink (char* parms);
static void SetupPortRedirect (char* parms);
static void SetupAddressRedirect (char* parms);
static void StrToAddr (char* str, struct in_addr* addr);
static int  StrToPort (char* str, char* proto);
static int  StrToProto (char* str);
static int  StrToAddrAndPort (char* str, struct in_addr* addr, char* proto);
static void ParseArgs (int argc, char** argv);

/*
 * Globals.
 */

static	int		verbose;
static 	int		background;
static	int		running;
static	int		assignAliasAddr;
static	char*		ifName;
static  int		ifIndex;
static	int		inPort;
static	int		outPort;
static	int		inOutPort;
static	struct in_addr	aliasAddr;
static 	int		dynamicMode;
static  int		ifMTU;
static	int		aliasOverhead;
static 	int		icmpSock;

int main (int argc, char** argv)
{
	int			divertIn;
	int			divertOut;
	int			divertInOut;
	int			routeSock;
	struct sockaddr_in	addr;
	fd_set			readMask;
	int			fdMax;
/* 
 * Initialize packet aliasing software.
 * Done already here to be able to alter option bits
 * during command line and configuration file processing.
 */
	InitPacketAlias ();
/*
 * Parse options.
 */
	inPort			= 0;
	outPort			= 0;
	verbose 		= 0;
	inOutPort		= 0;
	ifName			= NULL;
	ifMTU			= -1;
	background		= 0;
	running			= 1;
	assignAliasAddr		= 0;
	aliasAddr.s_addr	= INADDR_NONE;
	aliasOverhead		= 12;
	dynamicMode		= 0;

	ParseArgs (argc, argv);
/*
 * Check that valid aliasing address has been given.
 */
	if (aliasAddr.s_addr == INADDR_NONE && ifName == NULL) {

		fprintf (stderr, "Aliasing address not given.\n");
		exit (1);
	}

	if (aliasAddr.s_addr != INADDR_NONE && ifName != NULL) {

		fprintf (stderr, "Both alias address and interface name "
				 "are not allowed.\n");
		exit (1);
	}
/*
 * Check that valid port number is known.
 */
	if (inPort != 0 || outPort != 0)
		if (inPort == 0 || outPort == 0) {

			fprintf (stderr, "Both input and output ports"
					 " are required.\n");
			exit (1);
		}

	if (inPort == 0 && outPort == 0 && inOutPort == 0)
		ParseOption ("port", DEFAULT_SERVICE, 0);

/*
 * Create divert sockets. Use only one socket if -p was specified
 * on command line. Otherwise, create separate sockets for
 * outgoing and incoming connnections.
 */
	if (inOutPort) {

		divertInOut = socket (PF_INET, SOCK_RAW, IPPROTO_DIVERT);
		if (divertInOut == -1)
			Quit ("Unable to create divert socket.");

		divertIn  = -1;
		divertOut = -1;
/*
 * Bind socket.
 */

		addr.sin_family		= AF_INET;
		addr.sin_addr.s_addr	= INADDR_ANY;
		addr.sin_port		= inOutPort;

		if (bind (divertInOut,
			  (struct sockaddr*) &addr,
			  sizeof addr) == -1)
			Quit ("Unable to bind divert socket.");
	}
	else {

		divertIn = socket (PF_INET, SOCK_RAW, IPPROTO_DIVERT);
		if (divertIn == -1)
			Quit ("Unable to create incoming divert socket.");

		divertOut = socket (PF_INET, SOCK_RAW, IPPROTO_DIVERT);
		if (divertOut == -1)
			Quit ("Unable to create outgoing divert socket.");

		divertInOut = -1;

/*
 * Bind divert sockets.
 */

		addr.sin_family		= AF_INET;
		addr.sin_addr.s_addr	= INADDR_ANY;
		addr.sin_port		= inPort;

		if (bind (divertIn,
			  (struct sockaddr*) &addr,
			  sizeof addr) == -1)
			Quit ("Unable to bind incoming divert socket.");

		addr.sin_family		= AF_INET;
		addr.sin_addr.s_addr	= INADDR_ANY;
		addr.sin_port		= outPort;

		if (bind (divertOut,
			  (struct sockaddr*) &addr,
			  sizeof addr) == -1)
			Quit ("Unable to bind outgoing divert socket.");
	}
/*
 * Create routing socket if interface name specified.
 */
	if (ifName && dynamicMode) {

		routeSock = socket (PF_ROUTE, SOCK_RAW, 0);
		if (routeSock == -1)
			Quit ("Unable to create routing info socket.");
	}
	else
		routeSock = -1;
/*
 * Create socket for sending ICMP messages.
 */
	icmpSock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
	if (icmpSock == -1)
		Quit ("Unable to create ICMP socket.");
/*
 * Become a daemon unless verbose mode was requested.
 */
	if (!verbose)
		DaemonMode ();
/*
 * Catch signals to manage shutdown and
 * refresh of interface address.
 */
	signal (SIGTERM, InitiateShutdown);
	signal (SIGHUP, RefreshAddr);
/*
 * Set alias address if it has been given.
 */
	if (aliasAddr.s_addr != INADDR_NONE)
		SetPacketAliasAddress (aliasAddr);

	if (divertInOut != -1 && !ifName) {
		
/* 
 * When using only one socket, just call 
 * DoAliasing repeatedly to process packets.
 */
		while (running)
			DoAliasing (divertInOut);
	}
	else {
/*
 * We need largest descriptor number for select.
 */

		fdMax = -1;

		if (divertIn > fdMax)
			fdMax = divertIn;

		if (divertOut > fdMax)
			fdMax = divertOut;

		if (divertInOut > fdMax)
			fdMax = divertInOut;

		if (routeSock > fdMax)
			fdMax = routeSock;

		while (running) {
/* 
 * Build read mask from socket descriptors to select.
 */
			FD_ZERO (&readMask);

			if (divertIn != -1)
				FD_SET (divertIn, &readMask);

			if (divertOut != -1)
				FD_SET (divertOut, &readMask);

			if (divertInOut != -1)
				FD_SET (divertInOut, &readMask);

			if (routeSock != -1)
				FD_SET (routeSock, &readMask);

			if (select (fdMax + 1,
				    &readMask,
				    NULL,
				    NULL,
				    NULL) == -1) {

				if (errno == EINTR)
					continue;

				Quit ("Select failed.");
			}

			if (divertIn != -1)
				if (FD_ISSET (divertIn, &readMask))
					DoAliasing (divertIn);

			if (divertOut != -1)
				if (FD_ISSET (divertOut, &readMask))
					DoAliasing (divertOut);

			if (divertInOut != -1)
				if (FD_ISSET (divertInOut, &readMask))
					DoAliasing (divertInOut);

			if (routeSock != -1)
				if (FD_ISSET (routeSock, &readMask))
					HandleRoutingInfo (routeSock);
		}
	}

	if (background)
		unlink (PIDFILE);

	return 0;
}

static void DaemonMode ()
{
	FILE*	pidFile;

	daemon (0, 0);
	background = 1;

	pidFile = fopen (PIDFILE, "w");
	if (pidFile) {

		fprintf (pidFile, "%d\n", getpid ());
		fclose (pidFile);
	}
}

static void ParseArgs (int argc, char** argv)
{
	int		arg;
	char*		parm;
	char*		opt;
	char		parmBuf[256];

	for (arg = 1; arg < argc; arg++) {

		opt  = argv[arg];
		if (*opt != '-') {

			fprintf (stderr, "Invalid option %s.\n", opt);
			Usage ();
		}

		parm = NULL;
		parmBuf[0] = '\0';

		while (arg < argc - 1) {

			if (argv[arg + 1][0] == '-')
				break;

			if (parm)
				strcat (parmBuf, " ");

			++arg;
			parm = parmBuf;
			strcat (parmBuf, argv[arg]);
		}

		ParseOption (opt + 1, parm, 1);
	}
}

static void DoAliasing (int fd)
{
	int			bytes;
	int			origBytes;
	char			buf[IP_MAXPACKET];
	struct sockaddr_in	addr;
	int			wrote;
	int			addrSize;
	struct ip*		ip;
	char			msgBuf[80];

	if (assignAliasAddr) {

		SetAliasAddressFromIfName (ifName);
		assignAliasAddr = 0;
	}
/*
 * Get packet from socket.
 */
	addrSize  = sizeof addr;
	origBytes = recvfrom (fd,
			      buf,
			      sizeof buf,
			      0,
			      (struct sockaddr*) &addr,
			      &addrSize);

	if (origBytes == -1) {

		if (errno != EINTR)
			Warn ("Read from divert socket failed.");

		return;
	}
/*
 * This is a IP packet.
 */
	ip = (struct ip*) buf;

	if (verbose) {
		
/*
 * Print packet direction and protocol type.
 */
 
		if (addr.sin_addr.s_addr == INADDR_ANY)
			printf ("Out ");
		else
			printf ("In  ");

		switch (ip->ip_p) {
		case IPPROTO_TCP:
			printf ("[TCP]  ");
			break;

		case IPPROTO_UDP:
			printf ("[UDP]  ");
			break;

		case IPPROTO_ICMP:
			printf ("[ICMP] ");
			break;

		default:
			printf ("[?]    ");
			break;
		}
/*
 * Print addresses.
 */
		PrintPacket (ip);
	}

	if (addr.sin_addr.s_addr == INADDR_ANY) {
/*
 * Outgoing packets. Do aliasing.
 */
		PacketAliasOut (buf, IP_MAXPACKET);
	}
	else {
/*
 * Incoming packets may have ip checksum zeroed
 * when read from divert socket. Re-calculate it.
 */
		if (ip->ip_sum == 0)
			ip->ip_sum = in_cksum_hdr (ip);	
/*
 * Do aliasing.
 */	
		PacketAliasIn (buf, IP_MAXPACKET);
	}
/*
 * Length might have changed during aliasing.
 */
	bytes = ntohs (ip->ip_len);
/*
 * Update alias overhead size for outgoing packets.
 */
	if (addr.sin_addr.s_addr == INADDR_ANY &&
	    bytes - origBytes > aliasOverhead)
		aliasOverhead = bytes - origBytes;

	if (verbose) {
		
/*
 * Print addresses after aliasing.
 */
		printf (" aliased to\n");
		printf ("           ");
		PrintPacket (ip);
		printf ("\n");
	}
/*
 * Put packet back for processing.
 */
	wrote = sendto (fd, 
		        buf,
	    		bytes,
	    		0,
	    		(struct sockaddr*) &addr,
	    		sizeof addr);
	
	if (wrote != bytes) {

		if (errno == EMSGSIZE) {

			if (addr.sin_addr.s_addr == INADDR_ANY &&
			    ifMTU != -1)
				SendNeedFragIcmp (icmpSock,
						  (struct ip*) buf,
						  ifMTU - aliasOverhead);
		}
		else {

			sprintf (msgBuf, "Failed to write packet back.");
			Warn (msgBuf);
		}
	}
}

static void HandleRoutingInfo (int fd)
{
	int			bytes;
	struct if_msghdr	ifMsg;
/*
 * Get packet from socket.
 */
	bytes = read (fd, &ifMsg, sizeof ifMsg);
	if (bytes == -1) {

		Warn ("Read from routing socket failed.");
		return;
	}

	if (ifMsg.ifm_version != RTM_VERSION) {

		Warn ("Unexpected packet read from routing socket.");
		return;
	}

	if (verbose)
		printf ("Routing message %X received.\n", ifMsg.ifm_type);

	if (ifMsg.ifm_type != RTM_NEWADDR)
		return;

	if (verbose && ifMsg.ifm_index == ifIndex)
		printf ("Interface address has changed.\n");

	if (ifMsg.ifm_index == ifIndex)
		assignAliasAddr = 1;
}

static void PrintPacket (struct ip* ip)
{
	struct tcphdr*	tcphdr;

	if (ip->ip_p == IPPROTO_TCP)
		tcphdr = (struct tcphdr*) ((char*) ip + (ip->ip_hl << 2));
	else
		tcphdr = NULL;

	printf ("%s", inet_ntoa (ip->ip_src));
	if (tcphdr)
		printf (":%d", ntohs (tcphdr->th_sport));

	printf (" -> ");
	printf ("%s", inet_ntoa (ip->ip_dst));
	if (tcphdr)
		printf (":%d", ntohs (tcphdr->th_dport));
}

static void SetAliasAddressFromIfName (char* ifName)
{
	struct ifconf		cf;
	struct ifreq		buf[32];
	char			msg[80];
	struct ifreq*		ifPtr;
	int			extra;
	int			helperSock;
	int			bytes;
	struct sockaddr_in*	addr;
	int			found;
	struct ifreq		req;
	char			last[10];
/*
 * Create a dummy socket to access interface information.
 */
	helperSock = socket (AF_INET, SOCK_DGRAM, 0);
	if (helperSock == -1) {

		Quit ("Failed to create helper socket.");
		exit (1);
	}

	cf.ifc_len = sizeof (buf);
	cf.ifc_req = buf;
/*
 * Get interface data.
 */
	if (ioctl (helperSock, SIOCGIFCONF, &cf) == -1) {

		Quit ("Ioctl SIOCGIFCONF failed.");
		exit (1);
	}

	ifIndex	= 0;
	ifPtr	= buf;
	bytes	= cf.ifc_len;
	found   = 0;
	last[0] = '\0';
/*
 * Loop through interfaces until one with
 * given name is found. This is done to
 * find correct interface index for routing
 * message processing.
 */
	while (bytes) {

		if (ifPtr->ifr_addr.sa_family == AF_INET &&
                    !strcmp (ifPtr->ifr_name, ifName)) {

			found = 1;
			break;
		}

		if (strcmp (last, ifPtr->ifr_name)) {

			strcpy (last, ifPtr->ifr_name);
			++ifIndex;
		}

		extra = ifPtr->ifr_addr.sa_len - sizeof (struct sockaddr);

		ifPtr++;
		ifPtr = (struct ifreq*) ((char*) ifPtr + extra);
		bytes -= sizeof (struct ifreq) + extra;
	}

	if (!found) {

		close (helperSock);
		sprintf (msg, "Unknown interface name %s.\n", ifName);
		Quit (msg);
	}
/*
 * Get MTU size.
 */
	strcpy (req.ifr_name, ifName);

	if (ioctl (helperSock, SIOCGIFMTU, &req) == -1)
		Quit ("Cannot get interface mtu size.");

	ifMTU = req.ifr_mtu;
/*
 * Get interface address.
 */
	if (ioctl (helperSock, SIOCGIFADDR, &req) == -1)
		Quit ("Cannot get interface address.");

	addr = (struct sockaddr_in*) &req.ifr_addr;
	SetPacketAliasAddress (addr->sin_addr);
	syslog (LOG_INFO, "Aliasing to %s, mtu %d bytes",
			  inet_ntoa (addr->sin_addr),
			  ifMTU);

	close (helperSock);
}

void Quit (char* msg)
{
	Warn (msg);
	exit (1);
}

void Warn (char* msg)
{
	if (background)
		syslog (LOG_ALERT, "%s (%m)", msg);
	else
		perror (msg);
}

static void RefreshAddr ()
{
	signal (SIGHUP, RefreshAddr);
	if (ifName)
		assignAliasAddr = 1;
}

static void InitiateShutdown ()
{
/*
 * Start timer to allow kernel gracefully
 * shutdown existing connections when system
 * is shut down.
 */
	signal (SIGALRM, Shutdown);
	alarm (10);
}

static void Shutdown ()
{
	running = 0;
}

/* 
 * Different options recognized by this program.
 */

enum Option {

	PacketAliasOption,
	Verbose,
	InPort,
	OutPort,
	Port,
	AliasAddress,
	InterfaceName,
	PermanentLink,
	RedirectPort,
	RedirectAddress,
	ConfigFile,
	DynamicMode
};

enum Param {
	
	YesNo,
	Numeric,
	String,
	None,
	Address,
	Service
};

/*
 * Option information structure (used by ParseOption).
 */

struct OptionInfo {
	
	enum Option		type;
	int			packetAliasOpt;
	enum Param		parm;
	char*			parmDescription;
	char*			description;
	char*			name; 
	char*			shortName;
};

/*
 * Table of known options.
 */

static struct OptionInfo optionTable[] = {

	{ PacketAliasOption,
		PKT_ALIAS_UNREGISTERED_ONLY,
		YesNo,
		"[yes|no]",
		"alias only unregistered addresses",
		"unregistered_only",
		"u" },

	{ PacketAliasOption,
		PKT_ALIAS_LOG,
		YesNo,
		"[yes|no]",
		"enable logging",
		"log",
		"l" },

	{ PacketAliasOption,
		PKT_ALIAS_DENY_INCOMING,
		YesNo,
		"[yes|no]",
		"allow incoming connections",
		"deny_incoming",
		"d" },

	{ PacketAliasOption,
		PKT_ALIAS_USE_SOCKETS,
		YesNo,
		"[yes|no]",
		"use sockets to inhibit port conflict",
		"use_sockets",
		"s" },

	{ PacketAliasOption,
		PKT_ALIAS_SAME_PORTS,
		YesNo,
		"[yes|no]",
		"try to keep original port numbers for connections",
		"same_ports",
		"m" },

	{ Verbose,
		0,
		YesNo,
		"[yes|no]",
		"verbose mode, dump packet information",
		"verbose",
		"v" },
	
	{ DynamicMode,
		0,
		YesNo,
		"[yes|no]",
		"dynamic mode, automatically detect interface address changes",
		"dynamic",
		NULL },
	
	{ InPort,
		0,
		Service,
		"number|service_name",
		"set port for incoming packets",
		"in_port",
		"i" },
	
	{ OutPort,
		0,
		Service,
		"number|service_name",
		"set port for outgoing packets",
		"out_port",
		"o" },
	
	{ Port,
		0,
		Service,
		"number|service_name",
		"set port (defaults to natd/divert)",
		"port",
		"p" },
	
	{ AliasAddress,
		0,
		Address,
		"x.x.x.x",
		"address to use for aliasing",
		"alias_address",
		"a" },
	
	{ InterfaceName,
		0,
		String,
	        "network_if_name",
		"take aliasing address from interface",
		"interface",
		"n" },

	{ PermanentLink,
		0,
		String,
	        "tcp|udp src:port dst:port alias",
		"define permanent link for incoming connection",
		"permanent_link",
		NULL },

	{ RedirectPort,
		0,
		String,
	        "tcp|udp local_addr:local_port [public_addr:]public_port"
	 	" [remote_addr[:remote_port]]",
		"redirect a port for incoming traffic",
		"redirect_port",
		NULL },

	{ RedirectAddress,
		0,
		String,
	        "local_addr public_addr",
		"define mapping between local and public addresses",
		"redirect_address",
		NULL },

	{ ConfigFile,
		0,
		String,
		"file_name",
		"read options from configuration file",
		"config",
		"f" }
};
	
static void ParseOption (char* option, char* parms, int cmdLine)
{
	int			i;
	struct OptionInfo*	info;
	int			yesNoValue;
	int			aliasValue;
	int			numValue;
	char*			strValue;
	struct in_addr		addrValue;
	int			max;
	char*			end;
/*
 * Find option from table.
 */
	max = sizeof (optionTable) / sizeof (struct OptionInfo);
	for (i = 0, info = optionTable; i < max; i++, info++) {

		if (!strcmp (info->name, option))
			break;

		if (info->shortName)
			if (!strcmp (info->shortName, option))
				break;
	}

	if (i >= max) {

		fprintf (stderr, "Unknown option %s.\n", option);
		Usage ();
	}

	yesNoValue	= 0;
	numValue	= 0;
	strValue	= NULL;
/*
 * Check parameters.
 */
	switch (info->parm) {
	case YesNo:
		if (!parms)
			parms = "yes";

		if (!strcmp (parms, "yes"))
			yesNoValue = 1;
		else
			if (!strcmp (parms, "no"))
				yesNoValue = 0;
			else {

				fprintf (stderr, "%s needs yes/no parameter.\n",
						 option);
				exit (1);
			}
		break;

	case Service:
		if (!parms) {

			fprintf (stderr, "%s needs service name or "
					 "port number  parameter.\n",
					 option);
			exit (1);
		}

		numValue = StrToPort (parms, "divert");
		break;

	case Numeric:
		if (parms)
			numValue = strtol (parms, &end, 10);
		else
			end = parms;

		if (end == parms) {

			fprintf (stderr, "%s needs numeric parameter.\n",
					 option);
			exit (1);
		}
		break;

	case String:
		strValue = parms;
		if (!strValue) {

			fprintf (stderr, "%s needs parameter.\n",
					 option);
			exit (1);
		}
		break;

	case None:
		if (parms) {

			fprintf (stderr, "%s does not take parameters.\n",
					 option);
			exit (1);
		}
		break;

	case Address:
		if (!parms) {

			fprintf (stderr, "%s needs address/host parameter.\n",
					 option);
			exit (1);
		}

		StrToAddr (parms, &addrValue);
		break;
	}

	switch (info->type) {
	case PacketAliasOption:
	
		aliasValue = yesNoValue ? info->packetAliasOpt : 0;
		SetPacketAliasMode (aliasValue, info->packetAliasOpt);
		break;

	case Verbose:
		verbose = yesNoValue;
		break;

	case DynamicMode:
		dynamicMode = yesNoValue;
		break;

	case InPort:
		inPort = numValue;
		break;

	case OutPort:
		outPort = numValue;
		break;

	case Port:
		inOutPort = numValue;
		break;

	case AliasAddress:
		memcpy (&aliasAddr, &addrValue, sizeof (struct in_addr));
		break;

	case PermanentLink:
		SetupPermanentLink (strValue);
		break;

	case RedirectPort:
		SetupPortRedirect (strValue);
		break;

	case RedirectAddress:
		SetupAddressRedirect (strValue);
		break;

	case InterfaceName:
		if (ifName)
			free (ifName);

		ifName = strdup (strValue);
		assignAliasAddr = 1;
		break;

	case ConfigFile:
		ReadConfigFile (strValue);
		break;
	}
}

void ReadConfigFile (char* fileName)
{
	FILE*	file;
	char	buf[128];
	char*	ptr;
	char*	option;

	file = fopen (fileName, "r");
	if (!file) {

		sprintf (buf, "Cannot open config file %s.\n", fileName);
		Quit (buf);
	}

	while (fgets (buf, sizeof (buf), file)) {

		ptr = strchr (buf, '\n');
		if (!ptr) {

			fprintf (stderr, "config line too link: %s\n", buf);
			exit (1);
		}

		*ptr = '\0';
		if (buf[0] == '#')
			continue;

		ptr = buf;
/*
 * Skip white space at beginning of line.
 */
		while (*ptr && isspace (*ptr))
			++ptr;

		if (*ptr == '\0')
			continue;
/*
 * Extract option name.
 */
		option = ptr;
		while (*ptr && !isspace (*ptr))
			++ptr;

		if (*ptr != '\0') {

			*ptr = '\0';
			++ptr;
		}
/*
 * Skip white space between name and parms.
 */
		while (*ptr && isspace (*ptr))
			++ptr;

		ParseOption (option, *ptr ? ptr : NULL, 0);
	}

	fclose (file);
}

static void Usage ()
{
	int			i;
	int			max;
	struct OptionInfo*	info;

	fprintf (stderr, "Recognized options:\n\n");

	max = sizeof (optionTable) / sizeof (struct OptionInfo);
	for (i = 0, info = optionTable; i < max; i++, info++) {

		fprintf (stderr, "-%-20s %s\n", info->name,
						info->parmDescription);

		if (info->shortName)
			fprintf (stderr, "-%-20s %s\n", info->shortName,
							info->parmDescription);

		fprintf (stderr, "      %s\n\n", info->description);
	}

	exit (1);
}

void SetupPermanentLink (char* parms)
{
	char		buf[128];
	char*		ptr;
	struct in_addr	srcAddr;
	struct in_addr	dstAddr;
	int		srcPort;
	int		dstPort;
	int		aliasPort;
	int		proto;
	char*		protoName;

	strcpy (buf, parms);
/*
 * Extract protocol.
 */
	protoName = strtok (buf, " \t");
	if (!protoName) {

		fprintf (stderr, "permanent_link: missing protocol.\n");
		exit (1);
	}

	proto = StrToProto (protoName);
/*
 * Extract source address.
 */
	ptr = strtok (NULL, " \t");
	if (!ptr) {

		fprintf (stderr, "permanent_link: missing src address.\n");
		exit (1);
	}

	srcPort = StrToAddrAndPort (ptr, &srcAddr, protoName);
/*
 * Extract destination address.
 */
	ptr = strtok (NULL, " \t");
	if (!ptr) {

		fprintf (stderr, "permanent_link: missing dst address.\n");
		exit (1);
	}

	dstPort = StrToAddrAndPort (ptr, &dstAddr, protoName);
/*
 * Export alias port.
 */
	ptr = strtok (NULL, " \t");
	if (!ptr) {

		fprintf (stderr, "permanent_link: missing alias port.\n");
		exit (1);
	}

	aliasPort = StrToPort (ptr, protoName);

	PacketAliasPermanentLink (srcAddr,
				  srcPort,
				  dstAddr,
				  dstPort,
				  aliasPort,
				  proto);
}

void SetupPortRedirect (char* parms)
{
	char		buf[128];
	char*		ptr;
	struct in_addr	localAddr;
	struct in_addr	publicAddr;
	struct in_addr	remoteAddr;
	int		localPort;
	int		publicPort;
	int		remotePort;
	int		proto;
	char*		protoName;
	char*		separator;

	strcpy (buf, parms);
/*
 * Extract protocol.
 */
	protoName = strtok (buf, " \t");
	if (!protoName) {

		fprintf (stderr, "redirect_port: missing protocol.\n");
		exit (1);
	}

	proto = StrToProto (protoName);
/*
 * Extract local address.
 */
	ptr = strtok (NULL, " \t");
	if (!ptr) {

		fprintf (stderr, "redirect_port: missing local address.\n");
		exit (1);
	}

	localPort = StrToAddrAndPort (ptr, &localAddr, protoName);
/*
 * Extract public port and optinally address.
 */
	ptr = strtok (NULL, " \t");
	if (!ptr) {

		fprintf (stderr, "redirect_port: missing public port.\n");
		exit (1);
	}

	separator = strchr (ptr, ':');
	if (separator)
		publicPort = StrToAddrAndPort (ptr, &publicAddr, protoName);
	else {

		publicAddr.s_addr = INADDR_ANY;
		publicPort = StrToPort (ptr, protoName);
	}

/*
 * Extract remote address and optionally port.
 */
	ptr = strtok (NULL, " \t");
	if (ptr) {


		separator = strchr (ptr, ':');
		if (separator)
			remotePort = StrToAddrAndPort (ptr,
						       &remoteAddr,
						       protoName);
		else {

			remotePort = 0;
			StrToAddr (ptr, &remoteAddr);
		}
	}
	else {

		remotePort = 0;
		remoteAddr.s_addr = INADDR_ANY;
	}

	PacketAliasRedirectPort (localAddr,
				 localPort,
				 remoteAddr,
				 remotePort,
				 publicAddr,
				 publicPort,
				 proto);
}

void SetupAddressRedirect (char* parms)
{
	char		buf[128];
	char*		ptr;
	struct in_addr	localAddr;
	struct in_addr	publicAddr;

	strcpy (buf, parms);
/*
 * Extract local address.
 */
	ptr = strtok (buf, " \t");
	if (!ptr) {

		fprintf (stderr, "redirect_address: missing local address.\n");
		exit (1);
	}

	StrToAddr (ptr, &localAddr);
/*
 * Extract public address.
 */
	ptr = strtok (NULL, " \t");
	if (!ptr) {

		fprintf (stderr, "redirect_address: missing public address.\n");
		exit (1);
	}

	StrToAddr (ptr, &publicAddr);
	PacketAliasRedirectAddr (localAddr, publicAddr);
}

void StrToAddr (char* str, struct in_addr* addr)
{
	struct hostent* hp;

	if (inet_aton (str, addr))
		return;

	hp = gethostbyname (str);
	if (!hp) {

		fprintf (stderr, "Unknown host %s.\n", str);
		exit (1);
	}

	memcpy (addr, hp->h_addr, sizeof (struct in_addr));
}

int StrToPort (char* str, char* proto)
{
	int		port;
	struct servent*	sp;
	char*		end;

	port = strtol (str, &end, 10);
	if (end != str)
		return htons (port);

	sp = getservbyname (str, proto);
	if (!sp) {

		fprintf (stderr, "Unknown service %s/%s.\n",
				 str, proto);
		exit (1);
	}

	return sp->s_port;
}

int StrToProto (char* str)
{
	if (!strcmp (str, "tcp"))
		return IPPROTO_TCP;

	if (!strcmp (str, "udp"))
		return IPPROTO_UDP;

	fprintf (stderr, "Unknown protocol %s. Expected tcp or udp.\n", str);
	exit (1);
}

int StrToAddrAndPort (char* str, struct in_addr* addr, char* proto)
{
	char*	ptr;

	ptr = strchr (str, ':');
	if (!ptr) {

		fprintf (stderr, "%s is missing port number.\n", str);
		exit (1);
	}

	*ptr = '\0';
	++ptr;

	StrToAddr (str, addr);
	return StrToPort (ptr, proto);
}

OpenPOWER on IntegriCloud