summaryrefslogtreecommitdiffstats
path: root/etc/inc/captiveportal.inc
blob: e36a62663919d63ced38a40feda57081f2518962 (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
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
<?php
/*
	captiveportal.inc
	part of pfSense (http://www.pfSense.org)

	originally part of m0n0wall (http://m0n0.ch/wall)

	Copyright (C) 2010 Scott Ullrich <sullrich@gmail.com>
	Copyright (C) 2009 Ermal Luçi <ermal.luci@gmail.com>
	Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.

	This version of captiveportal.inc has been modified by Rob Parker
	<rob.parker@keycom.co.uk> to include changes for per-user bandwidth management
	via returned RADIUS attributes. This page has been modified to delete any
	added rules which may have been created by other per-user code (index.php, etc).
	These changes are (c) 2004 Keycom PLC.
	
	pfSense_BUILDER_BINARIES:	/sbin/ipfw	/sbin/sysctl	/sbin/kldunload
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/lighttpd	/usr/local/bin/minicron	/sbin/pfctl
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/cp	
	pfSense_MODULE:	captiveportal
*/

/* include all configuration functions */
require_once("config.inc");
require_once("functions.inc");
require_once("filter.inc");
require_once("radius.inc");
require_once("voucher.inc");

function get_default_captive_portal_html() {
	global $config, $g;
	// Detect if vouchers are being used and default to the voucher page
	if(isset($config['voucher']['enable'])) {
			$htmltext = <<<EOD
<html> 
	<body> 
		<form method="post" action="\$PORTAL_ACTION\$"> 
			<center>
				<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
					<tr height="10" bgcolor="#990000">
						<td style="border-bottom:1px solid #000000">
							<font color='white'>
								<b>
									Guest Voucher code required to continue
								</b>
							</font>
						</td>
					</tr>
					<tr>
						<td>
							<div id="mainlevel">
								<center>
									<table width="100%" border="0" cellpadding="5" cellspacing="0">
								 		<tr>
								    		<td>
												<center>
													<div id="mainarea">
														<center>
															<table width="100%" border="0" cellpadding="5" cellspacing="5">
																<tr>
																	<td>
																		<div id="maindivarea">
																			<center>
																				<div id='statusbox'>
																					<font color='red' face='arial' size='+1'>
																						<b>
																							\$PORTAL_MESSAGE\$
																						</b>
																					</font>
																				</div>
																				<p/>
																				<div id='loginbox'>
																					Enter Voucher Code: 
																					<input name="auth_voucher" type="text" style="border:1px dashed;" size="22"> 
																					<input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$"> 
																					<input name="accept" type="submit" value="Continue"> 
																				</div>
																			</center>
																		</div>
										     						</td>
																</tr>
															</table>
														</center>
													</div>
												</center>
											</td>
										</tr>
									</table>
								</center>
							</div>
						</td>
					</tr>
				</table>
			</center>
		</form>
	</body> 
</html>

EOD;
		return $htmltext;
	}

	// Vouchers are not found, return the normal user/pass auth page
	$htmltext = <<<EOD
<html> 
	<body> 
		<form method="post" action="\$PORTAL_ACTION\$"> 
		<input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$">
			<center>
				<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
					<tr height="10" bgcolor="#990000">
						<td style="border-bottom:1px solid #000000">
							<font color='white'>
								<b>
									{$g['product_name']} captive portal
								</b>
							</font>
						</td>
					</tr>
					<tr>
						<td>
							<div id="mainlevel">
								<center>
									<table width="100%" border="0" cellpadding="5" cellspacing="0">
								 		<tr>
								    		<td>
												<center>
													<div id="mainarea">
														<center>
															<table width="100%" border="0" cellpadding="5" cellspacing="5">
																<tr>
										     						<td>
																		<div id="maindivarea">
																			<center>
																				<div id='statusbox'>
																					<font color='red' face='arial' size='+1'>
																						<b>
																							\$PORTAL_MESSAGE\$
																						</b>
																					</font>
																				</div>
																				<br/>
																				<div id='loginbox'>
																					<table>
																					   <tr><td colspan="2"><center>Welcome to the {$g['product_name']} Captive Portal!</td></tr>
																					   <tr><td>&nbsp;</td></tr>
																					   <tr><td align="right">Username:</td><td><input name="auth_user" type="text" style="border: 1px dashed;"></td></tr>
																					   <tr><td align="right">Password:</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
																					   <tr><td>&nbsp;</td></tr>
																					   <tr>
																					     <td colspan="2">
																							<center><input name="accept" type="submit" value="Continue"></center>
																					     </td>
																					   </tr>
																					</table>
																				</div>
																			</center>
																		</div>
										     						</td>
																</tr>
															</table>
														</center>
													</div>
												</center>
											</td>
										</tr>
									</table>
								</center>
							</div>
						</td>
					</tr>
				</table>
			</center>
		</form>
	</body> 
</html>

EOD;

	return $htmltext;
}

function captiveportal_configure() {
	global $config, $g;

	$captiveportallck = lock('captiveportal');
	
	if (isset($config['captiveportal']['enable'])) {

		if ($g['booting'])
			echo "Starting captive portal... ";

		/* kill any running mini_httpd */
		killbypid("{$g['varrun_path']}/lighty-CaptivePortal.pid");
		killbypid("{$g['varrun_path']}/lighty-CaptivePortal-SSL.pid");

		/* remove old information */
		unlink_if_exists("{$g['vardb_path']}/captiveportal.db");
		unlink_if_exists("{$g['vardb_path']}/captiveportal_mac.db");
		unlink_if_exists("{$g['vardb_path']}/captiveportal_ip.db");
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius.db");

		/* setup new database in case someone tries to access the status -> captive portal page */
		touch("{$g['vardb_path']}/captiveportal.db");

		/* kill any running minicron */
		killbypid("{$g['varrun_path']}/minicron.pid");

		/* init ipfw rules */
		captiveportal_init_rules(true);

		/* stop accounting on all clients */
		captiveportal_radius_stop_all(true);

		/* initialize minicron interval value */
		$croninterval = $config['captiveportal']['croninterval'] ? $config['captiveportal']['croninterval'] : 60;

		/* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */
		if ((!is_numeric($croninterval)) || ($croninterval < 10)) { $croninterval = 60; }

		/* write portal page */
		if ($config['captiveportal']['page']['htmltext'])
			$htmltext = base64_decode($config['captiveportal']['page']['htmltext']);
		else {
			/* example/template page */
			$htmltext = get_default_captive_portal_html();
		}

		$fd = @fopen("{$g['varetc_path']}/captiveportal.html", "w");
		if ($fd) {
			// Special case handling.  Convert so that we can pass this page
			// through the PHP interpreter later without clobbering the vars.
			$htmltext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $htmltext);
			$htmltext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $htmltext);
			$htmltext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $htmltext);
			$htmltext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $htmltext);
			$htmltext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $htmltext);
			$htmltext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $htmltext);
			fwrite($fd, $htmltext);
			fclose($fd);
		}

		/* write error page */
		if ($config['captiveportal']['page']['errtext'])
			$errtext = base64_decode($config['captiveportal']['page']['errtext']);
		else {
			/* example page */
			$errtext = <<<EOD
<html> 
	<body> 
		<form method="post" action="\$PORTAL_ACTION\$"> 
		<input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$">
			<center>
				<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
					<tr height="10" bgcolor="#990000">
						<td style="border-bottom:1px solid #000000">
							<font color='white'>
								<b>
									{$g['product_name']} captive portal
								</b>
							</font>
						</td>
					</tr>
					<tr>
						<td>
							<div id="mainlevel">
								<center>
									<table width="100%" border="0" cellpadding="5" cellspacing="0">
								 		<tr>
								    		<td>
												<center>
													<div id="mainarea">
														<center>
															<table width="100%" border="0" cellpadding="5" cellspacing="5">
																<tr>
										     						<td>
																		<div id="maindivarea">
																			<center>
																				<div id='statusbox'>
																					<font color='red' face='arial' size='+1'>
																						<b>
																							\$PORTAL_MESSAGE\$
																						</b>
																					</font>
																				</div>
																				<br/>
																				<div id='loginbox'>
																					<table>
																					   <tr><td colspan="2"><center>Welcome to the {$g['product_name']} Captive Portal!</td></tr>
																					   <tr><td>&nbsp;</td></tr>
																					   <tr><td align="right">Username:</td><td><input name="auth_user" type="text" style="border: 1px dashed;"></td></tr>
																					   <tr><td align="right">Password:</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
																					   <tr><td>&nbsp;</td></tr>
																					   <tr>
																					     <td colspan="2">
																							<center><input name="accept" type="submit" value="Continue"></center>
																					     </td>
																					   </tr>
																					</table>
																				</div>
																			</center>
																		</div>
										     						</td>
																</tr>
															</table>
														</center>
													</div>
												</center>
											</td>
										</tr>
									</table>
								</center>
							</div>
						</td>
					</tr>
				</table>
			</center>
		</form>
	</body> 
</html>

EOD;
		}

		$fd = @fopen("{$g['varetc_path']}/captiveportal-error.html", "w");
		if ($fd) {
			// Special case handling.  Convert so that we can pass this page
			// through the PHP interpreter later without clobbering the vars.
			$errtext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $errtext);
			$errtext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $errtext);
			$errtext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $errtext);
			$errtext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $errtext);
			$errtext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $errtext);
			$errtext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $errtext);
			fwrite($fd, $errtext);
			fclose($fd);
		}

		/* write error page */
		if ($config['captiveportal']['page']['logouttext'])
			$logouttext = base64_decode($config['captiveportal']['page']['logouttext']);
		else {
			/* example page */
			$logouttext = <<<EOD
<HTML>
<HEAD><TITLE>Redirecting...</TITLE></HEAD>
<BODY>
<SPAN STYLE="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
<B>Redirecting to <A HREF="<?=\$my_redirurl;?>"><?=\$my_redirurl;?></A>...</B>
</SPAN>
<SCRIPT LANGUAGE="JavaScript">
<!--
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
if (LogoutWin) {
    LogoutWin.document.write('<HTML>');
    LogoutWin.document.write('<HEAD><TITLE>Logout</TITLE></HEAD>') ;
    LogoutWin.document.write('<BODY BGCOLOR="#435370">');
    LogoutWin.document.write('<DIV ALIGN="center" STYLE="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
    LogoutWin.document.write('<B>Click the button below to disconnect</B><P>');
    LogoutWin.document.write('<FORM METHOD="POST" ACTION="<?=\$logouturl;?>">');
    LogoutWin.document.write('<INPUT NAME="logout_id" TYPE="hidden" VALUE="<?=\$sessionid;?>">');
    LogoutWin.document.write('<INPUT NAME="logout" TYPE="submit" VALUE="Logout">');
    LogoutWin.document.write('</FORM>');
    LogoutWin.document.write('</DIV></BODY>');
    LogoutWin.document.write('</HTML>');
    LogoutWin.document.close();
}

document.location.href="<?=\$my_redirurl;?>";
-->
</SCRIPT>
</BODY>
</HTML>

EOD;
		}

		$fd = @fopen("{$g['varetc_path']}/captiveportal-logout.html", "w");
		if ($fd) {
			fwrite($fd, $logouttext);
			fclose($fd);
		}
		/* write elements */
		captiveportal_write_elements();

		/* start up the webserving daemon */
		captiveportal_init_webgui();

		/* start pruning process (interval defaults to 60 seconds) */
		mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/minicron.pid " .
			"/etc/rc.prunecaptiveportal");

		/* generate radius server database */
		if ($config['captiveportal']['radiusip'] && (!isset($config['captiveportal']['auth_method']) ||
				($config['captiveportal']['auth_method'] == "radius"))) {
			$radiusip = $config['captiveportal']['radiusip'];
			$radiusip2 = ($config['captiveportal']['radiusip2']) ? $config['captiveportal']['radiusip2'] : null;

			if ($config['captiveportal']['radiusport'])
				$radiusport = $config['captiveportal']['radiusport'];
			else
				$radiusport = 1812;

			if ($config['captiveportal']['radiusacctport'])
				$radiusacctport = $config['captiveportal']['radiusacctport'];
			else
				$radiusacctport = 1813;

			if ($config['captiveportal']['radiusport2'])
				$radiusport2 = $config['captiveportal']['radiusport2'];
			else
				$radiusport2 = 1812;

			$radiuskey = $config['captiveportal']['radiuskey'];
			$radiuskey2 = ($config['captiveportal']['radiuskey2']) ? $config['captiveportal']['radiuskey2'] : null;

			$fd = @fopen("{$g['vardb_path']}/captiveportal_radius.db", "w");
			if (!$fd) {
				printf("Error: cannot open radius DB file in captiveportal_configure().\n");
				return 1;
			} else if (isset($radiusip2, $radiuskey2)) {
				fwrite($fd,$radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . "\n"
					 . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2);
			} else {
				fwrite($fd,$radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey);
			}
			fclose($fd);
		}

		if ($g['booting'])
			echo "done\n";

	} else {
		killbypid("{$g['varrun_path']}/lighty-CaptivePortal.pid");
		killbypid("{$g['varrun_path']}/minicron.pid");

		captiveportal_radius_stop_all(true);

		mwexec("/sbin/sysctl net.link.ether.ipfw=0");

		/* unload ipfw */
		if (is_module_loaded("ipfw.ko"))		
			mwexec("/sbin/kldunload ipfw.ko");
		$listifs = get_configured_interface_list_by_realif();
		foreach ($listifs as $listrealif => $listif) {
			if (!empty($listrealif)) {
				if (does_interface_exist($listrealif)) {
					pfSense_interface_flags($listrealif, -IFF_IPFW_FILTER);
					$carpif = link_ip_to_carp_interface(find_interface_ip($listrealif));
                        		if (!empty($carpif)) {
						$carpsif = explode(" ", $carpif);
						foreach ($carpsif as $cpcarp)
							pfSense_interface_flags($cpcarp, -IFF_IPFW_FILTER);
					}
				}
			}
		}
	}

	unlock($captiveportallck);
	
	return 0;
}

function captiveportal_init_webgui() {
	global $g, $config;

	 if (!isset($config['captiveportal']['enable']))
                return;

	if ($config['captiveportal']['maxproc'])
		$maxproc = $config['captiveportal']['maxproc'];
	else
		$maxproc = 16;

	$use_fastcgi = true;

	if (isset($config['captiveportal']['httpslogin'])) {
		$cert = base64_decode($config['captiveportal']['certificate']);
		if (isset($config['captiveportal']['cacertificate']))
			$cacert = base64_decode($config['captiveportal']['cacertificate']);
		else
			$cacert = "";
		$key = base64_decode($config['captiveportal']['private-key']);
		/* generate lighttpd configuration */
		system_generate_lighty_config("{$g['varetc_path']}/lighty-CaptivePortal-SSL.conf",
			$cert, $key, $cacert, "lighty-CaptivePortal-ssl.pid", "8001", "/usr/local/captiveportal/",
			"cert-portal.pem", "ca-portal.pem", "1", $maxproc, $use_fastcgi, true);
	}

	/* generate lighttpd configuration */
	system_generate_lighty_config("{$g['varetc_path']}/lighty-CaptivePortal.conf",
		"", "", "", "lighty-CaptivePortal.pid", "8000", "/usr/local/captiveportal/",
		"cert-portal.pem", "ca-portal.pem", "1", $maxproc, $use_fastcgi, true);

	/* attempt to start lighttpd */
	$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-CaptivePortal.conf");

	/* fire up https instance */
	if (isset($config['captiveportal']['httpslogin']))
		$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-CaptivePortal-SSL.conf");
}

function captiveportal_init_rules($reinit = false) {
	global $config, $g;

	if (!isset($config['captiveportal']['enable']))
		return;

	$cpips = array();
	$ifaces = get_configured_interface_list();
	foreach ($ifaces as $kiface => $kiface2) {
		$tmpif = get_real_interface($kiface);
		pfSense_interface_flags($tmpif, -IFF_IPFW_FILTER);
	}
	$cpinterfaces = explode(",", $config['captiveportal']['interface']);
	$firsttime = 0;
	foreach ($cpinterfaces as $cpifgrp) {
		if (!isset($ifaces[$cpifgrp]))
			continue;
		$tmpif = get_real_interface($cpifgrp);
		if (!empty($tmpif)) {
			if ($firsttime > 0)
				$cpinterface .= " or ";
			$cpinterface .= "via {$tmpif}";
			$firsttime = 1;
			$cpipm = get_interface_ip($cpifgrp);
			if (is_ipaddr($cpipm)) {
				$carpif = link_ip_to_carp_interface($cpipm);
				if (!empty($carpif)) {
					$carpsif = explode(" ", $carpif);
					foreach ($carpsif as $cpcarp) {
						pfSense_interface_flags($cpcarp, IFF_IPFW_FILTER);
						$carpip = find_interface_ip($cpcarp);
						if (is_ipaddr($carpip))
							$cpips[] = $carpip;
					}
				}
				$cpips[] = $cpipm;
				pfSense_interface_flags($tmpif, IFF_IPFW_FILTER);
			}
		}
	}
	if (count($cpips) > 0) {
		$cpactive = true;
		$cpinterface = "{ {$cpinterface} } ";
        } else
		return false;

	if ($reinit == false)
		$captiveportallck = lock('captiveportal');

	/* init dummynet/ipfw rules number database */
	captiveportal_init_ipfw_ruleno();

	/* make sure ipfw is loaded */
	if (!is_module_loaded("ipfw.ko"))
		filter_load_ipfw();
	/* Always load dummynet now that even allowed ip and mac passthrough use it. */
	if (!is_module_loaded("dummynet.ko"))
		mwexec("/sbin/kldload dummynet");

	$cprules =  "add 65291 set 1 allow pfsync from any to any\n";
	$cprules .= "add 65292 set 1 allow carp from any to any\n";

	$cprules .= <<<EOD
# add 65300 set 1 skipto 65534 all from any to any not layer2
# layer 2: pass ARP
add 65301 set 1 pass layer2 mac-type arp
# pfsense requires for WPA
add 65302 set 1 pass layer2 mac-type 0x888e
add 65303 set 1 pass layer2 mac-type 0x88c7

# PPP Over Ethernet Discovery Stage
add 65304 set 1 pass layer2 mac-type 0x8863
# PPP Over Ethernet Session Stage
add 65305 set 1 pass layer2 mac-type 0x8864
# Allow WPA
add 65306 set 1 pass layer2 mac-type 0x888e

# layer 2: block anything else non-IP
add 65307 set 1 deny layer2 not mac-type ip

EOD;

	$rulenum = 65310;
	$ipcount = 0;
	$ips = "";
	foreach ($cpips as $cpip) {
		if($ipcount == 0) {
			$ips = "{$cpip} ";
		} else {
			$ips .= "or {$cpip} ";
		}
		$ipcount++;
	}
	$ips = "{ 255.255.255.255 or {$ips} }";
	$cprules .= "add {$rulenum} set 1 pass ip from any to {$ips} in\n";
	$rulenum++;
	$cprules .= "add {$rulenum} set 1 pass ip from {$ips} to any out\n";
	$rulenum++;
	$cprules .= "add {$rulenum} set 1 pass icmp from {$ips} to any out icmptype 0\n";
	$rulenum++;
	$cprules .= "add {$rulenum} set 1 pass icmp from any to {$ips} in icmptype 8 \n";
	$rulenum++;
	/* Allowed ips */
	$cprules .= "add {$rulenum} allow ip from table(3) to any in\n";
	$rulenum++;
	$cprules .= "add {$rulenum} allow ip from any to table(4) out\n";
	$rulenum++;
	$cprules .= "add {$rulenum} pipe tablearg ip from table(5) to any in\n";
	$rulenum++;
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(6) out\n";
	$rulenum++;
	$cprules .= "add {$rulenum} allow ip from any to table(7) in\n";
	$rulenum++;
	$cprules .= "add {$rulenum} allow ip from table(8) to any out\n";
	$rulenum++;
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(9) in\n";
	$rulenum++;
	$cprules .= "add {$rulenum} pipe tablearg ip from table(10) to any out\n";
	$rulenum++;

	/* Authenticated users rules. */
	if (isset($config['captiveportal']['peruserbw'])) {
		$cprules .= "add {$rulenum} set 1 pipe tablearg ip from table(1) to any in\n";
		$rulenum++;
		$cprules .= "add {$rulenum} set 1 pipe tablearg ip from any to table(2) out\n";
		$rulenum++;
	} else {
		$cprules .= "add {$rulenum} set 1 allow ip from table(1) to any in\n";
                $rulenum++;
                $cprules .= "add {$rulenum} set 1 allow ip from any to table(2) out\n";
                $rulenum++;
	}
	
       $cprules .= <<<EOD

# redirect non-authenticated clients to captive portal
add 65531 set 1 fwd 127.0.0.1,8000 tcp from any to any in
# let the responses from the captive portal web server back out
add 65532 set 1 pass tcp from any to any out
# block everything else
add 65533 set 1 deny all from any to any
# pass everything else on layer2
add 65534 set 1 pass all from any to any layer2

EOD;

	/* generate passthru mac database */
	$cprules .= captiveportal_passthrumac_configure(true);
	$cprules .= "\n";
	/* allowed ipfw rules to make allowed ip work */
	$cprules .= captiveportal_allowedip_configure();

	/* load rules */
	if ($reinit == true)
		$cprules = "table all flush\nflush\n{$cprules}";
	else {
		$tmprules = "table 3 flush\n";
		$tmprules .= "table 4 flush\n";
		$tmprules .= "table 5 flush\n";
		$tmprules .= "table 6 flush\n";
		$tmprules .= "table 7 flush\n";
		$tmprules .= "table 8 flush\n";
		$tmprules .= "table 9 flush\n";
		$tmprules .= "table 10 flush\n";
		$tmprules .= "flush\n";
		$cprules = "{$tmprules}\n{$cprules}";
	}

	file_put_contents("{$g['tmp_path']}/ipfw.cp.rules", $cprules);
	mwexec("/sbin/ipfw -q {$g['tmp_path']}/ipfw.cp.rules", true);
	@unlink("{$g['tmp_path']}/ipfw.cp.rules");

	if ($reinit == false)
		unlock($captiveportallck);


	/* filter on layer2 as well so we can check MAC addresses */
	mwexec("/sbin/sysctl net.link.ether.ipfw=1");

	return $cprules;
}

/* remove clients that have been around for longer than the specified amount of time */
/* db file structure:
timestamp,ipfw_rule_no,clientip,clientmac,username,sessionid,password,session_timeout,idle_timeout,session_terminate_time */

/* (password is in Base64 and only saved when reauthentication is enabled) */
function captiveportal_prune_old() {

    global $g, $config;

    /* check for expired entries */
    if ($config['captiveportal']['timeout'])
        $timeout = $config['captiveportal']['timeout'] * 60;
    else
        $timeout = 0;

    if ($config['captiveportal']['idletimeout'])
        $idletimeout = $config['captiveportal']['idletimeout'] * 60;
    else
        $idletimeout = 0;

    if (!$timeout && !$idletimeout && !isset($config['captiveportal']['reauthenticate']) && 
		!isset($config['captiveportal']['radiussession_timeout']) && !isset($config['voucher']['enable']))
        return;

    $captiveportallck = lock('captiveportal');

    /* read database */
    $cpdb = captiveportal_read_db();

    $radiusservers = captiveportal_get_radius_servers();

    /*  To make sure we iterate over ALL accounts on every run the count($cpdb) is moved
     *  outside of the loop. Otherwise the loop would evaluate count() on every iteration
     *  and since $i would increase and count() would decrement they would meet before we
     *  had a chance to iterate over all accounts.
     */
    $unsetindexes = array();
    $no_users = count($cpdb);
    for ($i = 0; $i < $no_users; $i++) {

        $timedout = false;
        $term_cause = 1;

        /* hard timeout? */
        if ($timeout) {
            if ((time() - $cpdb[$i][0]) >= $timeout) {
                $timedout = true;
                $term_cause = 5; // Session-Timeout
            }
        }

        /* Session-Terminate-Time */
        if (!$timedout && !empty($cpdb[$i][9])) {
            if (time() >= $cpdb[$i][9]) {
                $timedout = true;
                $term_cause = 5; // Session-Timeout
            }
        }

        /* check if the radius idle_timeout attribute has been set and if its set change the idletimeout to this value */
        $idletimeout = (is_numeric($cpdb[$i][8])) ? $cpdb[$i][8] : $idletimeout;
        /* if an idle timeout is specified, get last activity timestamp from ipfw */
        if (!$timedout && $idletimeout) {
            $lastact = captiveportal_get_last_activity($cpdb[$i][2]);
			/*  If the user has logged on but not sent any traffic they will never be logged out.
			 *  We "fix" this by setting lastact to the login timestamp. 
			 */
			$lastact = $lastact ? $lastact : $cpdb[$i][0];
            if ($lastact && ((time() - $lastact) >= $idletimeout)) {
                $timedout = true;
                $term_cause = 4; // Idle-Timeout
                $stop_time = $lastact; // Entry added to comply with WISPr
            }
        }

	/* if vouchers are configured, activate session timeouts */
	if (!$timedout && isset($config['voucher']['enable']) && !empty($cpdb[$i][7])) {
		if (time() >= ($cpdb[$i][0] + $cpdb[$i][7])) {
			$timedout = true;
			$term_cause = 5; // Session-Timeout
		}
	}

        /* if radius session_timeout is enabled and the session_timeout is not null, then check if the user should be logged out */
        if (!$timedout && isset($config['captiveportal']['radiussession_timeout']) && !empty($cpdb[$i][7])) {
            if (time() >= ($cpdb[$i][0] + $cpdb[$i][7])) {
                $timedout = true;
                $term_cause = 5; // Session-Timeout
            }
        }

        if ($timedout) {
            captiveportal_disconnect($cpdb[$i], $radiusservers,$term_cause,$stop_time);
            captiveportal_logportalauth($cpdb[$i][4], $cpdb[$i][3], $cpdb[$i][2], "TIMEOUT");
	    $unsetindexes[$i] = $i;
        }

        /* do periodic RADIUS reauthentication? */
        if (!$timedout && isset($config['captiveportal']['reauthenticate']) &&
            !empty($radiusservers)) {

            if (isset($config['captiveportal']['radacct_enable'])) {
                if ($config['captiveportal']['reauthenticateacct'] == "stopstart") {
                    /* stop and restart accounting */
                    RADIUS_ACCOUNTING_STOP($cpdb[$i][1], // ruleno
                                           $cpdb[$i][4], // username
                                           $cpdb[$i][5], // sessionid
                                           $cpdb[$i][0], // start time
                                           $radiusservers,
                                           $cpdb[$i][2], // clientip
                                           $cpdb[$i][3], // clientmac
                                           10); // NAS Request
                    exec("/sbin/ipfw table 1 entryzerostats {$cpdb[$i][2]}");
                    exec("/sbin/ipfw table 2 entryzerostats {$cpdb[$i][2]}");
                    RADIUS_ACCOUNTING_START($cpdb[$i][1], // ruleno
                                            $cpdb[$i][4], // username
                                            $cpdb[$i][5], // sessionid
                                            $radiusservers,
                                            $cpdb[$i][2], // clientip
                                            $cpdb[$i][3]); // clientmac
                } else if ($config['captiveportal']['reauthenticateacct'] == "interimupdate") {
                    RADIUS_ACCOUNTING_STOP($cpdb[$i][1], // ruleno
                                           $cpdb[$i][4], // username
                                           $cpdb[$i][5], // sessionid
                                           $cpdb[$i][0], // start time
                                           $radiusservers,
                                           $cpdb[$i][2], // clientip
                                           $cpdb[$i][3], // clientmac
                                           10, // NAS Request
                                           true); // Interim Updates
                }
            }

            /* check this user against RADIUS again */
            $auth_list = RADIUS_AUTHENTICATION($cpdb[$i][4], // username
                                          base64_decode($cpdb[$i][6]), // password
                                            $radiusservers,
                                          $cpdb[$i][2], // clientip
                                          $cpdb[$i][3], // clientmac
                                          $cpdb[$i][1]); // ruleno

            if ($auth_list['auth_val'] == 3) {
                captiveportal_disconnect($cpdb[$i], $radiusservers, 17);
                captiveportal_logportalauth($cpdb[$i][4], $cpdb[$i][3], $cpdb[$i][2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
	        $unsetindexes[$i] = $i;
            }
        }
    }
    /* This is a kludge to overcome some php weirdness */
    foreach($unsetindexes as $unsetindex)
	unset($cpdb[$unsetindex]);

    /* write database */
    captiveportal_write_db($cpdb);

    unlock($captiveportallck);
}

/* remove a single client according to the DB entry */
function captiveportal_disconnect($dbent, $radiusservers,$term_cause = 1,$stop_time = null) {

	global $g, $config;

	$stop_time = (empty($stop_time)) ? time() : $stop_time;

	/* this client needs to be deleted - remove ipfw rules */
	if (isset($config['captiveportal']['radacct_enable']) && !empty($radiusservers)) {
		RADIUS_ACCOUNTING_STOP($dbent[1], // ruleno
							   $dbent[4], // username
							   $dbent[5], // sessionid
							   $dbent[0], // start time
							   $radiusservers,
							   $dbent[2], // clientip
							   $dbent[3], // clientmac
							   $term_cause, // Acct-Terminate-Cause
							   false,
							   $stop_time);
	}
	/* Delete client's ip entry from tables 3 and 4. */
	mwexec("/sbin/ipfw table 1 delete {$dbent[2]}");
	mwexec("/sbin/ipfw table 2 delete {$dbent[2]}");

	/* Release the ruleno so it can be reallocated to new clients. */
	captiveportal_free_ipfw_ruleno($dbent[1]);

	/* 
	* These are the pipe numbers we use to control traffic shaping for each logged in user via captive portal
	* We could get an error if the pipe doesn't exist but everything should still be fine
	*/
	if (isset($config['captiveportal']['peruserbw'])) {
		mwexec("/sbin/ipfw pipe " . ($dbent[1]+20000) . " delete");
		mwexec("/sbin/ipfw pipe " . ($dbent[1]+20001) . " delete");
	}

	/* XXX: Redundant?! Ensure all pf(4) states are killed. */
	mwexec("pfctl -k {$dbent[2]}");
	mwexec("pfctl -K {$dbent[2]}");

}

/* remove a single client by ipfw rule number */
function captiveportal_disconnect_client($id,$term_cause = 1) {

	global $g, $config;

	$captiveportallck = lock('captiveportal');

	/* read database */
	$cpdb = captiveportal_read_db();
	$radiusservers = captiveportal_get_radius_servers();

	/* find entry */
	$tmpindex = 0;
	$cpdbcount = count($cpdb);
	for ($i = 0; $i < $cpdbcount; $i++) {
		if ($cpdb[$i][1] == $id) {
			captiveportal_disconnect($cpdb[$i], $radiusservers, $term_cause);
			captiveportal_logportalauth($cpdb[$i][4], $cpdb[$i][3], $cpdb[$i][2], "DISCONNECT");
			unset($cpdb[$i]);
			break;
		}
	}		

	/* write database */
	captiveportal_write_db($cpdb);

	unlock($captiveportallck);
}

/* send RADIUS acct stop for all current clients */
function captiveportal_radius_stop_all($lock = false) {
	global $g, $config;

	if (!isset($config['captiveportal']['radacct_enable']))
		return;

	if (!$lock)
		$captiveportallck = lock('captiveportal');

	$cpdb = captiveportal_read_db();

	$radiusservers = captiveportal_get_radius_servers();
	if (!empty($radiusservers)) {
		for ($i = 0; $i < count($cpdb); $i++) {
			RADIUS_ACCOUNTING_STOP($cpdb[$i][1], // ruleno
								   $cpdb[$i][4], // username
								   $cpdb[$i][5], // sessionid
								   $cpdb[$i][0], // start time
								   $radiusservers,
								   $cpdb[$i][2], // clientip
								   $cpdb[$i][3], // clientmac
								   7); // Admin Reboot
		}
	}
	if (!$lock)
		unlock($captiveportallck);
}

function captiveportal_passthrumac_configure_entry($macent) {
	$rules = "";
        $enBwup = isset($macent['bw_up']);
        $enBwdown = isset($macent['bw_down']);
	$actionup = "allow";
	$actiondown = "allow";

        if ($enBwup && $enBwdown)
                $ruleno = captiveportal_get_next_ipfw_ruleno(2000, 49899, true);
        else
                $ruleno = captiveportal_get_next_ipfw_ruleno(2000, 49899, false);

	if ($enBwup) {
                $bw_up = $ruleno + 20000;
                $rules .= "pipe {$bw_up} config bw {$macent['bw_up']}Kbit/s queue 100\n";
		$actionup = "pipe {$bw_up}";
        }
        if ($enBwdown) {
		$bw_down = $ruleno + 20001;
		$rules .= "pipe {$bw_down} config bw {$macent['bw_down']}Kbit/s queue 100\n";
		$actiondown = "pipe {$bw_down}";
        }
	$rules .= "add {$ruleno} {$actiondown} ip from any to any MAC {$macent['mac']} any\n";
	$ruleno++;
	$rules .= "add {$ruleno} {$actionup} ip from any to any MAC any {$macent['mac']}\n";

	return $rules;
}

function captiveportal_passthrumac_configure($lock = false) {
	global $config, $g;

	$rules = "";

	if (is_array($config['captiveportal']['passthrumac'])) {
		$macdb = array();
		foreach ($config['captiveportal']['passthrumac'] as $macent) {
			$rules .= captiveportal_passthrumac_configure_entry($macent);
			$macdb[$macent['mac']]['active']  = true;

		}
	}

	return $rules;
}

function captiveportal_passthrumac_findbyname($username) {
	global $config;

	if (is_array($config['captiveportal']['passthrumac'])) {
		foreach ($config['captiveportal']['passthrumac'] as $macent) {
			if ($macent['username'] == $username)
				return $macent;
		}
	}
	return NULL;
}

/* 
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
 * table (5=IN)/(6=OUT) hold allowed ip's with bw limit.
 */
function captiveportal_allowedip_configure_entry($ipent) {

	$rules = "";
	$enBwup = isset($ipent['bw_up']);
	$enBwdown = isset($ipent['bw_down']);
	$bw_up = "";
        $bw_down = "";
        $tablein = array();
        $tableout = array();

	if ($enBwup && $enBwdown)
		$ruleno = captiveportal_get_next_ipfw_ruleno(2000, 49899, true);
	else
		$ruleno = captiveportal_get_next_ipfw_ruleno(2000, 49899, false);

        if ($ipent['dir'] == "from") {
        	if ($enBwup)
                	$tablein[] = 5;
                else
                	$tablein[] = 3;
                if ($enBwdown)
                        $tableout[] = 6;
                else
                        $tableout[] = 4;
        } else if ($ipent['dir'] == "to") {
                if ($enBwup)
                	$tablein[] = 9;
                else
                        $tablein[] = 7;
                if ($enBwdown)
                        $tableout[] = 10;
                else
                        $tableout[] = 8;
        } else if ($ipent['dir'] == "both") {
                if ($enBwup) {
                        $tablein[] = 5;
                        $tablein[] = 9;
                } else {
                        $tablein[] = 3;
                        $tablein[] = 7;
                }
        	if ($enBwdown) {
                        $tableout[] = 6;
                        $tableout[] = 10;
                } else {
                        $tableout[] = 4;
                	$tableout[] = 8;
                }
        }
        if ($enBwup) {
                $bw_up = $ruleno + 20000;
        	$rules .= "pipe {$bw_up} config bw {$ipent['bw_up']}Kbit/s queue 100\n";
        }
	$subnet = "";
	if (!empty($ipent['sn']))
		$subnet = "/{$ipent['sn']}";
	foreach ($tablein as $table)
               $rules .= "table {$table} add {$ipent['ip']}{$subnet} {$bw_up}\n";
        if ($enBwdown) {
               $bw_down = $ruleno + 20001;
               $rules .= "pipe {$bw_down} config bw {$ipent['bw_down']}Kbit/s queue 100\n";
        }
        foreach ($tableout as $table)
        	$rules .= "table {$table} add {$ipent['ip']}{$subnet} {$bw_down}\n";

	return $rules;
}

function captiveportal_allowedip_configure() {
	global $config, $g;

	$rules = "";
	if (is_array($config['captiveportal']['allowedip'])) {
		foreach ($config['captiveportal']['allowedip'] as $ipent) {
			$rules .= captiveportal_allowedip_configure_entry($ipent);
		}
	}

	return $rules;
}

/* get last activity timestamp given client IP address */
function captiveportal_get_last_activity($ip) {

	$ipfwoutput = "";

	exec("/sbin/ipfw table 1 entrystats {$ip} 2>/dev/null", $ipfwoutput);
	/* Reading only from one of the tables is enough of approximation. */
	if ($ipfwoutput[0]) {
		$ri = explode(" ", $ipfwoutput[0]);
		if ($ri[4])
			return $ri[4];
	}

	return 0;
}

/* read RADIUS servers into array */
function captiveportal_get_radius_servers() {

        global $g;

        if (file_exists("{$g['vardb_path']}/captiveportal_radius.db")) {
                $radiusservers = array();
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius.db", 
			FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
		if ($cpradiusdb)
		foreach($cpradiusdb as $cpradiusentry) {
                	$line = trim($cpradiusentry);
                        if ($line) {
                        	$radsrv = array();
                                list($radsrv['ipaddr'],$radsrv['port'],$radsrv['acctport'],$radsrv['key']) = explode(",",$line);
                        	$radiusservers[] = $radsrv;
                        }
		}

		return $radiusservers;
        }

        return false;
}

/* log successful captive portal authentication to syslog */
/* part of this code from php.net */
function captiveportal_logportalauth($user,$mac,$ip,$status, $message = null) {
	$message = trim($message);
	// Log it
	if (!$message)
		$message = "$status: $user, $mac, $ip";
	else
		$message = "$status: $user, $mac, $ip, $message";
	captiveportal_syslog($message);
	closelog();
}

/* log simple messages to syslog */
function captiveportal_syslog($message) {
	define_syslog_variables();
	$message = trim($message);
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
	// Log it
	syslog(LOG_INFO, $message);
	closelog();
}

function radius($username,$password,$clientip,$clientmac,$type) {
    global $g, $config;

    /* Start locking from the beginning of an authentication session */
    $captiveportallck = lock('captiveportal');

    $ruleno = captiveportal_get_next_ipfw_ruleno();

    /* If the pool is empty, return appropriate message and fail authentication */
    if (is_null($ruleno)) {
        $auth_list = array();
        $auth_list['auth_val'] = 1;
        $auth_list['error'] = "System reached maximum login capacity";
        unlock($captiveportallck);
        return $auth_list;
    }

    /*
     * Drop the lock since radius takes some time to finish.
     * The implementation is reentrant so we gain speed with this.
     */
    unlock($captiveportallck);

    $radiusservers = captiveportal_get_radius_servers();

    $auth_list = RADIUS_AUTHENTICATION($username,
                    $password,
                    $radiusservers,
                    $clientip,
                    $clientmac,
                    $ruleno);

    $captiveportallck = lock('captiveportal');

    if ($auth_list['auth_val'] == 2) {
        captiveportal_logportalauth($username,$clientmac,$clientip,$type);
        $sessionid = portal_allow($clientip,
                    $clientmac,
                    $username,
                    $password,
                    $auth_list,
                    $ruleno);
    }

    unlock($captiveportallck);

    return $auth_list;

}

/* read captive portal DB into array */
function captiveportal_read_db() {

        global $g;

        $cpdb = array();
        $fd = @fopen("{$g['vardb_path']}/captiveportal.db", "r");
        if ($fd) {
                while (!feof($fd)) {
                        $line = trim(fgets($fd));
                        if ($line) {
                                $cpdb[] = explode(",", $line);
                        }
                }
                fclose($fd);
        }
        return $cpdb;
}

/* write captive portal DB */
function captiveportal_write_db($cpdb) {
                 
        global $g;
                
        $fd = @fopen("{$g['vardb_path']}/captiveportal.db", "w");
        if ($fd) { 
                foreach ($cpdb as $cpent) {
                        fwrite($fd, join(",", $cpent) . "\n");
                }       
                fclose($fd);
        }       
}

function captiveportal_write_elements() {
	global $g, $config;
    
	/* delete any existing elements */
	if (is_dir($g['captiveportal_element_path'])) {
		$dh = opendir($g['captiveportal_element_path']);
		while (($file = readdir($dh)) !== false) {
			if ($file != "." && $file != "..")
				unlink($g['captiveportal_element_path'] . "/" . $file);
		}
		closedir($dh);
	} else
		@mkdir($g['captiveportal_element_path']);

	if (is_array($config['captiveportal']['element'])) {
		conf_mount_rw();
		foreach ($config['captiveportal']['element'] as $data) {
			$fd = @fopen($g['captiveportal_element_path'] . '/' . $data['name'], "wb");
			if (!$fd) {
				printf("Error: cannot open '{$data['name']}' in captiveportal_write_elements().\n");
				return 1;
			}
			$decoded = base64_decode($data['content']);
			fwrite($fd,$decoded);
			fclose($fd);
			unlink_if_exists("{$g['captiveportal_path']}/{$data['name']}");
			unlink_if_exists("{$g['captiveportal_path']}/{$data['name']}");
			mwexec("cd {$g['captiveportal_path']}/ && ln -s {$g['captiveportal_element_path']}/{$data['name']} {$data['name']}");
		}
		conf_mount_ro();
	}
    
	return 0;
}

function captiveportal_init_ipfw_ruleno($rulenos_start = 2000, $rulenos_range_max = 49899) {
	global $g;

	@unlink("{$g['vardb_path']}/captiveportal.rules");
	$rules = array_pad(array(), $rulenos_range_max - $rulenos_start, false);
	file_put_contents("{$g['vardb_path']}/captiveportal.rules", serialize($rules));
}

/*
 * This function will calculate the lowest free firewall ruleno
 * within the range specified based on the actual logged on users
 *
 */
function captiveportal_get_next_ipfw_ruleno($rulenos_start = 2000, $rulenos_range_max = 49899, $usebw = false) {
	global $config, $g;

	if(!isset($config['captiveportal']['enable']))
		return NULL;

	$ruleno = 0;
	if (file_exists("{$g['vardb_path']}/captiveportal.rules")) {
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal.rules"));
		for ($ridx = 2; $ridx < ($rulenos_range_max - $rulenos_start); $ridx++) {
			if ($rules[$ridx]) {
				/* 
	 			 * This allows our traffic shaping pipes to be the in pipe the same as ruleno 
	 			 * and the out pipe ruleno + 1. This removes limitation that where present in 
	 			 * previous version of the peruserbw.
	 			 */
				if (isset($config['captiveportal']['peruserbw']))
					$ridx++;
				continue;
			}
			$ruleno = $ridx;
			$rules[$ridx] = "used";
			if (isset($config['captiveportal']['peruserbw']) || $usebw == true)
				$rules[++$ridx] = "used";
			break;
		}
	} else {
		$rules = array_pad(array(), $rulenos_range_max - $rulenos_start, false);
		$rules[2] = "used";
		$ruleno = 2;
	}
	file_put_contents("{$g['vardb_path']}/captiveportal.rules", serialize($rules));
	return $ruleno;
}

function captiveportal_free_ipfw_ruleno($ruleno, $usedbw = false) {
	global $config, $g;

	if(!isset($config['captiveportal']['enable']))
		return NULL;

	if (file_exists("{$g['vardb_path']}/captiveportal.rules")) {
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal.rules"));
		$rules[$ruleno] = false;
		if (isset($config['captiveportal']['peruserbw']) || $usedbw == true)
			$rules[++$ruleno] = false;
		file_put_contents("{$g['vardb_path']}/captiveportal.rules", serialize($rules));
	}
}

function captiveportal_get_ipfw_passthru_ruleno($value) {
	global $config, $g;

	if(!isset($config['captiveportal']['enable']))
                return NULL;

        if (file_exists("{$g['vardb_path']}/captiveportal.rules")) {
                $rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal.rules"));
		$ruleno = intval(`/sbin/ipfw show | /usr/bin/grep {$value} |  /usr/bin/grep -v grep | /usr/bin/cut -d " " -f 1 | /usr/bin/head -n 1`);
		if ($rules[$ruleno])
			return $ruleno;
        }

	return NULL;
}

/**
 * This function will calculate the traffic produced by a client
 * based on its firewall rule
 *
 * Point of view: NAS
 *
 * Input means: from the client
 * Output means: to the client
 *
 */

function getVolume($ip) {

    $volume = array();

    // Initialize vars properly, since we don't want NULL vars
    $volume['input_pkts'] = $volume['input_bytes'] = $volume['output_pkts'] = $volume['output_bytes'] = 0 ;

    // Ingress
    $ipfwin = "";
    $ipfwout = "";
    $matchesin = "";
    $matchesout = "";
    exec("/sbin/ipfw table 1 entrystats {$ip}", $ipfwin);
    if ($ipfwin[0]) {
		$ipfwin = split(" ", $ipfwin[0]);
		$volume['input_pkts'] = $ipfwin[2];
		$volume['input_bytes'] = $ipfwin[3];
    }

    exec("/sbin/ipfw table 2 entrystats {$ip}", $ipfwout);
    if ($ipfwout[0]) {
        $ipfwout = split(" ", $ipfwout[0]);
        $volume['output_pkts'] = $ipfwout[2];
        $volume['output_bytes'] = $ipfwout[3];
    }

    return $volume;
}

/**
 * Get the NAS-Identifier
 *
 * We will use our local hostname to make up the nas_id
 */
function getNasID()
{
    $nasId = "";
    exec("/bin/hostname", $nasId);
    if(!$nasId[0])
        $nasId[0] = "{$g['product_name']}";
    return $nasId[0];
}

/**
 * Get the NAS-IP-Address based on the current wan address
 *
 * Use functions in interfaces.inc to find this out
 *
 */

function getNasIP()
{
	global $config;

	if (empty($config['captiveportal']['radiussrcip_attribute']))
    		$nasIp = get_interface_ip();
	else {
		if (is_ipaddr($config['captiveportal']['radiussrcip_attribute']))
                        $nasIp = $config['captiveportal']['radiussrcip_attribute'];
                else
                        $nasIp = get_interface_ip($config['captiveportal']['radiussrcip_attribute']);
	}
		
    	if(!is_ipaddr($nasIp))
        	$nasIp = "0.0.0.0";

	return $nasIp;
}

function portal_ip_from_client_ip($cliip) {
	global $config;

	$interfaces = explode(",", $config['captiveportal']['interface']);
	foreach ($interfaces as $cpif) {
		$ip = get_interface_ip($cpif);
		$sn = get_interface_subnet($cpif);
		if (ip_in_subnet($cliip, "{$ip}/{$sn}"))
			return $ip;
	}

	// doesn't match up to any particular interface
	// so let's set the portal IP to what PHP says 
	// the server IP issuing the request is. 
	// allows same behavior as 1.2.x where IP isn't 
	// in the subnet of any CP interface (static routes, etc.)
	// rather than forcing to DNS hostname resolution
	$ip = $_SERVER['SERVER_ADDR'];
	if (is_ipaddr($ip))
		return $ip;

	return false;
}

?>
OpenPOWER on IntegriCloud