Project

General

Profile

Download (201 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * upgrade_config.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2023 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * Licensed under the Apache License, Version 2.0 (the "License");
12
 * you may not use this file except in compliance with the License.
13
 * You may obtain a copy of the License at
14
 *
15
 * http://www.apache.org/licenses/LICENSE-2.0
16
 *
17
 * Unless required by applicable law or agreed to in writing, software
18
 * distributed under the License is distributed on an "AS IS" BASIS,
19
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
 * See the License for the specific language governing permissions and
21
 * limitations under the License.
22
 */
23

    
24
if (!function_exists("dump_rrd_to_xml")) {
25
	require_once("rrd.inc");
26
}
27
if (!function_exists("read_altq_config")) {
28
	require_once("shaper.inc");
29
}
30
if (!function_exists("console_configure")) {
31
	require_once("/etc/inc/pfsense-utils.inc");
32
}
33
if (!function_exists("get_specialnet")) {
34
	require_once("/etc/inc/util.inc");
35
}
36

    
37
/* Upgrade functions must be named:
38
 *    upgrade_XXX_to_YYY
39
 * where XXX == previous version, zero padded, and YYY == next version, zero
40
 * padded
41
 */
42
function upgrade_010_to_011() {
43
	global $config;
44
	$opti = 1;
45
	$ifmap = array('lan' => 'lan', 'wan' => 'wan', 'pptp' => 'pptp');
46

    
47
	/* convert DMZ to optional, if necessary */
48
	if (isset($config['interfaces']['dmz'])) {
49

    
50
		$dmzcfg = &$config['interfaces']['dmz'];
51

    
52
		if ($dmzcfg['if']) {
53
			$config['interfaces']['opt' . $opti] = array();
54
			$optcfg = &$config['interfaces']['opt' . $opti];
55

    
56
			$optcfg['enable'] = $dmzcfg['enable'];
57
			$optcfg['descr'] = "DMZ";
58
			$optcfg['if'] = $dmzcfg['if'];
59
			$optcfg['ipaddr'] = $dmzcfg['ipaddr'];
60
			$optcfg['subnet'] = $dmzcfg['subnet'];
61

    
62
			$ifmap['dmz'] = "opt" . $opti;
63
			$opti++;
64
		}
65

    
66
		config_del_path('interfaces/dmz');
67
	}
68

    
69
	/* convert WLAN1/2 to optional, if necessary */
70
	for ($i = 1; isset($config['interfaces']['wlan' . $i]); $i++) {
71

    
72
		if (!$config['interfaces']['wlan' . $i]['if']) {
73
			config_del_path("interfaces/wlan{$i}");
74
			continue;
75
		}
76

    
77
		$wlancfg = &$config['interfaces']['wlan' . $i];
78
		$config['interfaces']['opt' . $opti] = array();
79
		$optcfg = &$config['interfaces']['opt' . $opti];
80

    
81
		$optcfg['enable'] = $wlancfg['enable'];
82
		$optcfg['descr'] = "WLAN" . $i;
83
		$optcfg['if'] = $wlancfg['if'];
84
		$optcfg['ipaddr'] = $wlancfg['ipaddr'];
85
		$optcfg['subnet'] = $wlancfg['subnet'];
86
		$optcfg['bridge'] = $wlancfg['bridge'];
87

    
88
		$optcfg['wireless'] = array();
89
		$optcfg['wireless']['mode'] = $wlancfg['mode'];
90
		$optcfg['wireless']['ssid'] = $wlancfg['ssid'];
91
		$optcfg['wireless']['channel'] = $wlancfg['channel'];
92
		$optcfg['wireless']['wep'] = $wlancfg['wep'];
93

    
94
		$ifmap['wlan' . $i] = "opt" . $opti;
95

    
96
		config_del_path("interfaces/wlan{$i}");
97
		$opti++;
98
	}
99

    
100
	/* convert filter rules */
101
	init_config_arr(array('filter', 'rule'));
102
	$n = count($config['filter']['rule']);
103
	for ($i = 0; $i < $n; $i++) {
104

    
105
		$fr = &$config['filter']['rule'][$i];
106

    
107
		/* remap interface */
108
		if (array_key_exists($fr['interface'], $ifmap)) {
109
			$fr['interface'] = $ifmap[$fr['interface']];
110
		} else {
111
			/* remove the rule */
112
			printf(gettext("%sWarning: filter rule removed " .
113
				"(interface '%s' does not exist anymore)."), "\n", $fr['interface']);
114
			config_del_path("filter/rule/{$i}");
115
			continue;
116
		}
117

    
118
		/* remap source network */
119
		if (isset($fr['source']['network'])) {
120
			if (array_key_exists($fr['source']['network'], $ifmap)) {
121
				$fr['source']['network'] = $ifmap[$fr['source']['network']];
122
			} else {
123
				/* remove the rule */
124
				printf(gettext("%sWarning: filter rule removed " .
125
					"(source network '%s' does not exist anymore)."), "\n", $fr['source']['network']);
126
				config_del_path("filter/rule/{$i}");
127
				continue;
128
			}
129
		}
130

    
131
		/* remap destination network */
132
		if (isset($fr['destination']['network'])) {
133
			if (array_key_exists($fr['destination']['network'], $ifmap)) {
134
				$fr['destination']['network'] = $ifmap[$fr['destination']['network']];
135
			} else {
136
				/* remove the rule */
137
				printf(gettext("%sWarning: filter rule removed " .
138
					"(destination network '%s' does not exist anymore)."), "\n", $fr['destination']['network']);
139
				config_del_path("filter/rule/{$i}");
140
				continue;
141
			}
142
		}
143
	}
144

    
145
	/* convert shaper rules */
146
	init_config_arr(array('pfqueueing', 'rule'));
147
	$n = count($config['pfqueueing']['rule']);
148
	if (is_array($config['pfqueueing']['rule'])) {
149
		for ($i = 0; $i < $n; $i++) {
150

    
151
			$fr = &$config['pfqueueing']['rule'][$i];
152

    
153
			/* remap interface */
154
			if (array_key_exists($fr['interface'], $ifmap)) {
155
				$fr['interface'] = $ifmap[$fr['interface']];
156
			} else {
157
				/* remove the rule */
158
				printf(gettext("%sWarning: traffic shaper rule removed " .
159
					"(interface '%s' does not exist anymore)."), "\n", $fr['interface']);
160
				config_del_path("pfqueueing/rule/{$i}");
161
				continue;
162
			}
163

    
164
			/* remap source network */
165
			if (isset($fr['source']['network'])) {
166
				if (array_key_exists($fr['source']['network'], $ifmap)) {
167
					$fr['source']['network'] = $ifmap[$fr['source']['network']];
168
				} else {
169
					/* remove the rule */
170
					printf(gettext("%sWarning: traffic shaper rule removed " .
171
						"(source network '%s' does not exist anymore)."), "\n", $fr['source']['network']);
172
					config_del_path("pfqueueing/rule/{$i}");
173
					continue;
174
				}
175
			}
176

    
177
			/* remap destination network */
178
			if (isset($fr['destination']['network'])) {
179
				if (array_key_exists($fr['destination']['network'], $ifmap)) {
180
					$fr['destination']['network'] = $ifmap[$fr['destination']['network']];
181
				} else {
182
					/* remove the rule */
183
					printf(gettext("%sWarning: traffic shaper rule removed " .
184
						"(destination network '%s' does not exist anymore)."), "\n", $fr['destination']['network']);
185
					config_del_path("pfqueueing/rule/{$i}");
186
					continue;
187
				}
188
			}
189
		}
190
	}
191
}
192

    
193

    
194
function upgrade_011_to_012() {
195
	global $config;
196
	/* move LAN DHCP server config */
197
	$tmp = config_get_path('dhcpd');
198
	$config['dhcpd'] = array();
199
	$config['dhcpd']['lan'] = $tmp;
200

    
201
	/* encrypt password */
202
	$config['system']['password'] = crypt($config['system']['password']);
203
}
204

    
205

    
206
function upgrade_012_to_013() {
207
	global $config;
208
	/* convert advanced outbound NAT config */
209
	for ($i = 0; isset($config['nat']['advancedoutbound']['rule'][$i]); $i++) {
210
		$curent = &$config['nat']['advancedoutbound']['rule'][$i];
211
		$src = $curent['source'];
212
		$curent['source'] = array();
213
		$curent['source']['network'] = $src;
214
		$curent['destination'] = array();
215
		$curent['destination']['any'] = true;
216
	}
217

    
218
	/* add an explicit type="pass" to all filter rules to make things consistent */
219
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++) {
220
		$config['filter']['rule'][$i]['type'] = "pass";
221
	}
222
}
223

    
224

    
225
function upgrade_013_to_014() {
226
	global $config;
227
	/* convert shaper rules (make pipes) */
228
	if (is_array($config['pfqueueing']['rule'])) {
229
		init_config_arr(array('pfqueueing', 'pipe'));
230
		$config['pfqueueing']['pipe'] = array();
231

    
232
		for ($i = 0; isset($config['pfqueueing']['rule'][$i]); $i++) {
233
			$curent = &$config['pfqueueing']['rule'][$i];
234

    
235
			/* make new pipe and associate with this rule */
236
			$newpipe = array();
237
			$newpipe['descr'] = $curent['descr'];
238
			$newpipe['bandwidth'] = $curent['bandwidth'];
239
			$newpipe['delay'] = $curent['delay'];
240
			$newpipe['mask'] = $curent['mask'];
241
			$config['pfqueueing']['pipe'][$i] = $newpipe;
242

    
243
			$curent['targetpipe'] = $i;
244

    
245
			unset($curent['bandwidth']);
246
			unset($curent['delay']);
247
			unset($curent['mask']);
248
		}
249
	}
250
}
251

    
252

    
253
function upgrade_014_to_015() {
254
	global $config;
255
	/* Default route moved */
256
	if (isset($config['interfaces']['wan']['gateway'])) {
257
		if ($config['interfaces']['wan']['gateway'] <> "") {
258
			$config['system']['gateway'] = config_get_path('interfaces/wan/gateway');
259
		}
260
		config_del_path('interfaces/wan/gateway');
261
	}
262

    
263
	/* Queues are no longer interface specific */
264
	if (isset($config['interfaces']['lan']['schedulertype'])) {
265
		config_del_path('interfaces/lan/schedulertype');
266
	}
267
	if (isset($config['interfaces']['wan']['schedulertype'])) {
268
		config_del_path('interfaces/wan/schedulertype');
269
	}
270

    
271
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) {
272
		if (isset($config['interfaces']['opt' . $i]['schedulertype'])) {
273
			config_del_path("interfaces/opt{$i}/schedulertype");
274
		}
275
	}
276
}
277

    
278

    
279
function upgrade_015_to_016() {
280
	global $config;
281
	/* Alternate firmware URL moved */
282
	if (isset($config['system']['firmwareurl']) && isset($config['system']['firmwarename'])) { // Only convert if *both* are defined.
283
		$config['system']['alt_firmware_url'] = array();
284
		$config['system']['alt_firmware_url']['enabled'] = "";
285
		$config['system']['alt_firmware_url']['firmware_base_url'] = config_get_path('system/firmwareurl');
286
		$config['system']['alt_firmware_url']['firmware_filename'] = config_get_path('system/firmwarename');
287
	}
288
	if (isset($config['system']['firmwareurl'])) {
289
		config_del_path('system/firmwareurl');
290
	}
291
	if (isset($config['system']['firmwarename'])) {
292
		config_del_path('system/firmwarename');
293
	}
294
}
295

    
296

    
297
function upgrade_016_to_017() {
298
	global $config;
299
	/* wipe previous shaper configuration */
300
	if (isset($config['shaper']['queue'])) {
301
		config_del_path('shaper/queue');
302
	}
303
	if (isset($config['shaper']['rule'])) {
304
		config_del_path('shaper/rule');
305
	}
306
	if (isset($config['interfaces']['wan']['bandwidth'])) {
307
		config_del_path('interfaces/wan/bandwidth');
308
	}
309
	if (isset($config['interfaces']['wan']['bandwidthtype'])) {
310
		config_del_path('interfaces/wan/bandwidthtype');
311
	}
312
	if (isset($config['interfaces']['lan']['bandwidth'])) {
313
		config_del_path('interfaces/lan/bandwidth');
314
	}
315
	if (isset($config['interfaces']['lan']['bandwidthtype'])) {
316
		config_del_path('interfaces/lan/bandwidthtype');
317
	}
318
	$config['shaper']['enable'] = FALSE;
319
}
320

    
321

    
322
function upgrade_017_to_018() {
323
	global $config;
324
	if (isset($config['proxyarp']) && is_array($config['proxyarp']['proxyarpnet'])) {
325
		$proxyarp = &$config['proxyarp']['proxyarpnet'];
326
		foreach ($proxyarp as $arpent) {
327
			$vip = array();
328
			$vip['mode'] = "proxyarp";
329
			$vip['interface'] = $arpent['interface'];
330
			$vip['descr'] = $arpent['descr'];
331
			if (isset($arpent['range'])) {
332
				$vip['range'] = $arpent['range'];
333
				$vip['type'] = "range";
334
			} else {
335
				$subnet = explode('/', $arpent['network']);
336
				$vip['subnet'] = $subnet[0];
337
				if (isset($subnet[1])) {
338
					$vip['subnet_bits'] = $subnet[1];
339
					$vip['type'] = "network";
340
				} else {
341
					$vip['subnet_bits'] = "32";
342
					$vip['type'] = "single";
343
				}
344
			}
345
			$config['virtualip']['vip'][] = $vip;
346
		}
347
		config_del_path('proxyarp');
348
	}
349
	if (isset($config['installedpackages']) && isset($config['installedpackages']['carp']) && is_array($config['installedpackages']['carp']['config'])) {
350
		$carp = &$config['installedpackages']['carp']['config'];
351
		foreach ($carp as $carpent) {
352
			$vip = array();
353
			$vip['mode'] = "carp";
354
			$vip['interface'] = "AUTO";
355
			$vip['descr'] = sprintf(gettext("CARP vhid %s"), $carpent['vhid']);
356
			$vip['type'] = "single";
357
			$vip['vhid'] = $carpent['vhid'];
358
			$vip['advskew'] = $carpent['advskew'];
359
			$vip['password'] = $carpent['password'];
360
			$vip['subnet'] = $carpent['ipaddress'];
361
			$vip['subnet_bits'] = $carpent['netmask'];
362
			$config['virtualip']['vip'][] = $vip;
363
		}
364
		config_del_path('installedpackages/carp');
365
	}
366
	/* Server NAT is no longer needed */
367
	if (isset($config['nat']['servernat'])) {
368
		config_del_path('nat/servernat');
369
	}
370

    
371
	/* enable SSH */
372
	if ($config['version'] == "1.8") {
373
		$config['system']['sshenabled'] = true;
374
	}
375
}
376

    
377

    
378
function upgrade_018_to_019() {
379
	global $config;
380
}
381

    
382

    
383
function upgrade_019_to_020() {
384
	global $config;
385
	if (is_array($config['ipsec']['tunnel'])) {
386
		reset($config['ipsec']['tunnel']);
387
		while (list($index, $tunnel) = each($config['ipsec']['tunnel'])) {
388
			/* Sanity check on required variables */
389
			/* This fixes bogus <tunnel> entries - remnant of bug #393 */
390
			if (!isset($tunnel['local-subnet']) && !isset($tunnel['remote-subnet'])) {
391
				config_del_path("ipsec/tunnel/{$tunnel}");
392
			}
393
		}
394
	}
395
}
396

    
397
function upgrade_020_to_021() {
398
	global $config;
399
	/* shaper scheduler moved */
400
	if (isset($config['system']['schedulertype'])) {
401
		$config['shaper']['schedulertype'] = config_get_path('system/schedulertype');
402
		config_del_path('system/schedulertype');
403
	}
404
}
405

    
406

    
407
function upgrade_021_to_022() {
408
	global $config;
409
	/* move gateway to wan interface */
410
	$config['interfaces']['wan']['gateway'] = config_get_path('system/gateway');
411
}
412

    
413
function upgrade_022_to_023() {
414
	global $config;
415
	if (isset($config['shaper'])) {
416
		config_del_path('shaper');
417
	}
418
}
419

    
420

    
421
function upgrade_023_to_024() {
422
	global $config;
423
}
424

    
425

    
426
function upgrade_024_to_025() {
427
	global $config;
428
	$config['interfaces']['wan']['use_rrd_gateway'] = config_get_path('system/use_rrd_gateway');
429
	if (isset($config['system']['use_rrd_gateway'])) {
430
		config_del_path('system/use_rrd_gateway');
431
	}
432
}
433

    
434

    
435
function upgrade_025_to_026() {
436
	global $config;
437
	$cron_item = array();
438
	$cron_item['minute'] = "0";
439
	$cron_item['hour'] = "*";
440
	$cron_item['mday'] = "*";
441
	$cron_item['month'] = "*";
442
	$cron_item['wday'] = "*";
443
	$cron_item['who'] = "root";
444
	$cron_item['command'] = "/usr/bin/nice -n20 newsyslog";
445

    
446
	$config['cron']['item'][] = $cron_item;
447

    
448
	$cron_item = array();
449
	$cron_item['minute'] = "1,31";
450
	$cron_item['hour'] = "0-5";
451
	$cron_item['mday'] = "*";
452
	$cron_item['month'] = "*";
453
	$cron_item['wday'] = "*";
454
	$cron_item['who'] = "root";
455
	$cron_item['command'] = "/usr/bin/nice -n20 adjkerntz -a";
456

    
457
	$config['cron']['item'][] = $cron_item;
458

    
459
	$cron_item = array();
460
	$cron_item['minute'] = "1";
461
	$cron_item['hour'] = "*";
462
	$cron_item['mday'] = "1";
463
	$cron_item['month'] = "*";
464
	$cron_item['wday'] = "*";
465
	$cron_item['who'] = "root";
466
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.update_bogons.sh";
467

    
468
	$config['cron']['item'][] = $cron_item;
469

    
470
	$cron_item = array();
471
	$cron_item['minute'] = "*/60";
472
	$cron_item['hour'] = "*";
473
	$cron_item['mday'] = "*";
474
	$cron_item['month'] = "*";
475
	$cron_item['wday'] = "*";
476
	$cron_item['who'] = "root";
477
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard";
478

    
479
	$config['cron']['item'][] = $cron_item;
480

    
481
	$cron_item = array();
482
	$cron_item['minute'] = "1";
483
	$cron_item['hour'] = "1";
484
	$cron_item['mday'] = "*";
485
	$cron_item['month'] = "*";
486
	$cron_item['wday'] = "*";
487
	$cron_item['who'] = "root";
488
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.dyndns.update";
489

    
490
	$config['cron']['item'][] = $cron_item;
491

    
492
	$cron_item = array();
493
	$cron_item['minute'] = "*/60";
494
	$cron_item['hour'] = "*";
495
	$cron_item['mday'] = "*";
496
	$cron_item['month'] = "*";
497
	$cron_item['wday'] = "*";
498
	$cron_item['who'] = "root";
499
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 virusprot";
500

    
501
	$config['cron']['item'][] = $cron_item;
502

    
503
	$cron_item = array();
504
	$cron_item['minute'] = "*/60";
505
	$cron_item['hour'] = "*";
506
	$cron_item['mday'] = "*";
507
	$cron_item['month'] = "*";
508
	$cron_item['wday'] = "*";
509
	$cron_item['who'] = "root";
510
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -t 1800 snort2c";
511

    
512
	$config['cron']['item'][] = $cron_item;
513
}
514

    
515

    
516
function upgrade_026_to_027() {
517
	global $config;
518
}
519

    
520

    
521
function upgrade_027_to_028() {
522
	global $config;
523
}
524

    
525

    
526
function upgrade_028_to_029() {
527
	global $config;
528
	init_config_arr(array('filter', 'rule'));
529
	$a_filter = &$config['filter']['rule'];
530
	$rule_item = array();
531
	$rule_item['interface'] = "enc0";
532
	$rule_item['type'] = "pass";
533
	$rule_item['source']['any'] = true;
534
	$rule_item['destination']['any'] = true;
535
	$rule_item['descr'] = gettext("Permit IPsec traffic.");
536
	$rule_item['statetype'] = "keep state";
537
	$a_filter[] = $rule_item;
538
}
539

    
540

    
541
function upgrade_029_to_030() {
542
	global $config;
543
	/* enable the rrd config setting by default */
544
	$config['rrd']['enable'] = true;
545
}
546

    
547

    
548
function upgrade_030_to_031() {
549
	global $config;
550
	/* Insert upgrade code here */
551
}
552

    
553

    
554
function upgrade_031_to_032() {
555
	global $config;
556
	/* Insert upgrade code here */
557
}
558

    
559

    
560
function upgrade_032_to_033() {
561
	global $config;
562
	/* Insert upgrade code here */
563
}
564

    
565

    
566
function upgrade_033_to_034() {
567
	global $config;
568
	/* Insert upgrade code here */
569
}
570

    
571

    
572
function upgrade_034_to_035() {
573
	global $config;
574
	/* Insert upgrade code here */
575
}
576

    
577

    
578
function upgrade_035_to_036() {
579
	global $config;
580
	/* Insert upgrade code here */
581
}
582

    
583

    
584
function upgrade_036_to_037() {
585
	global $config;
586
	/* Insert upgrade code here */
587
}
588

    
589

    
590
function upgrade_037_to_038() {
591
	global $config;
592
	/* Insert upgrade code here */
593
}
594

    
595

    
596
function upgrade_038_to_039() {
597
	global $config;
598
	/* Insert upgrade code here */
599
}
600

    
601

    
602
function upgrade_039_to_040() {
603
	global $config, $g;
604
	$config['system']['webgui']['auth_method'] = "session";
605
	$config['system']['webgui']['backing_method'] = "htpasswd";
606

    
607
	if (isset($config['system']['username'])) {
608
		$config['system']['group'] = array();
609
		$config['system']['group'][0]['name'] = "admins";
610
		$config['system']['group'][0]['description'] = gettext("System Administrators");
611
		$config['system']['group'][0]['scope'] = "system";
612
		$config['system']['group'][0]['priv'] = "page-all";
613
		$config['system']['group'][0]['home'] = "index.php";
614
		$config['system']['group'][0]['gid'] = "110";
615

    
616
		$config['system']['user'] = array();
617
		$config['system']['user'][0]['name'] = "{$config['system']['username']}";
618
		$config['system']['user'][0]['descr'] = "System Administrator";
619
		$config['system']['user'][0]['scope'] = "system";
620
		$config['system']['user'][0]['groupname'] = "admins";
621
		$config['system']['user'][0]['password'] = "{$config['system']['password']}";
622
		$config['system']['user'][0]['uid'] = "0";
623
		/* Ensure that we follow what this new "admin" username should be in the session. */
624
		$_SESSION["Username"] = "{$config['system']['username']}";
625

    
626
		$config['system']['user'][0]['priv'] = array();
627
		$config['system']['user'][0]['priv'][0]['id'] = "lockwc";
628
		$config['system']['user'][0]['priv'][0]['name'] = "Lock webConfigurator";
629
		$config['system']['user'][0]['priv'][0]['descr'] = gettext("Indicates whether this user will lock access to the webConfigurator for other users.");
630
		$config['system']['user'][0]['priv'][1]['id'] = "lock-ipages";
631
		$config['system']['user'][0]['priv'][1]['name'] = "Lock individual pages";
632
		$config['system']['user'][0]['priv'][1]['descr'] = gettext("Indicates whether this user will lock individual HTML pages after having accessed a particular page (the lock will be freed if the user leaves or saves the page form).");
633
		$config['system']['user'][0]['priv'][2]['id'] = "hasshell";
634
		$config['system']['user'][0]['priv'][2]['name'] = "Has shell access";
635
		$config['system']['user'][0]['priv'][2]['descr'] = gettext("Indicates whether this user is able to login for example via SSH.");
636
		$config['system']['user'][0]['priv'][3]['id'] = "copyfiles";
637
		$config['system']['user'][0]['priv'][3]['name'] = "Is allowed to copy files";
638
		$config['system']['user'][0]['priv'][3]['descr'] = sprintf(gettext("Indicates whether this user is allowed to copy files onto the %s appliance via SCP/SFTP."), g_get('product_label'));
639
		$config['system']['user'][0]['priv'][4]['id'] = "isroot";
640
		$config['system']['user'][0]['priv'][4]['name'] = "Is root user";
641
		$config['system']['user'][0]['priv'][4]['descr'] = gettext("This user is associated with the UNIX root user (this privilege should only be associated with one single user).");
642

    
643
		$config['system']['nextuid'] = "111";
644
		$config['system']['nextgid'] = "111";
645

    
646
		config_del_path('system/username');
647
		if (isset($config['system']['password'])) {
648
			config_del_path('system/password');
649
		}
650
	}
651
}
652

    
653
function upgrade_040_to_041() {
654
	global $config;
655
	if (!$config['sysctl']) {
656
		$config['sysctl']['item'] = array();
657

    
658
		$config['sysctl']['item'][0]['tunable'] = "net.inet.tcp.blackhole";
659
		$config['sysctl']['item'][0]['descr'] =    gettext("Drop packets to closed TCP ports without returning a RST");
660
		$config['sysctl']['item'][0]['value'] =   "default";
661

    
662
		$config['sysctl']['item'][1]['tunable'] = "net.inet.udp.blackhole";
663
		$config['sysctl']['item'][1]['descr'] =    gettext("Do not send ICMP port unreachable messages for closed UDP ports");
664
		$config['sysctl']['item'][1]['value'] =   "default";
665

    
666
		$config['sysctl']['item'][2]['tunable'] = "net.inet.ip.random_id";
667
		$config['sysctl']['item'][2]['descr'] =    gettext("Randomize the ID field in IP packets (default is 1: Assign random IP IDs)");
668
		$config['sysctl']['item'][2]['value'] =   "default";
669

    
670
		$config['sysctl']['item'][3]['tunable'] = "net.inet.tcp.drop_synfin";
671
		$config['sysctl']['item'][3]['descr'] =    gettext("Drop SYN-FIN packets (breaks RFC1379, but nobody uses it anyway)");
672
		$config['sysctl']['item'][3]['value'] =   "default";
673

    
674
		$config['sysctl']['item'][4]['tunable'] = "net.inet.ip.redirect";
675
		$config['sysctl']['item'][4]['descr'] =    gettext("Sending of IPv4 ICMP redirects");
676
		$config['sysctl']['item'][4]['value'] =   "default";
677

    
678
		$config['sysctl']['item'][5]['tunable'] = "net.inet6.ip6.redirect";
679
		$config['sysctl']['item'][5]['descr'] =    gettext("Sending of IPv6 ICMP redirects");
680
		$config['sysctl']['item'][5]['value'] =   "default";
681

    
682
		$config['sysctl']['item'][6]['tunable'] = "net.inet.tcp.syncookies";
683
		$config['sysctl']['item'][6]['descr'] =    gettext("Generate SYN cookies for outbound SYN-ACK packets");
684
		$config['sysctl']['item'][6]['value'] =   "default";
685

    
686
		$config['sysctl']['item'][7]['tunable'] = "net.inet.tcp.recvspace";
687
		$config['sysctl']['item'][7]['descr'] =    gettext("Maximum incoming TCP datagram size");
688
		$config['sysctl']['item'][7]['value'] =   "default";
689

    
690
		$config['sysctl']['item'][8]['tunable'] = "net.inet.tcp.sendspace";
691
		$config['sysctl']['item'][8]['descr'] =    gettext("Maximum outgoing TCP datagram size");
692
		$config['sysctl']['item'][8]['value'] =   "default";
693

    
694
		$config['sysctl']['item'][9]['tunable'] = "net.inet.tcp.delayed_ack";
695
		$config['sysctl']['item'][9]['descr'] =    gettext("Do not delay ACK to try and piggyback it onto a data packet");
696
		$config['sysctl']['item'][9]['value'] =   "default";
697

    
698
		$config['sysctl']['item'][10]['tunable'] = "net.inet.udp.maxdgram";
699
		$config['sysctl']['item'][10]['descr'] =    gettext("Maximum outgoing UDP datagram size");
700
		$config['sysctl']['item'][10]['value'] =   "default";
701

    
702
		$config['sysctl']['item'][11]['tunable'] = "net.link.bridge.pfil_onlyip";
703
		$config['sysctl']['item'][11]['descr'] =    gettext("Handling of non-IP packets which are not passed to pfil (see if_bridge(4))");
704
		$config['sysctl']['item'][11]['value'] =   "default";
705

    
706
		$config['sysctl']['item'][12]['tunable'] = "net.link.tap.user_open";
707
		$config['sysctl']['item'][12]['descr'] =    gettext("Allow unprivileged access to tap(4) device nodes");
708
		$config['sysctl']['item'][12]['value'] =   "default";
709

    
710
		$config['sysctl']['item'][13]['tunable'] = "kern.randompid";
711
		$config['sysctl']['item'][13]['descr'] =    gettext("Randomize PID's (see src/sys/kern/kern_fork.c: sysctl_kern_randompid())");
712
		$config['sysctl']['item'][13]['value'] =   "default";
713

    
714
		$config['sysctl']['item'][14]['tunable'] = "net.inet.tcp.inflight.enable";
715
		$config['sysctl']['item'][14]['descr'] =    gettext("The system will attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput. ");
716
		$config['sysctl']['item'][14]['value'] =   "default";
717

    
718
		$config['sysctl']['item'][15]['tunable'] = "net.inet.icmp.icmplim";
719
		$config['sysctl']['item'][15]['descr'] =    gettext("Set ICMP Limits");
720
		$config['sysctl']['item'][15]['value'] =   "default";
721

    
722
		$config['sysctl']['item'][16]['tunable'] = "net.inet.tcp.tso";
723
		$config['sysctl']['item'][16]['descr'] =    gettext("TCP Offload engine");
724
		$config['sysctl']['item'][16]['value'] =   "default";
725

    
726
		$config['sysctl']['item'][17]['tunable'] = "net.inet.ip.portrange.first";
727
		$config['sysctl']['item'][17]['descr'] =    "Set the ephemeral port range starting port";
728
		$config['sysctl']['item'][17]['value'] =   "default";
729

    
730
		$config['sysctl']['item'][18]['tunable'] = "hw.syscons.kbd_reboot";
731
		$config['sysctl']['item'][18]['descr'] =    "Enables ctrl+alt+delete";
732
		$config['sysctl']['item'][18]['value'] =   "default";
733

    
734
		$config['sysctl']['item'][19]['tunable'] = "kern.ipc.maxsockbuf";
735
		$config['sysctl']['item'][19]['descr'] =    "Maximum socket buffer size";
736
		$config['sysctl']['item'][19]['value'] =   "default";
737

    
738
	}
739
}
740

    
741

    
742
function upgrade_041_to_042() {
743
	global $config;
744
	if (isset($config['shaper'])) {
745
		config_del_path('shaper');
746
	}
747
	if (isset($config['ezshaper'])) {
748
		config_del_path('ezshaper');
749
	}
750
}
751

    
752

    
753
function upgrade_042_to_043() {
754
	global $config;
755
	/* migrate old interface gateway to the new gateways config */
756
	$iflist = get_configured_interface_list(true);
757
	$gateways = array();
758
	$i = 0;
759
	foreach ($iflist as $ifname => $interface) {
760
		if (!interface_has_gateway($ifname)) {
761
			continue;
762
		}
763
		$config['gateways']['gateway_item'][$i] = array();
764
		if (is_ipaddr($config['interfaces'][$ifname]['gateway'])) {
765
			$config['gateways']['gateway_item'][$i]['gateway'] = config_get_path("interfaces/{$ifname}/gateway");
766
			$config['gateways']['gateway_item'][$i]['descr'] = sprintf(gettext("Interface %s Static Gateway"), $ifname);
767
		} else {
768
			$config['gateways']['gateway_item'][$i]['gateway'] = "dynamic";
769
			$config['gateways']['gateway_item'][$i]['descr'] = sprintf(gettext("Interface %s Dynamic Gateway"), $ifname);
770
		}
771
		$config['gateways']['gateway_item'][$i]['interface'] = $ifname;
772
		$config['gateways']['gateway_item'][$i]['name'] = "GW_" . strtoupper($ifname);
773
		/* add default gateway bit for wan on upgrade */
774
		if ($ifname == "wan") {
775
			$config['gateways']['gateway_item'][$i]['defaultgw'] = true;
776
		}
777
		if (is_ipaddr($config['interfaces'][$ifname]['use_rrd_gateway'])) {
778
			$config['gateways']['gateway_item'][$i]['monitor'] = config_get_path("interfaces/{$ifname}/use_rrd_gateway");
779
			config_del_path("interfaces/{$ifname}/use_rrd_gateway");
780
		}
781
		$config['interfaces'][$ifname]['gateway'] = config_get_path("gateways/gateway_item/{$i}/name");
782

    
783
		/* Update all filter rules which might reference this gateway */
784
		$j = 0;
785
		foreach ($config['filter']['rule'] as $rule) {
786
			if (is_ipaddr($rule['gateway'])) {
787
				if ($rule['gateway'] == $config['gateways']['gateway_item'][$i]['gateway']) {
788
					$config['filter']['rule'][$j]['gateway'] = config_get_path("gateways/gateway_item/{$i}/name");
789
				} else if ($rule['gateway'] == $ifname) {
790
					$config['filter']['rule'][$j]['gateway'] = config_get_path("gateways/gateway_item/{$i}/name");
791
				}
792
			}
793
			$j++;
794
		}
795

    
796
		/* rename old Quality RRD files in the process */
797
		$rrddbpath = "/var/db/rrd";
798
		$gwname = "GW_" . strtoupper($ifname);
799
		if (is_readable("{$rrddbpath}/{$ifname}-quality.rrd")) {
800
			rename("{$rrddbpath}/{$ifname}-quality.rrd", "{$rrddbpath}/{$gwname}-quality.rrd");
801
		}
802
		$i++;
803
	}
804
}
805

    
806

    
807
function upgrade_043_to_044() {
808
	global $config;
809

    
810
	/* migrate static routes to the new gateways config */
811
	$gateways = return_gateways_array(true);
812
	$i = 0;
813
	if (is_array($config['staticroutes']['route'])) {
814
		$gwmap = array();
815
		foreach ($config['staticroutes']['route'] as $idx => $sroute) {
816
			$found = false;
817
			foreach ($gateways as $gwname => $gw) {
818
				if ($gw['gateway'] == $sroute['gateway']) {
819
					$config['staticroutes']['route'][$idx]['gateway'] = $gwname;
820
					$found = true;
821
					break;
822
				}
823
			}
824
			if ($gwmap[$sroute['gateway']]) {
825
				/* We already added a gateway name for this IP */
826
				$config['staticroutes']['route'][$idx]['gateway'] = "{$gwmap[$sroute['gateway']]}";
827
				$found = true;
828
			}
829

    
830
			if ($found == false) {
831
				$gateway = array();
832
				$gateway['name'] = "SROUTE{$i}";
833
				$gwmap[$sroute['gateway']] = $gateway['name'];
834
				$gateway['gateway'] = $sroute['gateway'];
835
				$gateway['interface'] = $sroute['interface'];
836
				$gateway['descr'] = sprintf(gettext("Upgraded static route for %s"), $sroute['network']);
837
				if (!is_array($config['gateways']['gateway_item'])) {
838
					$config['gateways']['gateway_item'] = array();
839
				}
840
				$config['gateways']['gateway_item'][] = $gateway;
841
				$config['staticroutes']['route'][$idx]['gateway'] = $gateway['name'];
842
				$i++;
843
			}
844
		}
845
	}
846
}
847

    
848

    
849
function upgrade_044_to_045() {
850
	global $config;
851
	$iflist = get_configured_interface_list(true);
852
	if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
853
		$i = 0;
854
		foreach ($config['vlans']['vlan'] as $id => $vlan) {
855
			/* Make sure to update the interfaces section with the right name */
856
			$vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}";
857
			foreach ($iflist as $ifname) {
858
				if ($config['interfaces'][$ifname]['if'] == "vlan{$i}") {
859
					$config['interfaces'][$ifname]['if'] = $vlan_name;
860
					continue;
861
				}
862
			}
863
			$config['vlans']['vlan'][$i]['vlanif'] = "{$vlan_name}";
864
			$i++;
865
		}
866
	}
867
}
868

    
869

    
870
function upgrade_045_to_046() {
871
	global $config;
872
	/* Load up monitors that are in the default config for 2.0 but not in 1.2.3
873
		thus wouldn't be in an upgraded config. */
874
	$config['load_balancer']['monitor_type'] = array (
875
		array ('name' => 'ICMP',
876
			'type' => 'icmp',
877
			'descr' => 'ICMP',
878
			'options' => '',
879
		),
880
		array ('name' => 'TCP',
881
			'type' => 'tcp',
882
			'descr' => 'Generic TCP',
883
			'options' => '',
884
		),
885
		array ('name' => 'HTTP',
886
			'type' => 'http',
887
			'descr' => 'Generic HTTP',
888
			'options' =>
889
			array ('path' => '/',
890
				'host' => '',
891
				'code' => '200',
892
			),
893
		),
894
		array ('name' => 'HTTPS',
895
			'type' => 'https',
896
			'descr' => 'Generic HTTPS',
897
			'options' =>
898
			array ('path' => '/',
899
				'host' => '',
900
				'code' => '200',
901
			),
902
		),
903
		array ('name' => 'SMTP',
904
			'type' => 'send',
905
			'descr' => 'Generic SMTP',
906
			'options' =>
907
			array ('send' => '',
908
				'expect' => '220 *',
909
			),
910
		),
911
	);
912
	/* Upgrade load balancer from slb to relayd */
913
	if (is_array($config['load_balancer']['virtual_server']) && count($config['load_balancer']['virtual_server'])) {
914
		$vs_a = &$config['load_balancer']['virtual_server'];
915
		init_config_arr(array('load_balancer', 'lbpool'));
916
		$pool_a = &$config['load_balancer']['lbpool'];
917
		$pools = array();
918
		/* Index pools by name */
919
		if (is_array($pool_a)) {
920
			for ($i = 0; isset($pool_a[$i]); $i++) {
921
				if ($pool_a[$i]['type'] == "server") {
922
					$pools[$pool_a[$i]['name']] = $pool_a[$i];
923
				}
924
			}
925
		}
926
		/* Convert sitedown entries to pools and re-attach */
927
		for ($i = 0; isset($vs_a[$i]); $i++) {
928
			/* Set mode while we're here. */
929
			$vs_a[$i]['mode'] = "redirect_mode";
930
			if (isset($vs_a[$i]['sitedown'])) {
931
				$pool = array();
932
				$pool['type'] = 'server';
933
				$pool['behaviour'] = 'balance';
934
				$pool['name'] = "{$vs_a[$i]['name']}-sitedown";
935
				$pool['descr'] = sprintf(gettext("Sitedown pool for VS: %s"), $vs_a[$i]['name']);
936
				if (is_array($vs_a[$i]['pool'])) {
937
					$vs_a[$i]['pool'] = $vs_a[$i]['pool'][0];
938
				}
939
				$pool['port'] = $pools[$vs_a[$i]['pool']]['port'];
940
				$pool['servers'] = array();
941
				$pool['servers'][] = $vs_a[$i]['sitedown'];
942
				$pool['monitor'] = $pools[$vs_a[$i]['pool']]['monitor'];
943
				$pool_a[] = $pool;
944
				$vs_a[$i]['sitedown'] = $pool['name'];
945
			}
946
		}
947
	}
948
	if (count($config['load_balancer']) == 0) {
949
		config_del_path('load_balancer');
950
	}
951
}
952

    
953

    
954
function upgrade_046_to_047() {
955
	global $config;
956
	/* Upgrade IPsec from tunnel to phase1/phase2 */
957

    
958
	if (is_array($config['ipsec']['tunnel'])) {
959

    
960
		$a_phase1 = array();
961
		$a_phase2 = array();
962
		$ikeid = 0;
963

    
964
		foreach ($config['ipsec']['tunnel'] as $tunnel) {
965

    
966
			unset($ph1ent);
967
			unset($ph2ent);
968

    
969
			/*
970
				*  attempt to locate an enabled phase1
971
				*  entry that matches the peer gateway
972
				*/
973

    
974
			if (!isset($tunnel['disabled'])) {
975

    
976
				$remote_gateway = $tunnel['remote-gateway'];
977

    
978
				foreach ($a_phase1 as $ph1tmp) {
979
					if ($ph1tmp['remote-gateway'] == $remote_gateway) {
980
						$ph1ent = $ph1tmp;
981
						break;
982
					}
983
				}
984
			}
985

    
986
			/* none found, create a new one */
987

    
988
			if (!isset($ph1ent)) {
989

    
990
				/* build new phase1 entry */
991

    
992
				$ph1ent = array();
993

    
994
				$ph1ent['ikeid'] = ++$ikeid;
995

    
996
				if (isset($tunnel['disabled'])) {
997
					$ph1ent['disabled'] = $tunnel['disabled'];
998
				}
999

    
1000
				/* convert to the new vip[$vhid] name */
1001
				if (preg_match("/^carp/", $tunnel['interface'])) {
1002
					$carpid = str_replace("carp", "", $tunnel['interface']);
1003
					$tunnel['interface'] = "vip" . $config['virtualip']['vip'][$carpid]['vhid'];
1004
				}
1005
				$ph1ent['interface'] = $tunnel['interface'];
1006
				$ph1ent['remote-gateway'] = $tunnel['remote-gateway'];
1007
				$ph1ent['descr'] = $tunnel['descr'];
1008

    
1009
				$ph1ent['mode'] = $tunnel['p1']['mode'];
1010

    
1011
				if (isset($tunnel['p1']['myident']['myaddress'])) {
1012
					$ph1ent['myid_type'] = "myaddress";
1013
				}
1014
				if (isset($tunnel['p1']['myident']['address'])) {
1015
					$ph1ent['myid_type'] = "address";
1016
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['address'];
1017
				}
1018
				if (isset($tunnel['p1']['myident']['fqdn'])) {
1019
					$ph1ent['myid_type'] = "fqdn";
1020
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['fqdn'];
1021
				}
1022
				if (isset($tunnel['p1']['myident']['ufqdn'])) {
1023
					$ph1ent['myid_type'] = "user_fqdn";
1024
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['ufqdn'];
1025
				}
1026
				if (isset($tunnel['p1']['myident']['asn1dn'])) {
1027
					$ph1ent['myid_type'] = "asn1dn";
1028
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['asn1dn'];
1029
				}
1030
				if (isset($tunnel['p1']['myident']['dyn_dns'])) {
1031
					$ph1ent['myid_type'] = "dyn_dns";
1032
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['dyn_dns'];
1033
				}
1034

    
1035
				$ph1ent['peerid_type'] = "peeraddress";
1036

    
1037
				switch ($tunnel['p1']['encryption-algorithm']) {
1038
					case "des":
1039
						$ph1alg = array('name' => 'des');
1040
						break;
1041
					case "3des":
1042
						$ph1alg = array('name' => '3des');
1043
						break;
1044
					case "blowfish":
1045
						$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1046
						break;
1047
					case "cast128":
1048
						$ph1alg = array('name' => 'cast128');
1049
						break;
1050
					case "rijndael":
1051
						$ph1alg = array('name' => 'aes', 'keylen' => '128');
1052
						break;
1053
					case "rijndael 256":
1054
					case "aes 256":
1055
						$ph1alg = array('name' => 'aes', 'keylen' => '256');
1056
						break;
1057
				}
1058

    
1059
				$ph1ent['encryption-algorithm'] = $ph1alg;
1060
				$ph1ent['hash-algorithm'] = $tunnel['p1']['hash-algorithm'];
1061
				$ph1ent['dhgroup'] = $tunnel['p1']['dhgroup'];
1062
				$ph1ent['lifetime'] = $tunnel['p1']['lifetime'];
1063
				$ph1ent['authentication_method'] = $tunnel['p1']['authentication_method'];
1064

    
1065
				if (isset($tunnel['p1']['pre-shared-key'])) {
1066
					$ph1ent['pre-shared-key'] = $tunnel['p1']['pre-shared-key'];
1067
				}
1068
				if (isset($tunnel['p1']['cert'])) {
1069
					$ph1ent['cert'] = $tunnel['p1']['cert'];
1070
				}
1071
				if (isset($tunnel['p1']['peercert'])) {
1072
					$ph1ent['peercert'] = $tunnel['p1']['peercert'];
1073
				}
1074
				if (isset($tunnel['p1']['private-key'])) {
1075
					$ph1ent['private-key'] = $tunnel['p1']['private-key'];
1076
				}
1077

    
1078
				$ph1ent['nat_traversal'] = "on";
1079
				$ph1ent['dpd_enable'] = 1;
1080
				$ph1ent['dpd_delay'] = 10;
1081
				$ph1ent['dpd_maxfail'] = 5;
1082

    
1083
				$a_phase1[] = $ph1ent;
1084
			}
1085

    
1086
			/* build new phase2 entry */
1087

    
1088
			$ph2ent = array();
1089

    
1090
			$ph2ent['ikeid'] = $ph1ent['ikeid'];
1091

    
1092
			if (isset($tunnel['disabled'])) {
1093
				$ph1ent['disabled'] = $tunnel['disabled'];
1094
			}
1095

    
1096
			$ph2ent['descr'] = sprintf(gettext("phase2 for %s"), $tunnel['descr']);
1097

    
1098
			$type = "lan";
1099
			if ($tunnel['local-subnet']['network']) {
1100
				$type = $tunnel['local-subnet']['network'];
1101
			}
1102
			if ($tunnel['local-subnet']['address']) {
1103
				list($address, $netbits) = explode("/", $tunnel['local-subnet']['address']);
1104
				if (is_null($netbits)) {
1105
					$type = "address";
1106
				} else {
1107
					$type = "network";
1108
				}
1109
			}
1110

    
1111
			switch ($type) {
1112
				case "address":
1113
					$ph2ent['localid'] = array('type' => $type, 'address' => $address);
1114
					break;
1115
				case "network":
1116
					$ph2ent['localid'] = array('type' => $type, 'address' => $address, 'netbits' => $netbits);
1117
					break;
1118
				default:
1119
					$ph2ent['localid'] = array('type' => $type);
1120
					break;
1121
			}
1122

    
1123
			list($address, $netbits) = explode("/", $tunnel['remote-subnet']);
1124
			$ph2ent['remoteid'] = array('type' => 'network', 'address' => $address, 'netbits' => $netbits);
1125

    
1126
			$ph2ent['protocol'] = $tunnel['p2']['protocol'];
1127

    
1128
			$aes_count = 0;
1129
			foreach ($tunnel['p2']['encryption-algorithm-option'] as $tunalg) {
1130
				$aes_found = false;
1131
				switch ($tunalg) {
1132
					case "des":
1133
						$ph2alg = array('name' => 'des');
1134
						break;
1135
					case "3des":
1136
						$ph2alg = array('name' => '3des');
1137
						break;
1138
					case "blowfish":
1139
						$ph2alg = array('name' => 'blowfish', 'keylen' => 'auto');
1140
						break;
1141
					case "cast128":
1142
						$ph2alg = array('name' => 'cast128');
1143
						break;
1144
					case "rijndael":
1145
					case "rijndael 256":
1146
					case "aes 256":
1147
						$ph2alg = array('name' => 'aes', 'keylen' => 'auto');
1148
						$aes_found = true;
1149
						$aes_count++;
1150
						break;
1151
				}
1152

    
1153
				if (!$aes_found || ($aes_count < 2)) {
1154
					$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1155
				}
1156
			}
1157

    
1158
			$ph2ent['hash-algorithm-option'] = $tunnel['p2']['hash-algorithm-option'];
1159
			$ph2ent['pfsgroup'] = $tunnel['p2']['pfsgroup'];
1160
			$ph2ent['lifetime'] = $tunnel['p2']['lifetime'];
1161

    
1162
			if (isset($tunnel['pinghost']['pinghost'])) {
1163
				$ph2ent['pinghost'] = $tunnel['pinghost'];
1164
			}
1165

    
1166
			$a_phase2[] = $ph2ent;
1167
		}
1168

    
1169
		config_del_path('ipsec/tunnel');
1170
		$config['ipsec']['phase1'] = $a_phase1;
1171
		$config['ipsec']['phase2'] = $a_phase2;
1172
	}
1173

    
1174
	/* Upgrade Mobile IPsec */
1175
	if (isset($config['ipsec']['mobileclients']) &&
1176
	    is_array($config['ipsec']['mobileclients']) &&
1177
	    is_array($config['ipsec']['mobileclients']['p1']) &&
1178
	    is_array($config['ipsec']['mobileclients']['p2'])) {
1179

    
1180
		if (isset($config['ipsec']['mobileclients']['enable'])) {
1181
			$config['ipsec']['client']['enable'] = true;
1182
			$config['ipsec']['client']['user_source'] = 'system';
1183
			$config['ipsec']['client']['group_source'] = 'system';
1184
		}
1185

    
1186
		$mobilecfg = config_get_path('ipsec/mobileclients');
1187

    
1188
		$ph1ent = array();
1189
		$ph1ent['ikeid'] = ++$ikeid;
1190

    
1191
		if (!isset($mobilecfg['enable'])) {
1192
			$ph1ent['disabled'] = true;
1193
		}
1194

    
1195
		/* Assume WAN since mobile tunnels couldn't be on a separate interface on 1.2.x */
1196
		$ph1ent['interface'] = 'wan';
1197
		$ph1ent['descr'] = "Mobile Clients (upgraded)";
1198
		$ph1ent['mode'] = $mobilecfg['p1']['mode'];
1199

    
1200
		if (isset($mobilecfg['p1']['myident']['myaddress'])) {
1201
			$ph1ent['myid_type'] = "myaddress";
1202
		}
1203
		if (isset($mobilecfg['p1']['myident']['address'])) {
1204
			$ph1ent['myid_type'] = "address";
1205
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['address'];
1206
		}
1207
		if (isset($mobilecfg['p1']['myident']['fqdn'])) {
1208
			$ph1ent['myid_type'] = "fqdn";
1209
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['fqdn'];
1210
		}
1211
		if (isset($mobilecfg['p1']['myident']['ufqdn'])) {
1212
			$ph1ent['myid_type'] = "user_fqdn";
1213
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['ufqdn'];
1214
		}
1215
		if (isset($mobilecfg['p1']['myident']['asn1dn'])) {
1216
			$ph1ent['myid_type'] = "asn1dn";
1217
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['asn1dn'];
1218
		}
1219
		if (isset($mobilecfg['p1']['myident']['dyn_dns'])) {
1220
			$ph1ent['myid_type'] = "dyn_dns";
1221
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['dyn_dns'];
1222
		}
1223
		$ph1ent['peerid_type'] = "fqdn";
1224
		$ph1ent['peerid_data'] = "";
1225

    
1226
		switch ($mobilecfg['p1']['encryption-algorithm']) {
1227
			case "des":
1228
				$ph1alg = array('name' => 'des');
1229
				break;
1230
			case "3des":
1231
				$ph1alg = array('name' => '3des');
1232
				break;
1233
			case "blowfish":
1234
				$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1235
				break;
1236
			case "cast128":
1237
				$ph1alg = array('name' => 'cast128');
1238
				break;
1239
			case "rijndael":
1240
				$ph1alg = array('name' => 'aes', 'keylen' => '128');
1241
				break;
1242
			case "rijndael 256":
1243
			case "aes 256":
1244
				$ph1alg = array('name' => 'aes', 'keylen' => '256');
1245
				break;
1246
		}
1247

    
1248
		$ph1ent['encryption-algorithm'] = $ph1alg;
1249
		$ph1ent['hash-algorithm'] = $mobilecfg['p1']['hash-algorithm'];
1250
		$ph1ent['dhgroup'] = $mobilecfg['p1']['dhgroup'];
1251
		$ph1ent['lifetime'] = $mobilecfg['p1']['lifetime'];
1252
		$ph1ent['authentication_method'] = $mobilecfg['p1']['authentication_method'];
1253

    
1254
		if (isset($mobilecfg['p1']['cert'])) {
1255
			$ph1ent['cert'] = $mobilecfg['p1']['cert'];
1256
		}
1257
		if (isset($mobilecfg['p1']['peercert'])) {
1258
			$ph1ent['peercert'] = $mobilecfg['p1']['peercert'];
1259
		}
1260
		if (isset($mobilecfg['p1']['private-key'])) {
1261
			$ph1ent['private-key'] = $mobilecfg['p1']['private-key'];
1262
		}
1263

    
1264
		$ph1ent['nat_traversal'] = "on";
1265
		$ph1ent['dpd_enable'] = 1;
1266
		$ph1ent['dpd_delay'] = 10;
1267
		$ph1ent['dpd_maxfail'] = 5;
1268
		$ph1ent['mobile'] = true;
1269

    
1270
		$ph2ent = array();
1271
		$ph2ent['ikeid'] = $ph1ent['ikeid'];
1272
		$ph2ent['descr'] = "phase2 for ".$mobilecfg['descr'];
1273
		$ph2ent['localid'] = array('type' => 'none');
1274
		$ph2ent['remoteid'] = array('type' => 'mobile');
1275
		$ph2ent['protocol'] = $mobilecfg['p2']['protocol'];
1276

    
1277
		$aes_count = 0;
1278
		foreach ($mobilecfg['p2']['encryption-algorithm-option'] as $tunalg) {
1279
			$aes_found = false;
1280
			switch ($tunalg) {
1281
				case "des":
1282
					$ph2alg = array('name' => 'des');
1283
					break;
1284
				case "3des":
1285
					$ph2alg = array('name' => '3des');
1286
					break;
1287
				case "blowfish":
1288
					$ph2alg = array('name' => 'blowfish', 'keylen' => 'auto');
1289
					break;
1290
				case "cast128":
1291
					$ph2alg = array('name' => 'cast128');
1292
					break;
1293
				case "rijndael":
1294
				case "rijndael 256":
1295
				case "aes 256":
1296
					$ph2alg = array('name' => 'aes', 'keylen' => 'auto');
1297
					$aes_found = true;
1298
					$aes_count++;
1299
					break;
1300
			}
1301

    
1302
			if (!$aes_found || ($aes_count < 2)) {
1303
				$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1304
			}
1305
		}
1306
		$ph2ent['hash-algorithm-option'] = $mobilecfg['p2']['hash-algorithm-option'];
1307
		$ph2ent['pfsgroup'] = $mobilecfg['p2']['pfsgroup'];
1308
		$ph2ent['lifetime'] = $mobilecfg['p2']['lifetime'];
1309
		$ph2ent['mobile'] = true;
1310

    
1311
		$config['ipsec']['phase1'][] = $ph1ent;
1312
		$config['ipsec']['phase2'][] = $ph2ent;
1313
		config_del_path('ipsec/mobileclients');
1314
	}
1315
}
1316

    
1317

    
1318
function upgrade_047_to_048() {
1319
	global $config;
1320
	if (!empty($config['dyndns'])) {
1321
		$config['dyndnses'] = array();
1322
		$config['dyndnses']['dyndns'] = array();
1323
		if (isset($config['dyndns'][0]['host'])) {
1324
			$tempdyn = array();
1325
			$tempdyn['enable'] = isset($config['dyndns'][0]['enable']);
1326
			$tempdyn['type'] = config_get_path('dyndns/0/type');
1327
			$tempdyn['wildcard'] = isset($config['dyndns'][0]['wildcard']);
1328
			$tempdyn['username'] = config_get_path('dyndns/0/username');
1329
			$tempdyn['password'] = config_get_path('dyndns/0/password');
1330
			$tempdyn['host'] = config_get_path('dyndns/0/host');
1331
			$tempdyn['mx'] = config_get_path('dyndns/0/mx');
1332
			$tempdyn['interface'] = "wan";
1333
			$tempdyn['descr'] = sprintf(gettext("Upgraded Dyndns %s"), $tempdyn['type']);
1334
			$config['dyndnses']['dyndns'][] = $tempdyn;
1335
		}
1336
		config_del_path('dyndns');
1337
	}
1338
	if (!empty($config['dnsupdate'])) {
1339
		$pconfig = config_get_path('dnsupdate/0');
1340
		if (!$pconfig['ttl']) {
1341
			$pconfig['ttl'] = 60;
1342
		}
1343
		if (!$pconfig['keytype']) {
1344
			$pconfig['keytype'] = "zone";
1345
		}
1346
		$pconfig['interface'] = "wan";
1347
		$config['dnsupdates']['dnsupdate'][] = $pconfig;
1348
		config_del_path('dnsupdate');
1349
	}
1350

    
1351
	if (is_array($config['pppoe']) && is_array($config['pppoe'][0])) {
1352
		$pconfig = array();
1353
		$pconfig['username'] = config_get_path('pppoe/0/username');
1354
		$pconfig['password'] = config_get_path('pppoe/0/password');
1355
		$pconfig['provider'] = config_get_path('pppoe/0/provider');
1356
		$pconfig['ondemand'] = isset($config['pppoe'][0]['ondemand']);
1357
		$pconfig['timeout'] = config_get_path('pppoe/0/timeout');
1358
		config_del_path('pppoe');
1359
		$config['interfaces']['wan']['pppoe_username'] = $pconfig['username'];
1360
		$config['interfaces']['wan']['pppoe_password'] = $pconfig['password'];
1361
		$config['interfaces']['wan']['provider'] = $pconfig['provider'];
1362
		$config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']);
1363
		$config['interfaces']['wan']['timeout'] = $pconfig['timeout'];
1364
	}
1365
	if (is_array($config['pptp'])) {
1366
		$pconfig = array();
1367
		$pconfig['username'] = config_get_path('pptp/username');
1368
		$pconfig['password'] = config_get_path('pptp/password');
1369
		$pconfig['provider'] = config_get_path('pptp/provider');
1370
		$pconfig['ondemand'] = isset($config['pptp']['ondemand']);
1371
		$pconfig['timeout'] = config_get_path('pptp/timeout');
1372
		config_del_path('pptp');
1373
		$config['interfaces']['wan']['pptp_username'] = $pconfig['username'];
1374
		$config['interfaces']['wan']['pptp_password'] = $pconfig['password'];
1375
		$config['interfaces']['wan']['provider'] = $pconfig['provider'];
1376
		$config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']);
1377
		$config['interfaces']['wan']['timeout'] = $pconfig['timeout'];
1378
	}
1379
}
1380

    
1381

    
1382
function upgrade_048_to_049() {
1383
	global $config;
1384
	/* setup new all users group */
1385
	$all = array();
1386
	$all['name'] = "all";
1387
	$all['description'] = gettext("All Users");
1388
	$all['scope'] = "system";
1389
	$all['gid'] = 1998;
1390
	$all['member'] = array();
1391

    
1392
	if (!is_array($config['system']['user'])) {
1393
		$config['system']['user'] = array();
1394
	}
1395
	if (!is_array($config['system']['group'])) {
1396
		$config['system']['group'] = array();
1397
	}
1398

    
1399
	/* work around broken uid assignments */
1400
	$config['system']['nextuid'] = 2000;
1401
	foreach ($config['system']['user'] as & $user) {
1402
		if (isset($user['uid']) && !$user['uid']) {
1403
			continue;
1404
		}
1405
		$user['uid'] = $config['system']['nextuid']++;
1406
	}
1407

    
1408
	/* work around broken gid assignments */
1409
	$config['system']['nextgid'] = 2000;
1410
	foreach ($config['system']['group'] as & $group) {
1411
		if ($group['name'] == g_get('admin_group')) {
1412
			$group['gid'] = 1999;
1413
		} else {
1414
			$group['gid'] = $config['system']['nextgid']++;
1415
		}
1416
	}
1417

    
1418
	/* build group membership information */
1419
	foreach ($config['system']['group'] as & $group) {
1420
		$group['member'] = array();
1421
		foreach ($config['system']['user'] as & $user) {
1422
			$groupnames = explode(",", $user['groupname']);
1423
			if (in_array($group['name'], $groupnames)) {
1424
				$group['member'][] = $user['uid'];
1425
			}
1426
		}
1427
	}
1428

    
1429
	/* reset user group information */
1430
	foreach ($config['system']['user'] as & $user) {
1431
		unset($user['groupname']);
1432
		$all['member'][] = $user['uid'];
1433
	}
1434

    
1435
	/* reset group scope information */
1436
	foreach ($config['system']['group'] as & $group) {
1437
		if ($group['name'] != g_get('admin_group')) {
1438
			$group['scope'] = "user";
1439
		}
1440
	}
1441

    
1442
	/* insert new all group */
1443
	$groups = Array();
1444
	$groups[] = $all;
1445
	$groups = array_merge($config['system']['group'], $groups);
1446
	$config['system']['group'] = $groups;
1447
}
1448

    
1449

    
1450
function upgrade_049_to_050() {
1451
	global $config;
1452

    
1453
	if (!is_array($config['system']['user'])) {
1454
		$config['system']['user'] = array();
1455
	}
1456
	/* update user privileges */
1457
	foreach ($config['system']['user'] as & $user) {
1458
		$privs = array();
1459
		if (!is_array($user['priv'])) {
1460
			unset($user['priv']);
1461
			continue;
1462
		}
1463
		foreach ($user['priv'] as $priv) {
1464
			switch ($priv['id']) {
1465
				case "hasshell":
1466
					$privs[] = "user-shell-access";
1467
					break;
1468
				case "copyfiles":
1469
					$privs[] = "user-copy-files";
1470
					break;
1471
			}
1472
		}
1473
		$user['priv'] = $privs;
1474
	}
1475

    
1476
	/* update group privileges */
1477
	foreach ($config['system']['group'] as & $group) {
1478
		$privs = array();
1479
		if (!is_array($group['pages'])) {
1480
			unset($group['pages']);
1481
			continue;
1482
		}
1483
		foreach ($group['pages'] as $page) {
1484
			$priv = map_page_privname($page);
1485
			if ($priv) {
1486
				$privs[] = $priv;
1487
			}
1488
		}
1489
		unset($group['pages']);
1490
		$group['priv'] = $privs;
1491
	}
1492

    
1493
	/* sync all local account information */
1494
	local_reset_accounts();
1495
}
1496

    
1497

    
1498
function upgrade_050_to_051() {
1499
	global $config;
1500
	$pconfig = array();
1501
	$pconfig['descr'] = "Set to 0 to disable filtering on the incoming and outgoing member interfaces.";
1502
	$pconfig['tunable'] = "net.link.bridge.pfil_member";
1503
	$pconfig['value'] = "1";
1504
	$config['sysctl']['item'][] = $pconfig;
1505
	$pconfig = array();
1506
	$pconfig['descr'] = "Set to 1 to enable filtering on the bridge interface";
1507
	$pconfig['tunable'] = "net.link.bridge.pfil_bridge";
1508
	$pconfig['value'] = "0";
1509
	$config['sysctl']['item'][] = $pconfig;
1510

    
1511
	if (isset($config['bridge'])) {
1512
		config_del_path('bridge');
1513
	}
1514

    
1515
	$convert_bridges = false;
1516
	foreach ($config['interfaces'] as $intf) {
1517
		if (isset($intf['bridge']) && $intf['bridge'] <> "") {
1518
			$config['bridges'] = array();
1519
			$config['bridges']['bridged'] = array();
1520
			$convert_bridges = true;
1521
			break;
1522
		}
1523
	}
1524
	if ($convert_bridges == true) {
1525
		$i = 0;
1526
		foreach ($config['interfaces'] as $ifr => &$intf) {
1527
			if (isset($intf['bridge']) && $intf['bridge'] <> "") {
1528
				$nbridge = array();
1529
				$nbridge['members'] = "{$ifr},{$intf['bridge']}";
1530
				$nbridge['descr'] = sprintf(gettext("Converted bridged %s"), $ifr);
1531
				$nbridge['bridgeif'] = "bridge{$i}";
1532
				$config['bridges']['bridged'][] = $nbridge;
1533
				unset($intf['bridge']);
1534
				$i++;
1535
			}
1536
		}
1537
	}
1538
}
1539

    
1540

    
1541
function upgrade_051_to_052() {
1542
	global $config;
1543
	$config['openvpn'] = array();
1544
	if (!is_array($config['ca'])) {
1545
		$config['ca'] = array();
1546
	}
1547
	if (!is_array($config['cert'])) {
1548
		$config['cert'] = array();
1549
	}
1550

    
1551
	$vpnid = 1;
1552

    
1553
	/* openvpn server configurations */
1554
	if (is_array($config['installedpackages']['openvpnserver'])) {
1555
		$config['openvpn']['openvpn-server'] = array();
1556

    
1557
		$index = 1;
1558
		foreach ($config['installedpackages']['openvpnserver']['config'] as $server) {
1559

    
1560
			if (!is_array($server)) {
1561
				continue;
1562
			}
1563

    
1564
			if ($server['auth_method'] == "pki") {
1565

    
1566
				/* create ca entry */
1567
				$ca = array();
1568
				$ca['refid'] = uniqid();
1569
				$ca['descr'] = "OpenVPN Server CA #{$index}";
1570
				$ca['crt'] = $server['ca_cert'];
1571
				$config['ca'][] = $ca;
1572

    
1573
				/* create ca reference */
1574
				unset($server['ca_cert']);
1575
				$server['caref'] = $ca['refid'];
1576

    
1577
				/* create a crl entry if needed */
1578
				if (!empty($server['crl'][0])) {
1579
					$crl = array();
1580
					$crl['refid'] = uniqid();
1581
					$crl['descr'] = "Imported OpenVPN CRL #{$index}";
1582
					$crl['caref'] = $ca['refid'];
1583
					$crl['text'] = $server['crl'][0];
1584
					if (!is_array($config['crl'])) {
1585
						$config['crl'] = array();
1586
					}
1587
					$config['crl'][] = $crl;
1588
					$server['crlref'] = $crl['refid'];
1589
				}
1590
				unset($server['crl']);
1591

    
1592
				/* create cert entry */
1593
				$cert = array();
1594
				$cert['refid'] = uniqid();
1595
				$cert['descr'] = "OpenVPN Server Certificate #{$index}";
1596
				$cert['crt'] = $server['server_cert'];
1597
				$cert['prv'] = $server['server_key'];
1598
				$config['cert'][] = $cert;
1599

    
1600
				/* create cert reference */
1601
				unset($server['server_cert']);
1602
				unset($server['server_key']);
1603
				$server['certref'] = $cert['refid'];
1604

    
1605
				$index++;
1606
			}
1607

    
1608
			/* determine operational mode */
1609
			if ($server['auth_method'] == 'pki') {
1610
				if ($server['nopool']) {
1611
					$server['mode'] = "p2p_tls";
1612
				} else {
1613
					$server['mode'] = "server_tls";
1614
				}
1615
			} else {
1616
				$server['mode'] = "p2p_shared_key";
1617
			}
1618
			unset($server['auth_method']);
1619

    
1620
			/* modify configuration values */
1621
			$server['dh_length'] = 1024;
1622
			unset($server['dh_params']);
1623
			if (!$server['interface']) {
1624
				$server['interface'] = 'any';
1625
			}
1626
			$server['tunnel_network'] = $server['addresspool'];
1627
			unset($server['addresspool']);
1628
			if (isset($server['use_lzo']) && ($server['use_lzo'] == "on")) {
1629
				$server['compression'] = "on";
1630
				unset($server['use_lzo']);
1631
			}
1632
			if ($server['nopool']) {
1633
				$server['pool_enable'] = false;
1634
			} else {
1635
				$server['pool_enable'] = "yes";
1636
			}
1637
			unset($server['nopool']);
1638
			$server['dns_domain'] = $server['dhcp_domainname'];
1639
			unset($server['dhcp_domainname']);
1640

    
1641
			$tmparr = explode(";", $server['dhcp_dns'], 4);
1642
			$d=1;
1643
			foreach ($tmparr as $tmpa) {
1644
				$server["dns_server{$d}"] = $tmpa;
1645
				$d++;
1646
			}
1647
			unset($server['dhcp_dns']);
1648

    
1649
			$tmparr = explode(";", $server['dhcp_ntp'], 2);
1650
			$d=1;
1651
			foreach ($tmparr as $tmpa) {
1652
				$server["ntp_server{$d}"] = $tmpa;
1653
				$d++;
1654
			}
1655
			unset($server['dhcp_ntp']);
1656

    
1657
			if ($server['dhcp_nbtdisable']) {
1658
				$server['netbios_enable'] = false;
1659
			} else {
1660
				$server['netbios_enable'] = "yes";
1661
			}
1662
			unset($server['dhcp_nbtdisable']);
1663
			$server['netbios_ntype'] = $server['dhcp_nbttype'];
1664
			unset($server['dhcp_nbttype']);
1665
			$server['netbios_scope'] = $server['dhcp_nbtscope'];
1666
			unset($server['dhcp_nbtscope']);
1667

    
1668
			$tmparr = explode(";", $server['dhcp_nbdd'], 2);
1669
			$d=1;
1670
			foreach ($tmparr as $tmpa) {
1671
				$server["nbdd_server{$d}"] = $tmpa;
1672
				$d++;
1673
			}
1674
			unset($server['dhcp_nbdd']);
1675

    
1676
			$tmparr = explode(";", $server['dhcp_wins'], 2);
1677
			$d=1;
1678
			foreach ($tmparr as $tmpa) {
1679
				$server["wins_server{$d}"] = $tmpa;
1680
				$d++;
1681
			}
1682
			unset($server['dhcp_wins']);
1683

    
1684
			if (!empty($server['disable'])) {
1685
				$server['disable'] = true;
1686
			} else {
1687
				unset($server['disable']);
1688
			}
1689

    
1690
			/* allocate vpnid */
1691
			$server['vpnid'] = $vpnid++;
1692

    
1693
			if (!empty($server['custom_options'])) {
1694
				$cstmopts = array();
1695
				$tmpcstmopts = explode(";", $server['custom_options']);
1696
				$assigned_if = "";
1697
				$tmpstr = "";
1698
				foreach ($tmpcstmopts as $tmpcstmopt) {
1699
					$tmpstr = str_replace(" ", "", $tmpcstmopt);
1700
					if (substr($tmpstr, 0, 6) == "devtun") {
1701
						$assigned_if = substr($tmpstr, 3);
1702
						continue;
1703
					} else if (substr($tmpstr, 0, 5) == "local") {
1704
						$localip = substr($tmpstr, 5);
1705
						$server['ipaddr'] = str_replace("\n", "", $localip);
1706
					} else {
1707
						$cstmopts[] = $tmpcstmopt;
1708
					}
1709
				}
1710
				$server['custom_options'] = implode(";", $cstmopts);
1711
				if (!empty($assigned_if)) {
1712
					foreach ($config['interfaces'] as $iface => $cfgif) {
1713
						if ($cfgif['if'] == $assigned_if) {
1714
							$config['interfaces'][$iface]['if'] = "ovpns{$server['vpnid']}";
1715
							break;
1716
						}
1717
					}
1718
				}
1719
			}
1720

    
1721
			$config['openvpn']['openvpn-server'][] = $server;
1722
		}
1723
		config_del_path('installedpackages/openvpnserver');
1724
	}
1725

    
1726
	/* openvpn client configurations */
1727
	if (is_array($config['installedpackages']['openvpnclient'])) {
1728
		$config['openvpn']['openvpn-client'] = array();
1729

    
1730
		$index = 1;
1731
		foreach ($config['installedpackages']['openvpnclient']['config'] as $client) {
1732

    
1733
			if (!is_array($client)) {
1734
				continue;
1735
			}
1736

    
1737
			if ($client['auth_method'] == "pki") {
1738

    
1739
				/* create ca entry */
1740
				$ca = array();
1741
				$ca['refid'] = uniqid();
1742
				$ca['descr'] = "OpenVPN Client CA #{$index}";
1743
				$ca['crt'] = $client['ca_cert'];
1744
				$ca['crl'] = $client['crl'];
1745
				$config['ca'][] = $ca;
1746

    
1747
				/* create ca reference */
1748
				unset($client['ca_cert']);
1749
				unset($client['crl']);
1750
				$client['caref'] = $ca['refid'];
1751

    
1752
				/* create cert entry */
1753
				$cert = array();
1754
				$cert['refid'] = uniqid();
1755
				$cert['descr'] = "OpenVPN Client Certificate #{$index}";
1756
				$cert['crt'] = $client['client_cert'];
1757
				$cert['prv'] = $client['client_key'];
1758
				$config['cert'][] = $cert;
1759

    
1760
				/* create cert reference */
1761
				unset($client['client_cert']);
1762
				unset($client['client_key']);
1763
				$client['certref'] = $cert['refid'];
1764

    
1765
				$index++;
1766
			}
1767

    
1768
			/* determine operational mode */
1769
			if ($client['auth_method'] == 'pki') {
1770
				$client['mode'] = "p2p_tls";
1771
			} else {
1772
				$client['mode'] = "p2p_shared_key";
1773
			}
1774
			unset($client['auth_method']);
1775

    
1776
			/* modify configuration values */
1777
			if (!$client['interface']) {
1778
				$client['interface'] = 'wan';
1779
			}
1780
			$client['tunnel_network'] = $client['interface_ip'];
1781
			unset($client['interface_ip']);
1782
			$client['server_addr'] = $client['serveraddr'];
1783
			unset($client['serveraddr']);
1784
			$client['server_port'] = $client['serverport'];
1785
			unset($client['serverport']);
1786
			$client['proxy_addr'] = $client['poxy_hostname'];
1787
			unset($client['proxy_addr']);
1788
			if (isset($client['use_lzo']) && ($client['use_lzo'] == "on")) {
1789
				$client['compression'] = "on";
1790
				unset($client['use_lzo']);
1791
			}
1792
			$client['resolve_retry'] = $client['infiniteresolvretry'];
1793
			unset($client['infiniteresolvretry']);
1794

    
1795
			/* allocate vpnid */
1796
			$client['vpnid'] = $vpnid++;
1797

    
1798
			if (!empty($client['custom_options'])) {
1799
				$cstmopts = array();
1800
				$tmpcstmopts = explode(";", $client['custom_options']);
1801
				$assigned_if = "";
1802
				$tmpstr = "";
1803
				foreach ($tmpcstmopts as $tmpcstmopt) {
1804
					$tmpstr = str_replace(" ", "", $tmpcstmopt);
1805
					if (substr($tmpstr, 0, 6) == "devtun") {
1806
						$assigned_if = substr($tmpstr, 3);
1807
						continue;
1808
					} else if (substr($tmpstr, 0, 5) == "local") {
1809
						$localip = substr($tmpstr, 5);
1810
						$client['ipaddr'] = str_replace("\n", "", $localip);
1811
					} else {
1812
						$cstmopts[] = $tmpcstmopt;
1813
					}
1814
				}
1815
				$client['custom_options'] = implode(";", $cstmopts);
1816
				if (!empty($assigned_if)) {
1817
					foreach ($config['interfaces'] as $iface => $cfgif) {
1818
						if ($cfgif['if'] == $assigned_if) {
1819
							$config['interfaces'][$iface]['if'] = "ovpnc{$client['vpnid']}";
1820
							break;
1821
						}
1822
					}
1823
				}
1824
			}
1825

    
1826
			if (!empty($client['disable'])) {
1827
				$client['disable'] = true;
1828
			} else {
1829
				unset($client['disable']);
1830
			}
1831

    
1832
			$config['openvpn']['openvpn-client'][] = $client;
1833
		}
1834

    
1835
		config_del_path('installedpackages/openvpnclient');
1836
	}
1837

    
1838
	/* openvpn client specific configurations */
1839
	if (is_array($config['installedpackages']['openvpncsc'])) {
1840
		$config['openvpn']['openvpn-csc'] = array();
1841

    
1842
		foreach ($config['installedpackages']['openvpncsc']['config'] as $csc) {
1843

    
1844
			if (!is_array($csc)) {
1845
				continue;
1846
			}
1847

    
1848
			/* modify configuration values */
1849
			$csc['common_name'] = $csc['commonname'];
1850
			unset($csc['commonname']);
1851
			$csc['tunnel_network'] = $csc['ifconfig_push'];
1852
			unset($csc['ifconfig_push']);
1853
			$csc['dns_domain'] = $csc['dhcp_domainname'];
1854
			unset($csc['dhcp_domainname']);
1855

    
1856
			$tmparr = explode(";", $csc['dhcp_dns'], 4);
1857
			$d=1;
1858
			foreach ($tmparr as $tmpa) {
1859
				$csc["dns_server{$d}"] = $tmpa;
1860
				$d++;
1861
			}
1862
			unset($csc['dhcp_dns']);
1863

    
1864
			$tmparr = explode(";", $csc['dhcp_ntp'], 2);
1865
			$d=1;
1866
			foreach ($tmparr as $tmpa) {
1867
				$csc["ntp_server{$d}"] = $tmpa;
1868
				$d++;
1869
			}
1870
			unset($csc['dhcp_ntp']);
1871

    
1872
			if ($csc['dhcp_nbtdisable']) {
1873
				$csc['netbios_enable'] = false;
1874
			} else {
1875
				$csc['netbios_enable'] = "yes";
1876
			}
1877
			unset($csc['dhcp_nbtdisable']);
1878
			$csc['netbios_ntype'] = $csc['dhcp_nbttype'];
1879
			unset($csc['dhcp_nbttype']);
1880
			$csc['netbios_scope'] = $csc['dhcp_nbtscope'];
1881
			unset($csc['dhcp_nbtscope']);
1882

    
1883
			$tmparr = explode(";", $csc['dhcp_nbdd'], 2);
1884
			$d=1;
1885
			foreach ($tmparr as $tmpa) {
1886
				$csc["nbdd_server{$d}"] = $tmpa;
1887
				$d++;
1888
			}
1889
			unset($csc['dhcp_nbdd']);
1890

    
1891
			$tmparr = explode(";", $csc['dhcp_wins'], 2);
1892
			$d=1;
1893
			foreach ($tmparr as $tmpa) {
1894
				$csc["wins_server{$d}"] = $tmpa;
1895
				$d++;
1896
			}
1897
			unset($csc['dhcp_wins']);
1898

    
1899
			if (!empty($csc['disable'])) {
1900
				$csc['disable'] = true;
1901
			} else {
1902
				unset($csc['disable']);
1903
			}
1904

    
1905
			$config['openvpn']['openvpn-csc'][] = $csc;
1906
		}
1907

    
1908
		config_del_path('installedpackages/openvpncsc');
1909
	}
1910

    
1911
	if (count($config['openvpn']['openvpn-server']) > 0 ||
1912
	    count($config['openvpn']['openvpn-client']) > 0) {
1913
		$ovpnrule = array();
1914
		$ovpnrule['type'] = "pass";
1915
		$ovpnrule['interface'] = "openvpn";
1916
		$ovpnrule['statetype'] = "keep state";
1917
		$ovpnrule['source'] = array();
1918
		$ovpnrule['destination'] = array();
1919
		$ovpnrule['source']['any'] = true;
1920
		$ovpnrule['destination']['any'] = true;
1921
		$ovpnrule['descr'] = gettext("Auto added OpenVPN rule from config upgrade.");
1922
		$config['filter']['rule'][] = $ovpnrule;
1923
	}
1924

    
1925
	/*
1926
		* FIXME: hack to keep things working with no installedpackages
1927
		* or carp array in the configuration data.
1928
		*/
1929
	if (!is_array($config['installedpackages'])) {
1930
		$config['installedpackages'] = array();
1931
	}
1932
	if (!is_array($config['installedpackages']['carp'])) {
1933
		$config['installedpackages']['carp'] = array();
1934
	}
1935

    
1936
}
1937

    
1938

    
1939
function upgrade_052_to_053() {
1940
	global $config;
1941
	if (!is_array($config['ca'])) {
1942
		$config['ca'] = array();
1943
	}
1944
	if (!is_array($config['cert'])) {
1945
		$config['cert'] = array();
1946
	}
1947

    
1948
	/* migrate advanced admin page webui ssl to certificate manager */
1949
	if ($config['system']['webgui']['certificate'] &&
1950
	    $config['system']['webgui']['private-key']) {
1951

    
1952
		/* create cert entry */
1953
		$cert = array();
1954
		$cert['refid'] = uniqid();
1955
		$cert['descr'] = "webConfigurator SSL/TLS Certificate";
1956
		$cert['crt'] = config_get_path('system/webgui/certificate');
1957
		$cert['prv'] = config_get_path('system/webgui/private-key');
1958
		$config['cert'][] = $cert;
1959

    
1960
		config_del_path('system/webgui/certificate');
1961
		config_del_path('system/webgui/private-key');
1962
		$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1963
	}
1964

    
1965
	/* migrate advanced admin page ssh keys to user manager */
1966
	if ($config['system']['ssh']['authorizedkeys']) {
1967
		$admin_user =& getUserEntryByUID(0);
1968
		$admin_user['authorizedkeys'] = config_get_path('system/ssh/authorizedkeys');
1969
		config_del_path('system/ssh/authorizedkeys');
1970
	}
1971
}
1972

    
1973

    
1974
function upgrade_053_to_054() {
1975
	global $config;
1976
	if (is_array($config['load_balancer']['lbpool'])) {
1977
		$lbpool_arr = config_get_path('load_balancer/lbpool');
1978
		$lbpool_srv_arr = array();
1979
		$gateway_group_arr = array();
1980
		$gateways = return_gateways_array();
1981
		$group_name_changes = array();
1982
		init_config_arr(array('gateways', 'gateway_item'));
1983
		$a_gateways = &$config['gateways']['gateway_item'];
1984
		foreach ($lbpool_arr as $lbpool) {
1985
			if ($lbpool['type'] == "gateway") {
1986
				// Gateway Groups have to have valid names in pf, old lb pools did not. Clean them up.
1987
				$group_name = preg_replace("/[^A-Za-z0-9]/", "", $lbpool['name']);
1988
				// If we made and changes, check for collisions and note the change.
1989
				if ($group_name != $lbpool['name']) {
1990
					// Make sure the name isn't already in use.
1991
					foreach ($gateway_group_arr as $gwg) {
1992
						// If the name is in use, add some random bits to avoid collision.
1993
						if ($gwg['name'] == $group_name) {
1994
							$group_name .= uniqid();
1995
						}
1996
					}
1997
					$group_name_changes[$lbpool['name']] = $group_name;
1998
				}
1999
				$gateway_group['name'] = $group_name;
2000
				$gateway_group['descr'] = $lbpool['descr'];
2001
				$gateway_group['trigger'] = "down";
2002
				$gateway_group['item'] = array();
2003
				$i = 0;
2004
				foreach ($lbpool['servers'] as $member) {
2005
					$split = explode("|", $member);
2006
					$interface = $split[0];
2007
					$monitor = $split[1];
2008
					/* on static upgraded configuration we automatically prepend GW_ */
2009
					$static_name = "GW_" . strtoupper($interface);
2010
					if (is_ipaddr($monitor)) {
2011
						foreach ($a_gateways as & $gw) {
2012
							if ($gw['name'] == $static_name) {
2013
								$gw['monitor'] = $monitor;
2014
							}
2015
						}
2016
					}
2017

    
2018
					/* on failover increment tier. Else always assign 1 */
2019
					if ($lbpool['behaviour'] == "failover") {
2020
						$i++;
2021
					} else {
2022
						$i = 1;
2023
					}
2024
					$gateway_group['item'][] = "$static_name|$i";
2025
				}
2026
				$gateway_group_arr[] = $gateway_group;
2027
			} else {
2028
				$lbpool_srv_arr[] = $lbpool;
2029
			}
2030
		}
2031
		$config['load_balancer']['lbpool'] = $lbpool_srv_arr;
2032
		$config['gateways']['gateway_group'] = $gateway_group_arr;
2033
	}
2034
	// Unset lbpool if we no longer have any server pools
2035
	if (count($lbpool_srv_arr) == 0) {
2036
		if (empty($config['load_balancer'])) {
2037
			config_del_path('load_balancer');
2038
		} else {
2039
			if (isset($config['load_balancer']['lbpool'])) {
2040
				config_del_path('load_balancer/lbpool');
2041
			}
2042
		}
2043
	} else {
2044
		$config['load_balancer']['lbpool'] = $lbpool_srv_arr;
2045
	}
2046
	// Only set the gateway group array if we converted any
2047
	if (count($gateway_group_arr) != 0) {
2048
		$config['gateways']['gateway_group'] = $gateway_group_arr;
2049
		// Update any rules that had a gateway change, if any.
2050
		if (count($group_name_changes) > 0) {
2051
			foreach ($config['filter']['rule'] as & $rule) {
2052
				if (!empty($rule["gateway"]) && array_key_exists($rule["gateway"], $group_name_changes)) {
2053
					$rule["gateway"] = $group_name_changes[$rule["gateway"]];
2054
				}
2055
			}
2056
		}
2057
	}
2058
}
2059

    
2060

    
2061
function upgrade_054_to_055() {
2062
	global $config;
2063
	global $g;
2064

    
2065
	/* RRD files changed for quality, traffic and packets graphs */
2066
	//ini_set("max_execution_time", "1800");
2067
	/* convert traffic RRD file */
2068
	global $parsedcfg, $listtags;
2069
	$listtags = array("ds", "v", "rra", "row");
2070

    
2071
	$rrddbpath = "/var/db/rrd/";
2072
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2073

    
2074
	$rrdinterval = 60;
2075
	$valid = $rrdinterval * 2;
2076

    
2077
	/* Assume GigE for now */
2078
	$downstream = 125000000;
2079
	$upstream = 125000000;
2080

    
2081
	/* build a list of quality databases */
2082
	/* roundtrip has become delay */
2083
	function divide_delay($delayval) {
2084
		$delayval = floatval($delayval);
2085
		$delayval = ($delayval / 1000);
2086
		$delayval = " ". sprintf("%1.10e", $delayval) ." ";
2087
		return $delayval;
2088
	}
2089
	/* the roundtrip times need to be divided by 1000 to get seconds, really */
2090
	$databases = array();
2091
	if (!file_exists($rrddbpath)) {
2092
		@mkdir($rrddbpath);
2093
	}
2094
	chdir($rrddbpath);
2095
	$databases = glob("*-quality.rrd");
2096
	rsort($databases);
2097
	foreach ($databases as $database) {
2098
		$xmldump = "{$database}.old.xml";
2099
		$xmldumpnew = "{$database}.new.xml";
2100

    
2101
		if (platform_booting()) {
2102
			echo "Migrate RRD database {$database} to new format for IPv6 \n";
2103
		}
2104
		mwexec("$rrdtool tune {$rrddbpath}{$database} -r roundtrip:delay 2>&1");
2105

    
2106
		dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}");
2107
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2108
		$rrdold = $rrdold['rrd'];
2109

    
2110
		$i = 0;
2111
		foreach ($rrdold['rra'] as $rra) {
2112
			$l = 0;
2113
			foreach ($rra['database']['row'] as $row) {
2114
				$vnew = divide_delay($row['v'][1]);
2115
				$rrdold['rra'][$i]['database']['row'][$l]['v'][1] = $vnew;
2116
				$l++;
2117
			}
2118
			$i++;
2119
		}
2120

    
2121
		file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", dump_xml_config_raw($rrdold, "rrd"));
2122
		mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1");
2123

    
2124
		unset($rrdold);
2125
		@unlink("{$g['tmp_path']}/{$xmldump}");
2126
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2127
	}
2128

    
2129
	/* build a list of traffic and packets databases */
2130
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
2131
	rsort($databases);
2132
	foreach ($databases as $database) {
2133
		$databasetmp = "{$database}.tmp";
2134
		$xmldump = "{$database}.old.xml";
2135
		$xmldumptmp = "{$database}.tmp.xml";
2136
		$xmldumpnew = "{$database}.new.xml";
2137

    
2138
		if (platform_booting()) {
2139
			echo "Migrate RRD database {$database} to new format \n";
2140
		}
2141
		/* rename DS source */
2142
		mwexec("$rrdtool tune {$rrddbpath}/{$database} -r in:inpass 2>&1");
2143
		mwexec("$rrdtool tune {$rrddbpath}/{$database} -r out:outpass 2>71");
2144

    
2145
		/* dump contents to xml and move database out of the way */
2146
		dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}");
2147

    
2148
		/* create new rrd database file */
2149
		$rrdcreate = "$rrdtool create {$g['tmp_path']}/{$databasetmp} --step $rrdinterval ";
2150
		$rrdcreate .= "DS:inpass:COUNTER:$valid:0:$downstream ";
2151
		$rrdcreate .= "DS:outpass:COUNTER:$valid:0:$upstream ";
2152
		$rrdcreate .= "DS:inblock:COUNTER:$valid:0:$downstream ";
2153
		$rrdcreate .= "DS:outblock:COUNTER:$valid:0:$upstream ";
2154
		$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
2155
		$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
2156
		$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
2157
		$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
2158

    
2159
		create_new_rrd("$rrdcreate");
2160
		/* create temporary xml from new RRD */
2161
		dump_rrd_to_xml("{$g['tmp_path']}/{$databasetmp}", "{$g['tmp_path']}/{$xmldumptmp}");
2162

    
2163
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2164
		$rrdold = $rrdold['rrd'];
2165

    
2166
		$rrdnew = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldumptmp}"), 1, "tag");
2167
		$rrdnew = $rrdnew['rrd'];
2168

    
2169
		/* remove any MAX RRA's. Not needed for traffic. */
2170
		$i = 0;
2171
		foreach ($rrdold['rra'] as $rra) {
2172
			if (trim($rra['cf']) == "MAX") {
2173
				unset($rrdold['rra'][$i]);
2174
			}
2175
			$i++;
2176
		}
2177

    
2178
		file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", dump_xml_config_raw(migrate_rrd_format($rrdold, $rrdnew), "rrd"));
2179
		mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1");
2180
		/* we now have the rrd with the new fields, adjust the size now. */
2181
		/* RRA 2 is 60 minutes, RRA 3 is 720 minutes */
2182
		mwexec("/bin/sync");
2183
		mwexec("$rrdtool resize {$rrddbpath}/{$database} 2 GROW 2000;/bin/mv resize.rrd {$rrddbpath}/{$database} 2>&1");
2184
		mwexec("/bin/sync");
2185
		mwexec("$rrdtool resize {$rrddbpath}/{$database} 3 GROW 2000;/bin/mv resize.rrd {$rrddbpath}/{$database} 2>&1");
2186
		unset($rrdxmlarray);
2187
		@unlink("{$g['tmp_path']}/{$xmldump}");
2188
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2189
	}
2190
	if (!platform_booting()) {
2191
		enable_rrd_graphing();
2192
	}
2193
	/* Let's save the RRD graphs after we run enable RRD graphing */
2194
	/* The function will restore the rrd.tgz so we will save it after */
2195
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
2196
	unlink_if_exists("{$g['vardb_path']}/rrd/*.xml");
2197
	if (platform_booting()) {
2198
		echo "Updating configuration...";
2199
	}
2200
}
2201

    
2202

    
2203
function upgrade_055_to_056() {
2204
	global $config;
2205

    
2206
	if (!is_array($config['ca'])) {
2207
		$config['ca'] = array();
2208
	}
2209
	if (!is_array($config['cert'])) {
2210
		$config['cert'] = array();
2211
	}
2212

    
2213
	/* migrate ipsec ca's to cert manager */
2214
	if (is_array($config['ipsec']['cacert'])) {
2215
		foreach ($config['ipsec']['cacert'] as & $cacert) {
2216
			$ca = array();
2217
			$ca['refid'] = uniqid();
2218
			if (is_array($cacert['cert'])) {
2219
				$ca['crt'] = $cacert['cert'][0];
2220
			} else {
2221
				$ca['crt'] = $cacert['cert'];
2222
			}
2223
			$ca['descr'] = $cacert['ident'];
2224
			$config['ca'][] = $ca;
2225
		}
2226
		config_del_path('ipsec/cacert');
2227
	}
2228

    
2229
	/* migrate phase1 certificates to cert manager */
2230
	if (is_array($config['ipsec']['phase1'])) {
2231
		foreach ($config['ipsec']['phase1'] as & $ph1ent) {
2232
			$cert = array();
2233
			$cert['refid'] = uniqid();
2234
			$cert['descr'] = "IPsec Peer {$ph1ent['remote-gateway']} Certificate";
2235
			if (is_array($ph1ent['cert'])) {
2236
				$cert['crt'] = $ph1ent['cert'][0];
2237
			} else {
2238
				$cert['crt'] = $ph1ent['cert'];
2239
			}
2240
			$cert['prv'] = $ph1ent['private-key'];
2241
			$config['cert'][] = $cert;
2242
			$ph1ent['certref'] = $cert['refid'];
2243
			if ($ph1ent['cert']) {
2244
				unset($ph1ent['cert']);
2245
			}
2246
			if ($ph1ent['private-key']) {
2247
				unset($ph1ent['private-key']);
2248
			}
2249
			if ($ph1ent['peercert']) {
2250
				unset($ph1ent['peercert']);
2251
			}
2252
		}
2253
	}
2254
}
2255

    
2256

    
2257
function upgrade_056_to_057() {
2258
	global $config;
2259

    
2260
	if (!is_array($config['system']['user'])) {
2261
		$config['system']['user'] = array();
2262
	}
2263
	/* migrate captivate portal to user manager */
2264
	if (is_array($config['captiveportal']['user'])) {
2265
		foreach ($config['captiveportal']['user'] as $user) {
2266
			// avoid user conflicts
2267
			$found = false;
2268
			foreach ($config['system']['user'] as $userent) {
2269
				if ($userent['name'] == $user['name']) {
2270
					$found = true;
2271
					break;
2272
				}
2273
			}
2274
			if ($found) {
2275
				continue;
2276
			}
2277
			$user['scope'] = "user";
2278
			if (isset($user['expirationdate'])) {
2279
				$user['expires'] = $user['expirationdate'];
2280
				unset($user['expirationdate']);
2281
			}
2282
			if (isset($user['password'])) {
2283
				$user['md5-hash'] = $user['password'];
2284
				unset($user['password']);
2285
			}
2286
			$user['uid'] = $config['system']['nextuid']++;
2287
			$config['system']['user'][] = $user;
2288
		}
2289
		config_del_path('captiveportal/user');
2290
	}
2291
}
2292

    
2293
function upgrade_057_to_058() {
2294
	global $config;
2295
	/* set all phase2 entries to tunnel mode */
2296
	if (is_array($config['ipsec']['phase2'])) {
2297
		foreach ($config['ipsec']['phase2'] as & $ph2ent) {
2298
			$ph2ent['mode'] = 'tunnel';
2299
		}
2300
	}
2301
}
2302

    
2303
function upgrade_058_to_059() {
2304
	global $config;
2305

    
2306
	if (is_array($config['schedules']['schedule'])) {
2307
		foreach ($config['schedules']['schedule'] as & $schedl) {
2308
			$schedl['schedlabel'] = uniqid();
2309
		}
2310
	}
2311
}
2312

    
2313
function upgrade_059_to_060() {
2314
	global $config;
2315
	require_once("/etc/inc/certs.inc");
2316
	if (is_array($config['ca'])) {
2317
		/* Locate issuer for all CAs */
2318
		foreach ($config['ca'] as & $ca) {
2319
			$subject = cert_get_subject($ca['crt']);
2320
			$issuer = cert_get_issuer($ca['crt']);
2321
			if ($issuer <> $subject) {
2322
				$issuer_crt =& lookup_ca_by_subject($issuer);
2323
				if ($issuer_crt) {
2324
					$ca['caref'] = $issuer_crt['refid'];
2325
				}
2326
			}
2327
		}
2328

    
2329
		/* Locate issuer for all certificates */
2330
		if (is_array($config['cert'])) {
2331
			foreach ($config['cert'] as & $cert) {
2332
				$subject = cert_get_subject($cert['crt']);
2333
				$issuer = cert_get_issuer($cert['crt']);
2334
				if ($issuer <> $subject) {
2335
					$issuer_crt =& lookup_ca_by_subject($issuer);
2336
					if ($issuer_crt) {
2337
						$cert['caref'] = $issuer_crt['refid'];
2338
					}
2339
				}
2340
			}
2341
		}
2342
	}
2343
}
2344

    
2345
function upgrade_060_to_061() {
2346
	global $config;
2347

    
2348
	if (is_array($config['interfaces']['wan'])) {
2349
		$config['interfaces']['wan']['enable'] = true;
2350
	}
2351
	if (is_array($config['interfaces']['lan'])) {
2352
		$config['interfaces']['lan']['enable'] = true;
2353
	}
2354

    
2355
	/* On 1.2.3 the "mtu" field adjusted MSS.
2356
	   On 2.x the "mtu" field is actually the MTU. Rename accordingly.
2357
	   See redmine ticket #1886
2358
	*/
2359
	foreach ($config['interfaces'] as $ifr => &$intf) {
2360
		if (isset($intf['mtu']) && is_numeric($intf['mtu'])) {
2361
			$intf['mss'] = $intf['mtu'];
2362
			unset($intf['mtu']);
2363
		}
2364
	}
2365
}
2366

    
2367
function upgrade_061_to_062() {
2368
	global $config;
2369

    
2370
	/* Convert NAT port forwarding rules */
2371
	if (is_array($config['nat']['rule'])) {
2372
		$a_nat = &$config['nat']['rule'];
2373

    
2374
		foreach ($a_nat as &$natent) {
2375
			$natent['disabled'] = false;
2376
			$natent['nordr']    = false;
2377

    
2378
			$natent['source'] = array(
2379
				"not"     => false,
2380
				"any"     => true,
2381
				"port"    => ""
2382
			);
2383

    
2384
			$natent['destination'] = array(
2385
				"not"     => false,
2386
				"address" => $natent['external-address'],
2387
				"port"    => $natent['external-port']
2388
			);
2389

    
2390
			if (empty($natent['destination']['address'])) {
2391
				unset($natent['destination']['address']);
2392
				$natent['destination']['network'] = $natent['interface'] . 'ip';
2393
			} else if ($natent['destination']['address'] == 'any') {
2394
				unset($natent['destination']['address']);
2395
				$natent['destination']['any'] = true;
2396
			}
2397

    
2398
			unset($natent['external-address']);
2399
			unset($natent['external-port']);
2400
		}
2401

    
2402
		unset($natent);
2403
	}
2404
}
2405

    
2406
function upgrade_062_to_063() {
2407
	/* Upgrade legacy Themes to the new pfsense_ng */
2408
	// Not supported in 2.3+
2409

    
2410
}
2411

    
2412
function upgrade_063_to_064() {
2413
	global $config;
2414
	$j = 0;
2415
	init_config_arr(array('ppps', 'ppp'));
2416
	init_config_arr(array('interfaces'));
2417
	$ifcfg = &$config['interfaces'];
2418

    
2419
	if (count($config['ppps']['ppp'])) {
2420
		foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
2421
			$config['ppps']['ppp'][$pppid]['if'] = "ppp".$j;
2422
			$config['ppps']['ppp'][$pppid]['ptpid'] = $j;
2423
			$j++;
2424
			if (isset($ppp['port'])) {
2425
				$config['ppps']['ppp'][$pppid]['ports'] = $ppp['port'];
2426
				config_del_path("ppps/ppp/{$pppid}/port");
2427
			}
2428
			if (!isset($ppp['type'])) {
2429
				$config['ppps']['ppp'][$pppid]['type'] = "ppp";
2430
			}
2431
			if (isset($ppp['defaultgw'])) {
2432
				config_del_path("ppps/ppp/{$pppid}/defaultgw");
2433
			}
2434
		}
2435
	}
2436

    
2437
	$a_ppps = &$config['ppps']['ppp'];
2438

    
2439
	foreach ($ifcfg as $ifname => $ifinfo) {
2440
		$ppp = array();
2441
		// For pppoe conversion
2442
		if ($ifinfo['ipaddr'] == "pppoe" || $ifinfo['ipaddr'] == "pptp") {
2443
			if (isset($ifinfo['ptpid'])) {
2444
				continue;
2445
			}
2446
			$ppp['ptpid'] = $j;
2447
			$ppp['type'] = $ifinfo['ipaddr'];
2448
			$ppp['if'] = $ifinfo['ipaddr'].$j;
2449
			$ppp['ports'] = $ifinfo['if'];
2450
			if ($ifinfo['ipaddr'] == "pppoe") {
2451
				$ppp['username'] = $ifinfo['pppoe_username'];
2452
				$ppp['password'] = base64_encode($ifinfo['pppoe_password']);
2453
			}
2454
			if ($ifinfo['ipaddr'] == "pptp") {
2455
				$ppp['username'] = $ifinfo['pptp_username'];
2456
				$ppp['password'] = base64_encode($ifinfo['pptp_password']);
2457
			}
2458

    
2459
			if (isset($ifinfo['provider'])) {
2460
				$ppp['provider'] = $ifinfo['provider'];
2461
			}
2462
			if (isset($ifinfo['ondemand'])) {
2463
				$ppp['ondemand'] = true;
2464
			}
2465
			if (isset($ifinfo['timeout'])) {
2466
				$ppp['idletimeout'] = $ifinfo['timeout'];
2467
			}
2468
			if (isset($ifinfo['pppoe']['pppoe-reset-type'])) {
2469
				$ppp['pppoe-reset-type'] = $ifinfo['pppoe']['pppoe-reset-type'];
2470
				if (is_array($config['cron']['item'])) {
2471
					for ($i = 0; $i < count($config['cron']['item']); $i++) {
2472
						$item = config_get_path("cron/item/{$i}");
2473
						if (strpos($item['command'], "/conf/pppoe{$ifname}restart") !== false) {
2474
							$config['cron']['item'][$i]['command'] = "/var/etc/pppoe_restart_" . $ppp['if'];
2475
						}
2476
					}
2477
				}
2478
			}
2479
			if (isset($ifinfo['local'])) {
2480
				$ppp['localip'] = $ifinfo['local'];
2481
			}
2482
			if (isset($ifinfo['subnet'])) {
2483
				$ppp['subnet'] = $ifinfo['subnet'];
2484
			}
2485
			if (isset($ifinfo['remote'])) {
2486
				$ppp['gateway'] = $ifinfo['remote'];
2487
			}
2488

    
2489
			$ifcfg[$ifname]['if'] = $ifinfo['ipaddr'].$j;
2490
			$j++;
2491

    
2492
			unset($ifcfg[$ifname]['pppoe_username']);
2493
			unset($ifcfg[$ifname]['pppoe_password']);
2494
			unset($ifcfg[$ifname]['provider']);
2495
			unset($ifcfg[$ifname]['ondemand']);
2496
			unset($ifcfg[$ifname]['timeout']);
2497
			unset($ifcfg[$ifname]['pppoe_reset']);
2498
			unset($ifcfg[$ifname]['pppoe_preset']);
2499
			unset($ifcfg[$ifname]['pppoe']);
2500
			unset($ifcfg[$ifname]['pptp_username']);
2501
			unset($ifcfg[$ifname]['pptp_password']);
2502
			unset($ifcfg[$ifname]['local']);
2503
			unset($ifcfg[$ifname]['subnet']);
2504
			unset($ifcfg[$ifname]['remote']);
2505

    
2506
			$a_ppps[] = $ppp;
2507

    
2508
		}
2509
	}
2510
}
2511

    
2512
function upgrade_064_to_065() {
2513
	/* Disable TSO and LRO in upgraded configs */
2514
	global $config;
2515
	$config['system']['disablesegmentationoffloading'] = true;
2516
	$config['system']['disablelargereceiveoffloading'] = true;
2517
}
2518

    
2519
function upgrade_065_to_066() {
2520
	global $config;
2521

    
2522
	init_config_arr(array('dhcrelay'));
2523
	$dhcrelaycfg = &$config['dhcrelay'];
2524

    
2525
	if (is_array($dhcrelaycfg)) {
2526
		$dhcrelayifs = array();
2527
		$foundifs = false;
2528
		/* DHCPRelay enabled on any interfaces? */
2529
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
2530
			if (isset($dhcrelayifconf['enable'])) {
2531
				$dhcrelayifs[] = $dhcrelayif;
2532
				unset($dhcrelaycfg['dhcrelayif']);
2533
				$foundifs = true;
2534
			}
2535
		}
2536
		if ($foundifs == true) {
2537
			$dhcrelaycfg['interface'] = implode(",", $dhcrelayifs);
2538
		}
2539
	}
2540
}
2541

    
2542
function upgrade_066_to_067() {
2543
	global $config;
2544
	if (isset($config['system']['ca'])) {
2545
		$config['ca'] = config_get_path('system/ca');
2546
		config_del_path('system/ca');
2547
	}
2548
	if (isset($config['system']['cert'])) {
2549
		$config['cert'] = config_get_path('system/cert');
2550
		config_del_path('system/cert');
2551
	}
2552
}
2553

    
2554
function upgrade_067_to_068() {
2555
	global $config;
2556

    
2557
	if (!empty($config['pppoe'])) {
2558
		$config['pppoes'] = array();
2559
		$config['pppoes']['pppoe'] = array();
2560
		$config['pppoes']['pppoe'][] = config_get_path('pppoe/0');
2561

    
2562
		if (is_array($config['pppoe']['user'])) {
2563
			$username = array();
2564
			foreach ($config['pppoe']['user'] as $user) {
2565
				$usr = $user['name'] . ":" . base64_encode($user['password']);
2566
				if ($user['ip']) {
2567
					$usr .= ":{$user['ip']}";
2568
				}
2569
				$username[] = $usr;
2570
			}
2571
			$config['pppoes']['pppoe'][0]['username'] = implode(" ", $username);
2572
		}
2573
		config_del_path('pppoe');
2574
	}
2575
}
2576

    
2577
function upgrade_068_to_069() {
2578
	global $config;
2579
	if (!is_array($config['system']['user'])) {
2580
		return;
2581
	}
2582
	foreach ($config['system']['user'] as & $user) {
2583
		if (!is_array($user['cert'])) {
2584
			continue;
2585
		}
2586
		$rids = array();
2587
		foreach ($user['cert'] as $id => $cert) {
2588
			if (!isset($cert['descr'])) {
2589
				continue;
2590
			}
2591
			$tcert = $cert;
2592
			// Make sure each cert gets a refid
2593
			if (!isset($tcert['refid'])) {
2594
				$tcert['refid'] = uniqid();
2595
			}
2596
			// Keep the cert references for this user
2597
			$rids[] = $tcert['refid'];
2598
			$config['cert'][] = $tcert;
2599
		}
2600
		// Replace user certs with cert references instead.
2601
		if (count($rids) > 0) {
2602
			$user['cert'] = $rids;
2603
		}
2604
	}
2605
}
2606

    
2607
function upgrade_069_to_070() {
2608
	global $config;
2609

    
2610
	/* Convert NAT 1:1 rules */
2611
	if (is_array($config['nat']['onetoone'])) {
2612
		foreach ($config['nat']['onetoone'] as $nidx => $natent) {
2613
			if ($natent['subnet'] == 32) {
2614
				$config['nat']['onetoone'][$nidx]['source'] = array("address" => $natent['internal']);
2615
			} else {
2616
				$config['nat']['onetoone'][$nidx]['source'] = array("address" => $natent['internal'] . "/" . $natent['subnet']);
2617
			}
2618

    
2619
			$config['nat']['onetoone'][$nidx]['destination'] = array("any" => true);
2620

    
2621
			config_del_path("nat/onetoone/{$nidx}/internal");
2622
			config_del_path("nat/onetoone/{$nidx}/subnet");
2623
		}
2624

    
2625
		unset($natent);
2626
	}
2627
}
2628

    
2629
function upgrade_070_to_071() {
2630
	global $config;
2631

    
2632
	if (is_array($config['cron']['item'])) {
2633
		foreach ($config['cron']['item'] as $idx => $cronitem) {
2634
			if (stristr($cronitem['command'], "checkreload.sh")) {
2635
				config_del_path("cron/item/{$idx}");
2636
				break;
2637
			}
2638
		}
2639
	}
2640
}
2641

    
2642
function rename_field(& $section, $oldname, $newname) {
2643
	if (is_array($section)) {
2644
		foreach ($section as & $item) {
2645
			if (is_array($item) && !empty($item[$oldname])) {
2646
				$item[$newname] = $item[$oldname];
2647
			}
2648
			if (is_array($item) && isset($item[$oldname])) {
2649
				unset($item[$oldname]);
2650
			}
2651
		}
2652
	}
2653
}
2654

    
2655
function upgrade_071_to_072() {
2656
	global $config;
2657
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
2658
		rename_field($config['sysctl']['item'], 'desc', 'descr');
2659
	}
2660
}
2661

    
2662
function upgrade_072_to_073() {
2663
	global $config;
2664
	if (!is_array($config['load_balancer'])) {
2665
		return;
2666
	}
2667
	if (is_array($config['load_balancer']['monitor_type'])) {
2668
		rename_field($config['load_balancer']['monitor_type'], 'desc', 'descr');
2669
	}
2670
	if (is_array($config['load_balancer']['lbpool'])) {
2671
		rename_field($config['load_balancer']['lbpool'], 'desc', 'descr');
2672
	}
2673
	if (is_array($config['load_balancer']['lbaction'])) {
2674
		rename_field($config['load_balancer']['lbaction'], 'desc', 'descr');
2675
	}
2676
	if (is_array($config['load_balancer']['lbprotocol'])) {
2677
		rename_field($config['load_balancer']['lbprotocol'], 'desc', 'descr');
2678
	}
2679
	if (is_array($config['load_balancer']['virtual_server'])) {
2680
		rename_field($config['load_balancer']['virtual_server'], 'desc', 'descr');
2681
	}
2682
}
2683

    
2684
function upgrade_073_to_074() {
2685
	global $config;
2686
	rename_field($config['system']['user'], 'fullname', 'descr');
2687
}
2688

    
2689
function upgrade_074_to_075() {
2690
	global $config;
2691
	if (is_array($config['ca'])) {
2692
		rename_field($config['ca'], 'name', 'descr');
2693
	}
2694
	if (is_array($config['cert'])) {
2695
		rename_field($config['cert'], 'name', 'descr');
2696
	}
2697
	if (is_array($config['crl'])) {
2698
		rename_field($config['crl'], 'name', 'descr');
2699
	}
2700
}
2701

    
2702
function upgrade_075_to_076() {
2703
	global $config;
2704
	$cron_item = array();
2705
	$cron_item['minute'] = "30";
2706
	$cron_item['hour'] = "12";
2707
	$cron_item['mday'] = "*";
2708
	$cron_item['month'] = "*";
2709
	$cron_item['wday'] = "*";
2710
	$cron_item['who'] = "root";
2711
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.update_urltables";
2712
	$config['cron']['item'][] = $cron_item;
2713
}
2714

    
2715
function upgrade_076_to_077() {
2716
	global $config;
2717
	foreach ($config['filter']['rule'] as & $rule) {
2718
		if (isset($rule['protocol']) && !empty($rule['protocol'])) {
2719
			$rule['protocol'] = strtolower($rule['protocol']);
2720
		}
2721
	}
2722
}
2723

    
2724
function upgrade_077_to_078() {
2725
	global $config;
2726
	if (is_array($config['pptpd']) && is_array($config['pptpd']['radius']) &&
2727
	    !is_array($config['pptpd']['radius']['server'])) {
2728
		$radarr = array();
2729
		$radsvr = array();
2730
		$radsvr['ip'] = config_get_path('pptpd/radius/server');
2731
		$radsvr['secret'] = config_get_path('pptpd/radius/secret');
2732
		$radsvr['port'] = 1812;
2733
		$radsvr['acctport'] = 1813;
2734
		$radsvr['enable'] = isset($config['pptpd']['radius']['enable']);
2735
		$radarr['accounting'] = isset($config['pptpd']['radius']['accounting']);
2736
		if ($radarr['accounting']) {
2737
			$radarr['acct_update'] = $radsvr['ip'];
2738
		}
2739
		$radarr['server'] = $radsvr;
2740
		$config['pptpd']['radius'] = $radarr;
2741
	}
2742
	if (is_array($config['pptpd'])) {
2743
		$config['pptpd']['n_pptp_units'] = empty($config['pptpd']['n_pptp_units']) ? 16 : $config['pptpd']['n_pptp_units'];
2744
	}
2745
}
2746
function upgrade_078_to_079() {
2747
	global $g;
2748
	/* Delete old and unused RRD file */
2749
	unlink_if_exists("{$g['vardb_path']}/rrd/captiveportal-totalusers.rrd");
2750
}
2751

    
2752
function upgrade_079_to_080() {
2753
	global $config;
2754

    
2755
	/* Upgrade config in 1.2.3 specifying a username other than admin for syncing. */
2756
	if (!empty($config['system']['username']) && is_array($config['installedpackages']['carpsettings']) &&
2757
	    is_array($config['installedpackages']['carpsettings']['config'])) {
2758
		$config['installedpackages']['carpsettings']['config'][0]['username'] = config_get_path('system/username');
2759
		config_del_path('system/username');
2760
	}
2761
}
2762

    
2763
function upgrade_080_to_081() {
2764
	global $config;
2765
	global $g;
2766
	/* Welcome to the 2.1 migration path */
2767

    
2768
	/* tag all the existing gateways as being IPv4 */
2769
	$i = 0;
2770
	if (is_array($config['gateways']['gateway_item'])) {
2771
		foreach ($config['gateways']['gateway_item'] as $gw) {
2772
			$config['gateways']['gateway_item'][$i]['ipprotocol'] = "inet";
2773
			$i++;
2774
		}
2775
	}
2776

    
2777
	/* RRD files changed for quality, traffic and packets graphs */
2778
	/* convert traffic RRD file */
2779
	global $parsedcfg, $listtags;
2780
	$listtags = array("ds", "v", "rra", "row");
2781

    
2782
	$rrddbpath = "/var/db/rrd/";
2783
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2784

    
2785
	$rrdinterval = 60;
2786
	$valid = $rrdinterval * 2;
2787

    
2788
	/* Assume GigE for now */
2789
	$downstream = 125000000;
2790
	$upstream = 125000000;
2791

    
2792
	/* build a list of traffic and packets databases */
2793
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
2794
	rsort($databases);
2795
	foreach ($databases as $database) {
2796
		$xmldump = "{$database}.old.xml";
2797
		$xmldumpnew = "{$database}.new.xml";
2798

    
2799
		if (platform_booting()) {
2800
			echo "Migrate RRD database {$database} to new format for IPv6.\n";
2801
		}
2802

    
2803
		/* dump contents to xml and move database out of the way */
2804
		dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}");
2805

    
2806
		/* search and replace tags to add data sources */
2807
		$ds_search = "<!-- Round Robin Archives -->";
2808
		$ds_arr = array();
2809
		$ds_arr[] = "	<ds>
2810
				<name> inpass6 </name>
2811
				<type> COUNTER </type>
2812
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2813
				<min> 0.0000000000e+00 </min>
2814
				<max> 1.2500000000e+08 </max>
2815

    
2816
				<!-- PDP Status -->
2817
				<last_ds> 0 </last_ds>
2818
				<value> NaN </value>
2819
				<unknown_sec> 3 </unknown_sec>
2820
			</ds>
2821
			";
2822
		$ds_arr[] = "	<ds>
2823
				<name> outpass6 </name>
2824
				<type> COUNTER </type>
2825
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2826
				<min> 0.0000000000e+00 </min>
2827
				<max> 1.2500000000e+08 </max>
2828

    
2829
				<!-- PDP Status -->
2830
				<last_ds> 0 </last_ds>
2831
				<value> NaN </value>
2832
				<unknown_sec> 3 </unknown_sec>
2833
			</ds>
2834
			";
2835
		$ds_arr[] = "	<ds>
2836
				<name> inblock6 </name>
2837
				<type> COUNTER </type>
2838
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2839
				<min> 0.0000000000e+00 </min>
2840
				<max> 1.2500000000e+08 </max>
2841

    
2842
				<!-- PDP Status -->
2843
				<last_ds> 0 </last_ds>
2844
				<value> NaN </value>
2845
				<unknown_sec> 3 </unknown_sec>
2846
			</ds>
2847
			";
2848
		$ds_arr[] = "	<ds>
2849
				<name> outblock6 </name>
2850
				<type> COUNTER </type>
2851
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2852
				<min> 0.0000000000e+00 </min>
2853
				<max> 1.2500000000e+08 </max>
2854

    
2855
				<!-- PDP Status -->
2856
				<last_ds> 0 </last_ds>
2857
				<value> NaN </value>
2858
				<unknown_sec> 3 </unknown_sec>
2859
			</ds>
2860
			";
2861

    
2862
		$cdp_search = "<\/cdp_prep>";
2863
		$cdp_replace = "</cdp_prep>";
2864
		$cdp_arr = array();
2865
		$cdp_arr[] = "			<ds>
2866
					<primary_value> NaN </primary_value>
2867
					<secondary_value> 0.0000000000e+00 </secondary_value>
2868
					<value> NaN </value>
2869
					<unknown_datapoints> 0 </unknown_datapoints>
2870
					</ds>
2871
		";
2872
		$cdp_arr[] = "			<ds>
2873
					<primary_value> NaN </primary_value>
2874
					<secondary_value> 0.0000000000e+00 </secondary_value>
2875
					<value> NaN </value>
2876
					<unknown_datapoints> 0 </unknown_datapoints>
2877
					</ds>
2878
		";
2879
		$cdp_arr[] = "			<ds>
2880
					<primary_value> NaN </primary_value>
2881
					<secondary_value> 0.0000000000e+00 </secondary_value>
2882
					<value> NaN </value>
2883
					<unknown_datapoints> 0 </unknown_datapoints>
2884
					</ds>
2885
		";
2886
		$cdp_arr[] = "			<ds>
2887
					<primary_value> NaN </primary_value>
2888
					<secondary_value> 0.0000000000e+00 </secondary_value>
2889
					<value> NaN </value>
2890
					<unknown_datapoints> 0 </unknown_datapoints>
2891
					</ds>
2892
		";
2893

    
2894
		$value_search = "<\/row>";
2895
		$value_replace = "</row>";
2896
		$value = "<v> NaN </v>";
2897

    
2898
		$xml = file_get_contents("{$g['tmp_path']}/{$xmldump}");
2899
		foreach ($ds_arr as $ds) {
2900
			$xml = preg_replace("/$ds_search/s", "$ds{$ds_search}", $xml);
2901
		}
2902
		foreach ($cdp_arr as $cdp) {
2903
			$xml = preg_replace("/$cdp_search/s", "$cdp{$cdp_replace}", $xml);
2904
		}
2905
		foreach ($ds_arr as $ds) {
2906
			$xml = preg_replace("/$value_search/s", "$value{$value_replace}", $xml);
2907
		}
2908

    
2909
		file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", $xml);
2910
		mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1");
2911
		unset($xml);
2912
		# Default /tmp tmpfs is ~40mb, do not leave temp files around
2913
		unlink_if_exists("{$g['tmp_path']}/{$xmldump}");
2914
		unlink_if_exists("{$g['tmp_path']}/{$xmldumpnew}");
2915
	}
2916
	if (!platform_booting()) {
2917
		enable_rrd_graphing();
2918
	}
2919
	/* Let's save the RRD graphs after we run enable RRD graphing */
2920
	/* The function will restore the rrd.tgz so we will save it after */
2921
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
2922
	if (platform_booting()) {
2923
		echo "Updating configuration...";
2924
	}
2925
	foreach ($config['filter']['rule'] as & $rule) {
2926
		if (isset($rule['protocol']) && !empty($rule['protocol'])) {
2927
			$rule['protocol'] = strtolower($rule['protocol']);
2928
		}
2929
	}
2930
	unset($rule);
2931
}
2932

    
2933
function upgrade_081_to_082() {
2934
	/* don't enable the allow IPv6 toggle */
2935
}
2936

    
2937
function upgrade_082_to_083() {
2938
	global $config;
2939

    
2940
	/* Upgrade captiveportal config */
2941
	if (!empty($config['captiveportal'])) {
2942
		$tmpcp = config_get_path('captiveportal');
2943
		$config['captiveportal'] = array();
2944
		$config['captiveportal']['cpzone'] = array();
2945
		$config['captiveportal']['cpzone'] = $tmpcp;
2946
		$config['captiveportal']['cpzone']['zoneid'] = 8000;
2947
		$config['captiveportal']['cpzone']['zone'] = "cpzone";
2948
		if ($config['captiveportal']['cpzone']['auth_method'] == "radius") {
2949
			$config['captiveportal']['cpzone']['radius_protocol'] = "PAP";
2950
		}
2951
	}
2952
	if (!empty($config['voucher'])) {
2953
		$tmpcp = config_get_path('voucher');
2954
		$config['voucher'] = array();
2955
		$config['voucher']['cpzone'] = array();
2956
		$config['voucher']['cpzone'] = $tmpcp;
2957
	}
2958
}
2959

    
2960
function upgrade_083_to_084() {
2961
	global $config;
2962
	if (!isset($config['hasync'])) {
2963
		if (!empty($config['installedpackages']) &&
2964
		    !empty($config['installedpackages']['carpsettings']) &&
2965
		    !empty($config['installedpackages']['carpsettings']['config'])) {
2966
			$config['hasync'] = config_get_path('installedpackages/carpsettings/config/0');
2967
			config_del_path('installedpackages/carpsettings');
2968
		}
2969
		if (empty($config['installedpackages']['carpsettings']) && isset($config['installedpackages']['carpsettings'])) {
2970
			config_del_path('installedpackages/carpsettings');
2971
		}
2972
		if (empty($config['installedpackages']) && isset($config['installedpackages'])) {
2973
			config_del_path('installedpackages');
2974
		}
2975
	}
2976
}
2977

    
2978
function upgrade_084_to_085() {
2979
	global $config;
2980

    
2981
	$gateway_group_arr = array();
2982
	$gateways = return_gateways_array();
2983
	$oldnames = array();
2984
	/* setup translation array */
2985
	foreach ($gateways as $name => $gw) {
2986
		if (isset($gw['dynamic'])) {
2987
			$oldname = strtoupper($config['interfaces'][$gw['friendlyiface']]['descr']);
2988
			$oldnames[$oldname] = $name;
2989
		} else {
2990
			$oldnames[$name] = $name;
2991
		}
2992
	}
2993

    
2994
	/* process the old array */
2995
	if (is_array($config['gateways']['gateway_group'])) {
2996
		$group_array_new = array();
2997
		foreach ($config['gateways']['gateway_group'] as $name => $group) {
2998
			if (is_array($group['item'])) {
2999
				$newlist = array();
3000
				foreach ($group['item'] as $entry) {
3001
					$elements = explode("|", $entry);
3002
					if ($oldnames[$elements[0]] <> "") {
3003
						$newlist[] = "{$oldnames[$elements[0]]}|{$elements[1]}";
3004
					} else {
3005
						$newlist[] = "{$elements[0]}|{$elements[1]}";
3006
					}
3007
				}
3008
				$group['item'] = $newlist;
3009
				$group_array_new[$name] = $group;
3010
			}
3011
		}
3012
		$config['gateways']['gateway_group'] = $group_array_new;
3013
	}
3014
	/* rename old Quality RRD files in the process */
3015
	$rrddbpath = "/var/db/rrd";
3016
	foreach ($oldnames as $old => $new) {
3017
		if (is_readable("{$rrddbpath}/{$old}-quality.rrd")) {
3018
			@rename("{$rrddbpath}/{$old}-quality.rrd", "{$rrddbpath}/{$new}-quality.rrd");
3019
		}
3020
	}
3021
	unset($gateways, $oldnames, $gateway_group_arr);
3022
}
3023

    
3024
function upgrade_085_to_086() {
3025
	global $config, $g;
3026

    
3027
	/* XXX: Gross hacks in sight */
3028
	if (is_array($config['virtualip']['vip'])) {
3029
		$vipchg = array();
3030
		foreach ($config['virtualip']['vip'] as $vip) {
3031
			if ($vip['mode'] != "carp") {
3032
				continue;
3033
			}
3034
			$config = array_replace_values_recursive(
3035
				$config,
3036
				'^vip' . $vip['vhid'] . '$',
3037
				"{$vip['interface']}_vip{$vip['vhid']}"
3038
			);
3039
		}
3040
	}
3041
}
3042

    
3043
function upgrade_086_to_087() {
3044
	global $config, $dummynet_pipe_list;
3045

    
3046
	if (!is_array($config['dnshaper']) || !is_array($config['dnshaper']['queue'])) {
3047
		return;
3048
	}
3049

    
3050
	$dnqueue_number = 1;
3051
	$dnpipe_number = 1;
3052

    
3053
	foreach ($config['dnshaper']['queue'] as $idx => $dnpipe) {
3054
		$config['dnshaper']['queue'][$idx]['number'] = $dnpipe_number;
3055
		$dnpipe_number++;
3056
		if (is_array($dnpipe['queue'])) {
3057
			foreach ($dnpipe['queue'] as $qidx => $dnqueue) {
3058
				$config['dnshaper']['queue'][$idx]['queue'][$qidx]['number'] = $dnqueue_number;
3059
				$dnqueue_number++;
3060
			}
3061
		}
3062
	}
3063

    
3064
	unset($dnqueue_number, $dnpipe_number, $qidx, $idx, $dnpipe, $dnqueue);
3065

    
3066
	if (!is_array($config['filter']) || !is_array($config['filter']['rule'])) {
3067
		return;
3068
	}
3069

    
3070
	require_once("shaper.inc");
3071
	read_dummynet_config();
3072

    
3073
	$dn_list = array();
3074
	if (is_array($dummynet_pipe_list)) {
3075
		foreach ($dummynet_pipe_list as $dn) {
3076
			$tmplist =& $dn->get_queue_list();
3077
			foreach ($tmplist as $qname => $link) {
3078
				$dn_list[$link] = $qname;
3079
			}
3080
		}
3081
		unset($dummynet_pipe_list);
3082
	}
3083

    
3084
	foreach ($config['filter']['rule'] as $idx => $rule) {
3085
		if (!empty($rule['dnpipe'])) {
3086
			if (!empty($dn_list[$rule['dnpipe']])) {
3087
				$config['filter']['rule'][$idx]['dnpipe'] = $dn_list[$rule['dnpipe']];
3088
			}
3089
		}
3090
		if (!empty($rule['pdnpipe'])) {
3091
			if (!empty($dn_list[$rule['pdnpipe']])) {
3092
				$config['filter']['rule'][$idx]['pdnpipe'] = $dn_list[$rule['pdnpipe']];
3093
			}
3094
		}
3095
	}
3096
}
3097
function upgrade_087_to_088() {
3098
	global $config;
3099
	if (isset($config['system']['glxsb_enable'])) {
3100
		config_del_path('system/glxsb_enable');
3101
		$config['system']['crypto_hardware'] = "glxsb";
3102
	}
3103
}
3104

    
3105
function upgrade_088_to_089() {
3106
	global $config;
3107
	if (!is_array($config['ca'])) {
3108
		$config['ca'] = array();
3109
	}
3110
	if (!is_array($config['cert'])) {
3111
		$config['cert'] = array();
3112
	}
3113

    
3114
	/* migrate captive portal ssl to certificate manager */
3115
	if (is_array($config['captiveportal'])) {
3116
		foreach ($config['captiveportal'] as $id => &$setting) {
3117
			if (isset($setting['httpslogin'])) {
3118
				/* create cert entry */
3119
				$cert = array();
3120
				$cert['refid'] = uniqid();
3121
				$cert['descr'] = "Captive Portal Cert - {$setting['zone']}";
3122
				$cert['crt'] = $setting['certificate'];
3123
				$cert['prv'] = $setting['private-key'];
3124

    
3125
				if (!empty($setting['cacertificate'])) {
3126
					/* create ca entry */
3127
					$ca = array();
3128
					$ca['refid'] = uniqid();
3129
					$ca['descr'] = "Captive Portal CA - {$setting['zone']}";
3130
					$ca['crt'] = $setting['cacertificate'];
3131
					$config['ca'][] = $ca;
3132

    
3133
					/* add ca reference to certificate */
3134
					$cert['caref'] = $ca['refid'];
3135
				}
3136

    
3137
				$config['cert'][] = $cert;
3138

    
3139
				/* create cert reference */
3140
				$setting['certref'] = $cert['refid'];
3141

    
3142
				unset($setting['certificate']);
3143
				unset($setting['private-key']);
3144
				unset($setting['cacertificate']);
3145

    
3146
			}
3147
		}
3148
	}
3149
}
3150

    
3151
function upgrade_089_to_090() {
3152
	global $config;
3153
	if (is_array($config['load_balancer']['virtual_server']) && count($config['load_balancer']['virtual_server'])) {
3154
		$vs_a = &$config['load_balancer']['virtual_server'];
3155
		for ($i = 0; isset($vs_a[$i]); $i++) {
3156
			if (is_array($vs_a[$i]['pool'])) {
3157
				$vs_a[$i]['poolname'] = $vs_a[$i]['pool'][0];
3158
				unset($vs_a[$i]['pool']);
3159
			} elseif (!empty($vs_a[$i]['pool'])) {
3160
				$vs_a[$i]['poolname'] = $vs_a[$i]['pool'];
3161
				unset($vs_a[$i]['pool']);
3162
			}
3163
		}
3164
	}
3165
}
3166

    
3167
function upgrade_090_to_091() {
3168
	global $config;
3169

    
3170
	if (is_array($config['dnshaper']) && is_array($config['dnshaper']['queue'])) {
3171
		foreach ($config['dnshaper']['queue'] as $idx => $dnqueue) {
3172
			if (!empty($dnqueue['bandwidth'])) {
3173
				$bw = array();
3174
				$bw['bw'] = $dnqueue['bandwidth'];
3175
				$bw['bwscale'] = $dnqueue['bandwidthtype'];
3176
				$bw['bwsched'] = "none";
3177
				$config['dnshaper']['queue'][$idx]['bandwidth'] = array();
3178
				$config['dnshaper']['queue'][$idx]['bandwidth']['item'] = array();
3179
				$config['dnshaper']['queue'][$idx]['bandwidth']['item'][] = $bw;
3180
			}
3181
		}
3182
	}
3183
}
3184

    
3185
function upgrade_091_to_092() {
3186
	global $config;
3187

    
3188
	if (is_array($config['nat']['advancedoutbound']['rule'])) {
3189
		$nat_rules = &$config['nat']['advancedoutbound']['rule'];
3190
		for ($i = 0; isset($nat_rules[$i]); $i++) {
3191
			if (empty($nat_rules[$i]['interface'])) {
3192
				$nat_rules[$i]['interface'] = 'wan';
3193
			}
3194
		}
3195
	}
3196
}
3197

    
3198
function upgrade_092_to_093() {
3199
	global $g;
3200

    
3201
	$suffixes = array("concurrent", "loggedin");
3202

    
3203
	foreach ($suffixes as $suffix) {
3204
		if (file_exists("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd")) {
3205
			rename("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd",
3206
				"{$g['vardb_path']}/rrd/captiveportal-cpZone-{$suffix}.rrd");
3207
		}
3208
	}
3209

    
3210
	if (!platform_booting()) {
3211
		enable_rrd_graphing();
3212
	}
3213
}
3214

    
3215
function upgrade_093_to_094() {
3216
	global $config;
3217

    
3218
	if (isset($config['system']['powerd_mode'])) {
3219
		$config['system']['powerd_ac_mode'] = config_get_path('system/powerd_mode');
3220
		$config['system']['powerd_battery_mode'] = config_get_path('system/powerd_mode');
3221
		config_del_path('system/powerd_mode');
3222
	}
3223
}
3224

    
3225
function upgrade_094_to_095() {
3226
	global $config;
3227

    
3228
	if (!isset($config['interfaces']) || !is_array($config['interfaces'])) {
3229
		return;
3230
	}
3231

    
3232
	foreach ($config['interfaces'] as $iface => $cfg) {
3233
		if (isset($cfg['ipaddrv6']) && ($cfg['ipaddrv6'] == "track6")) {
3234
			if (!isset($cfg['track6-prefix-id']) || ($cfg['track6-prefix-id'] == "")) {
3235
				$config['interfaces'][$iface]['track6-prefix-id'] = 0;
3236
			}
3237
		}
3238
	}
3239
}
3240

    
3241
function upgrade_095_to_096() {
3242
	global $config, $g;
3243

    
3244
	$names = array("inpass", "outpass", "inblock", "outblock",
3245
		"inpass6", "outpass6", "inblock6", "outblock6");
3246
	$rrddbpath = "/var/db/rrd";
3247
	$rrdtool = "/usr/local/bin/rrdtool";
3248

    
3249
	/* Assume 2*10GigE for now */
3250
	$stream = 2500000000;
3251

    
3252
	/* build a list of traffic and packets databases */
3253
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
3254
	rsort($databases);
3255
	foreach ($databases as $database) {
3256
		if (platform_booting()) {
3257
			echo "Update RRD database {$database}.\n";
3258
		}
3259

    
3260
		$cmd = "{$rrdtool} tune {$rrddbpath}/{$database}";
3261
		foreach ($names as $name) {
3262
			$cmd .= " -a {$name}:{$stream}";
3263
		}
3264
		mwexec("{$cmd} 2>&1");
3265

    
3266
	}
3267
	if (!platform_booting()) {
3268
		enable_rrd_graphing();
3269
	}
3270
	/* Let's save the RRD graphs after we run enable RRD graphing */
3271
	/* The function will restore the rrd.tgz so we will save it after */
3272
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
3273
}
3274

    
3275
function upgrade_096_to_097() {
3276
	global $config, $g;
3277
	/* If the user had disabled default block rule logging before, then bogon/private network logging was already off, so respect their choice. */
3278
	if (isset($config['syslog']['nologdefaultblock'])) {
3279
		$config['syslog']['nologbogons'] = true;
3280
		$config['syslog']['nologprivatenets'] = true;
3281
	}
3282
}
3283

    
3284
function upgrade_097_to_098() {
3285
	// no longer used (used to set kill_states)
3286
	return;
3287
}
3288

    
3289
function upgrade_098_to_099() {
3290
	global $config;
3291

    
3292
	if (empty($config['dhcpd']) || !is_array($config['dhcpd'])) {
3293
		return;
3294
	}
3295

    
3296
	foreach ($config['dhcpd'] as & $dhcpifconf) {
3297
		if (isset($dhcpifconf['next-server'])) {
3298
			$dhcpifconf['nextserver'] = $dhcpifconf['next-server'];
3299
			unset($dhcpifconf['next-server']);
3300
		}
3301
	}
3302
}
3303

    
3304
function upgrade_099_to_100() {
3305
	require_once("/etc/inc/services.inc");
3306
	/* See #7146 for detail on why the extra parameters are needed for the time being. */
3307
	install_cron_job("/usr/bin/nice -n20 newsyslog", false, null, null, null, null, null, null, false);
3308
}
3309

    
3310
function upgrade_100_to_101() {
3311
	global $config, $g;
3312

    
3313
	if (!is_array($config['voucher'])) {
3314
		return;
3315
	}
3316

    
3317
	foreach ($config['voucher'] as $cpzone => $cp) {
3318
		if (!is_array($cp['roll'])) {
3319
			continue;
3320
		}
3321
		foreach ($cp['roll'] as $ridx => $rcfg) {
3322
			if (!empty($rcfg['comment'])) {
3323
				$config['voucher'][$cpzone]['roll'][$ridx]['descr'] = $rcfg['comment'];
3324
			}
3325
		}
3326
	}
3327
}
3328

    
3329
function upgrade_101_to_102() {
3330
	global $config, $g;
3331

    
3332
	if (is_array($config['captiveportal'])) {
3333
		foreach ($config['captiveportal'] as $cpzone => $cp) {
3334
			if (!is_array($cp['passthrumac'])) {
3335
				continue;
3336
			}
3337

    
3338
			foreach ($cp['passthrumac'] as $idx => $passthrumac) {
3339
				$config['captiveportal'][$cpzone]['passthrumac'][$idx]['action'] = 'pass';
3340
			}
3341
		}
3342
	}
3343

    
3344
	/* Convert OpenVPN Compression option to the new style */
3345
	// Nothing to do if there is no OpenVPN tag
3346
	if (isset($config['openvpn']) && is_array($config['openvpn'])) {
3347
		if (is_array($config['openvpn']['openvpn-server'])) {
3348
			foreach ($config['openvpn']['openvpn-server'] as &$vpn) {
3349
				if (!empty($vpn['compression'])) {
3350
					$vpn['compression'] = "adaptive";
3351
				}
3352
			}
3353
		}
3354
		if (is_array($config['openvpn']['openvpn-client'])) {
3355
			foreach ($config['openvpn']['openvpn-client'] as &$vpn) {
3356
				if (!empty($vpn['compression'])) {
3357
					$vpn['compression'] = "adaptive";
3358
				}
3359
			}
3360
		}
3361
	}
3362
}
3363

    
3364
function upgrade_102_to_103() {
3365
	global $config;
3366

    
3367
	if (isset($config['nat']['advancedoutbound']['enable'])) {
3368
		$config['nat']['advancedoutbound']['mode'] = "advanced";
3369
		config_del_path('nat/advancedoutbound/enable');
3370
	} else {
3371
		$config['nat']['advancedoutbound']['mode'] = "automatic";
3372
	}
3373

    
3374
	$config['nat']['outbound'] = config_get_path('nat/advancedoutbound');
3375

    
3376
	if (isset($config['nat']['ipsecpassthru'])) {
3377
		config_del_path('nat/ipsecpassthru');
3378
	}
3379
	if (isset($config['nat']['advancedoutbound'])) {
3380
		config_del_path('nat/advancedoutbound');
3381
	}
3382
}
3383

    
3384
function upgrade_103_to_104() {
3385
	global $config;
3386

    
3387
	$changed_privs = array(
3388
		"page-diag-system-activity" => "page-diagnostics-system-activity",
3389
		"page-interfacess-groups" => "page-interfaces-groups",
3390
		"page-interfacess-lagg" => "page-interfaces-lagg",
3391
		"page-interfacess-qinq" => "page-interfaces-qinq"
3392
	);
3393

    
3394
	/* update user privileges */
3395
	foreach ($config['system']['user'] as & $user) {
3396
		if (!is_array($user['priv'])) {
3397
			continue;
3398
		}
3399
		foreach ($user['priv'] as & $priv) {
3400
			if (array_key_exists($priv, $changed_privs)) {
3401
				$priv = $changed_privs[$priv];
3402
			}
3403
		}
3404
	}
3405

    
3406
	/* update group privileges */
3407
	foreach ($config['system']['group'] as & $group) {
3408
		if (!is_array($group['priv'])) {
3409
			continue;
3410
		}
3411
		foreach ($group['priv'] as & $priv) {
3412
			if (array_key_exists($priv, $changed_privs)) {
3413
				$priv = $changed_privs[$priv];
3414
			}
3415
		}
3416
	}
3417

    
3418
	/* sync all local account information */
3419
	local_reset_accounts();
3420
}
3421

    
3422
function upgrade_104_to_105() {
3423
	global $config;
3424

    
3425
	if (is_array($config['captiveportal'])) {
3426
		$zoneid = 2;
3427
		foreach ($config['captiveportal'] as $cpzone => $cpcfg) {
3428
			if (empty($cpcfg['zoneid'])) {
3429
				$config['captiveportal'][$cpzone]['zoneid'] = $zoneid;
3430
				$zoneid += 2;
3431
			} else if ($cpcfg['zoneid'] > 4000) {
3432
				$config['captiveportal'][$cpzone]['zoneid'] = $zoneid;
3433
				$zoneid += 2;
3434
			}
3435
		}
3436
	}
3437
}
3438

    
3439
function upgrade_105_to_106() {
3440
	/* NOTE: This upgrade code was reverted. See redmine ticket #3967 and
3441
	   https://github.com/pfsense/pfsense/commit/6f55af1c25f5232ffe905a90f5f97aad4c87bdfa */
3442
}
3443

    
3444
function upgrade_106_to_107() {
3445
	global $config;
3446

    
3447
	if (is_array($config['filter']) && is_array($config['filter']['rule'])) {
3448
		$tracker = (int)microtime(true);
3449
		foreach ($config['filter']['rule'] as $ridx => $rule) {
3450
			if (empty($rule['tracker'])) {
3451
				$config['filter']['rule'][$ridx]['tracker'] = $tracker;
3452
				$tracker++;
3453
			}
3454
		}
3455
		unset($tracker, $ridx);
3456
	}
3457
	if (is_array($config['nat']) && is_array($config['nat']['rule'])) {
3458
		$tracker = (int)microtime(true);
3459
		foreach ($config['nat']['rule'] as $ridx => $rule) {
3460
			if (empty($rule['tracker'])) {
3461
				$config['nat']['rule'][$ridx]['tracker'] = $tracker;
3462
				$tracker++;
3463
			}
3464
		}
3465
		unset($tracker, $ridx);
3466
	}
3467
}
3468

    
3469
function upgrade_107_to_108() {
3470
	global $config;
3471

    
3472
	if (isset($config['system']['webgui']['noautocomplete'])) {
3473
		config_del_path('system/webgui/noautocomplete');
3474
	} else {
3475
		$config['system']['webgui']['loginautocomplete'] = true;
3476
	}
3477
}
3478

    
3479
function upgrade_108_to_109() {
3480
	global $config;
3481

    
3482
	if (!isset($config['filter']['rule']) || !is_array($config['filter']['rule'])) {
3483
		return;
3484
	}
3485

    
3486
	foreach ($config['filter']['rule'] as &$rule) {
3487
		if (!isset($rule['dscp']) || empty($rule['dscp'])) {
3488
			continue;
3489
		}
3490

    
3491
		$pos = strpos($rule['dscp'], ' ');
3492
		if ($pos !== false) {
3493
			$rule['dscp'] = substr($rule['dscp'], 0, $pos);
3494
		}
3495
		unset($pos);
3496
	}
3497
}
3498

    
3499
function upgrade_109_to_110() {
3500
	global $config;
3501

    
3502
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3503
		return;
3504
	}
3505

    
3506
	foreach ($config['ipsec']['phase2'] as &$rule) {
3507
		if (!empty($rule['uniqid'])) {
3508
			continue;
3509
		}
3510

    
3511
		$rule['uniqid'] = uniqid();
3512
	}
3513
}
3514

    
3515
function upgrade_110_to_111() {
3516
	global $config;
3517

    
3518
	/* Make sure unbound user exist */
3519
	mwexec('/usr/sbin/pw groupadd -n unbound -g 59', true);
3520
	mwexec('/usr/sbin/pw useradd -n unbound -c "Unbound DNS Resolver" -d /var/unbound -s /usr/sbin/nologin -u 59 -g 59', true);
3521

    
3522
	/* cleanup old unbound package stuffs */
3523
	unlink_if_exists("/usr/local/pkg/unbound.xml");
3524
	unlink_if_exists("/usr/local/pkg/unbound.inc");
3525
	unlink_if_exists("/usr/local/pkg/unbound_advanced.xml");
3526
	unlink_if_exists("/usr/local/www/unbound_status.php");
3527
	unlink_if_exists("/usr/local/www/unbound_acls.php");
3528
	unlink_if_exists("/usr/local/bin/unbound_monitor.sh");
3529
	unlink_if_exists("/usr/local/etc/rc.d/unbound.sh");
3530

    
3531
	/* Remove old menu and service entries */
3532
	if (isset($config['installedpackages']['menu']) && is_array($config['installedpackages']['menu'])) {
3533
		foreach ($config['installedpackages']['menu'] as $idx => $menu) {
3534
			if ($menu['name'] != 'Unbound DNS') {
3535
				continue;
3536
			}
3537

    
3538
			config_del_path("installedpackages/menu/{$idx}");
3539
			break;
3540
		}
3541
	}
3542

    
3543
	if (isset($config['installedpackages']['service']) && is_array($config['installedpackages']['service'])) {
3544
		foreach ($config['installedpackages']['service'] as $idx => $service) {
3545
			if ($service['name'] != 'unbound') {
3546
				continue;
3547
			}
3548
			config_del_path("installedpackages/service/{$idx}");
3549
			break;
3550
		}
3551
	}
3552

    
3553
	if (!isset($config['installedpackages']['unbound']['config'][0])) {
3554
		return;
3555
	}
3556

    
3557
	$pkg = config_get_path('installedpackages/unbound/config/0');
3558

    
3559
	if (isset($config['installedpackages']['unboundadvanced']['config'][0])) {
3560
		$pkg = array_merge($pkg, $config['installedpackages']['unboundadvanced']['config'][0]);
3561
	}
3562

    
3563
	$new = array();
3564

    
3565
	/* deal first with boolean fields */
3566
	$fields = array(
3567
		"enable" => "enable",
3568
		"dnssec_status" => "dnssec",
3569
		"forwarding_mode" => "forwarding",
3570
		"regdhcp" => "regdhcp",
3571
		"regdhcpstatic" => "regdhcpstatic",
3572
		"txtsupport" => "txtsupport",
3573
		"hide_id" => "hideidentity",
3574
		"hide_version" => "hideversion",
3575
		"prefetch" => "prefetch",
3576
		"prefetch_key" => "prefetchkey",
3577
		"harden_glue" => "hardenglue",
3578
		"harden_dnssec_stripped" => "dnssec_stripped");
3579

    
3580
	foreach ($fields as $oldk => $newk) {
3581
		if (isset($pkg[$oldk])) {
3582
			if ($pkg[$oldk] == 'on') {
3583
				$new[$newk] = true;
3584
			}
3585
			unset($pkg[$oldk]);
3586
		}
3587
	}
3588

    
3589
	$fields = array(
3590
		"active_interface" => "network_interface",
3591
		"query_interface" => "outgoing_interface",
3592
		"unbound_verbosity" => "log_verbosity",
3593
		"msg_cache_size" => "msgcachesize",
3594
		"outgoing_num_tcp" => "outgoing_num_tcp",
3595
		"incoming_num_tcp" => "incoming_num_tcp",
3596
		"edns_buffer_size" => "edns_buffer_size",
3597
		"num_queries_per_thread" => "num_queries_per_thread",
3598
		"jostle_timeout" => "jostle_timeout",
3599
		"cache_max_ttl" => "cache_max_ttl",
3600
		"cache_min_ttl" => "cache_min_ttl",
3601
		"infra_host_ttl" => "infra_host_ttl",
3602
		"infra_cache_numhosts" => "infra_cache_numhosts",
3603
		"unwanted_reply_threshold" => "unwanted_reply_threshold",
3604
		"custom_options" => "custom_options");
3605

    
3606
	foreach ($fields as $oldk => $newk) {
3607
		if (isset($pkg[$oldk])) {
3608
			$new[$newk] = $pkg[$oldk];
3609
			unset($pkg[$oldk]);
3610
		}
3611
	}
3612

    
3613
	if (isset($new['custom_options']) && !empty($new['custom_options'])) {
3614
		$new['custom_options'] = str_replace("\r\n", "\n", $new['custom_options']);
3615
	}
3616

    
3617
	/* Following options were removed, bring them as custom_options */
3618
	if (isset($pkg['stats']) && $pkg['stats'] == "on") {
3619
		if (isset($pkg['stats_interval'])) {
3620
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "statistics-interval: {$pkg['stats_interval']}";
3621
		}
3622
		if (isset($pkg['cumulative_stats'])) {
3623
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "statistics-cumulative: {$pkg['cumulative_stats']}";
3624
		}
3625
		if (isset($pkg['extended_stats']) && $pkg['extended_stats'] == "on") {
3626
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "extended-statistics: yes";
3627
		} else {
3628
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "extended-statistics: no";
3629
		}
3630
	}
3631

    
3632
	$new['acls'] = array();
3633
	if (isset($config['installedpackages']['unboundacls']['config']) &&
3634
	    is_array($config['installedpackages']['unboundacls']['config'])) {
3635
		foreach ($config['installedpackages']['unboundacls']['config'] as $acl) {
3636
			$new['acls'][] = $acl;
3637
		}
3638
	}
3639

    
3640
	$config['unbound'] = $new;
3641

    
3642
	if (isset($config['installedpackages']['unbound'])) {
3643
		config_del_path('installedpackages/unbound');
3644
	}
3645
	if (isset($config['installedpackages']['unboundadvanced'])) {
3646
		config_del_path('installedpackages/unboundadvanced');
3647
	}
3648
	if (isset($config['installedpackages']['unboundacls'])) {
3649
		config_del_path('installedpackages/unboundacls');
3650
	}
3651

    
3652
	unset($pkg, $new);
3653
}
3654

    
3655
function upgrade_111_to_112() {
3656
	global $config;
3657

    
3658
	$config['cron']['item'][] = array(
3659
		'minute' => '*/60',
3660
		'hour' => '*',
3661
		'mday' => '*',
3662
		'month' => '*',
3663
		'wday' => '*',
3664
		'who' => 'root',
3665
		'command' => '/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 webConfiguratorlockout'
3666
	);
3667
}
3668

    
3669
function upgrade_112_to_113() {
3670
	global $config;
3671

    
3672
	if (isset($config['notifications']['smtp']['ssl'])) {
3673
		if ($config['notifications']['smtp']['ssl'] == "checked") {
3674
			$config['notifications']['smtp']['ssl'] = true;
3675
		} else {
3676
			config_del_path('notifications/smtp/ssl');
3677
		}
3678
	}
3679

    
3680
	if (isset($config['notifications']['smtp']['tls'])) {
3681
		if ($config['notifications']['smtp']['tls'] == "checked") {
3682
			$config['notifications']['smtp']['tls'] = true;
3683
		} else {
3684
			config_del_path('notifications/smtp/tls');
3685
		}
3686
	}
3687
}
3688

    
3689
function upgrade_113_to_114() {
3690
	global $config;
3691

    
3692
	if (!isset($config['ipsec']['phase1']) ||
3693
	    !is_array($config['ipsec']['phase1'])) {
3694
		return;
3695
	}
3696

    
3697
	foreach ($config['ipsec']['phase1'] as &$ph1ent) {
3698
		if (!isset($ph1ent['iketype'])) {
3699
			$ph1ent['iketype'] = 'ikev1';
3700
		}
3701
	}
3702
}
3703

    
3704
function upgrade_114_to_115() {
3705
	global $config;
3706

    
3707
	if (isset($config['unbound']['custom_options'])) {
3708
		$config['unbound']['custom_options'] = base64_encode($config['unbound']['custom_options']);
3709
	}
3710
}
3711

    
3712
function upgrade_115_to_116() {
3713
	global $config;
3714

    
3715
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3716
		return;
3717
	}
3718

    
3719
	$keyid = 1;
3720
	foreach ($config['ipsec']['phase2'] as $idx => $ph2) {
3721
		$config['ipsec']['phase2'][$idx]['reqid'] = $keyid;
3722
		$keyid++;
3723
	}
3724
}
3725

    
3726
function upgrade_116_to_117() {
3727
	global $config;
3728

    
3729
	if (!isset($config['ipsec']['client']) ||
3730
	    !isset($config['ipsec']['client']['dns_split']) ||
3731
	    empty($config['ipsec']['client']['dns_split'])) {
3732
		return;
3733
	}
3734

    
3735
	$config['ipsec']['client']['dns_split'] =
3736
		preg_replace('/\s*,\s*/', ' ', trim($config['ipsec']['client']['dns_split']));
3737

    
3738
}
3739

    
3740
function upgrade_117_to_118() {
3741
	global $config;
3742

    
3743
	// Unset any old CA and Cert in the system section that might still be there from when upgrade_066_to_067 did not unset them.
3744
	if (isset($config['system']['ca'])) {
3745
		config_del_path('system/ca');
3746
	}
3747
	if (isset($config['system']['cert'])) {
3748
		config_del_path('system/cert');
3749
	}
3750

    
3751
	init_config_arr(array('ipsec', 'phase1'));
3752
	$a_phase1 = &$config['ipsec']['phase1'];
3753

    
3754
	foreach ($a_phase1 as &$ph1_entry) {
3755
		// update asn1dn strings from racoon's format to strongswan's
3756
		if (isset($ph1_entry['myid_type']) && $ph1_entry['myid_type'] == 'asn1dn') {
3757
			$ph1_entry['myid_data'] =
3758
			    preg_replace('/\/\s*emailAddress\s*=\s*/', ', E=', $ph1_entry['myid_data']);
3759
		}
3760
		if (isset($ph1_entry['peerid_type']) && $ph1_entry['peerid_type'] == 'asn1dn') {
3761
			$ph1_entry['peerid_data'] =
3762
			    preg_replace('/\/\s*emailAddress\s*=\s*/', ', E=', $ph1_entry['peerid_data']);
3763
		}
3764
	}
3765
}
3766

    
3767
function upgrade_118_to_119() {
3768
	global $config;
3769

    
3770
	if (!isset($config['ipsec']['phase1'])) {
3771
		return;
3772
	}
3773

    
3774
	// change peerid_type to 'any' for EAP types to retain previous behavior of omitting rightid
3775
	init_config_arr(array('ipsec', 'phase1'));
3776
	$a_phase1 = &$config['ipsec']['phase1'];
3777

    
3778
	foreach ($a_phase1 as &$ph1_entry) {
3779
		if (strstr($ph1_entry['authentication_method'], 'eap')) {
3780
			$ph1_entry['peerid_type'] = "any";
3781
		}
3782
	}
3783
}
3784

    
3785
function upgrade_119_to_120() {
3786
	require_once("ipsec.inc");
3787
	global $config, $ipsec_log_cats;
3788

    
3789
	if (!is_array($config['ipsec'])) {
3790
		return;
3791
	}
3792

    
3793
	// add 1 to configured log levels as part of redmine #5340
3794
	foreach ($ipsec_log_cats as $lkey => $ldescr) {
3795
		if (isset($config['ipsec']["ipsec_{$lkey}"])) {
3796
			$config['ipsec']["ipsec_{$lkey}"] = $config['ipsec']["ipsec_{$lkey}"] + 1;
3797
		}
3798
	}
3799

    
3800
}
3801

    
3802

    
3803
function upgrade_120_to_121() {
3804
	global $config;
3805

    
3806
	if (!isset($config['installedpackages']['miniupnpd']['config'][0])) {
3807
		return;
3808
	}
3809

    
3810
	$miniupnpd = &$config['installedpackages']['miniupnpd']['config'][0];
3811

    
3812
	$miniupnpd['row'] = array();
3813

    
3814
	for ($i = 1; $i <= 4; $i++) {
3815
		if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) {
3816
			$miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]);
3817
		}
3818
		unset($miniupnpd["permuser{$i}"]);
3819
	}
3820
}
3821

    
3822
function upgrade_121_to_122() {
3823
	global $config;
3824
	foreach ($config['system']['user'] as &$user) {
3825
		if (isset($user['nt-hash'])) {
3826
			unset($user['nt-hash']);
3827
		}
3828
	}
3829
}
3830

    
3831
function upgrade_122_to_123() {
3832
	global $config;
3833

    
3834
	// PPTP server was removed
3835
	if (isset($config['pptpd'])) {
3836
		config_del_path('pptpd');
3837
	}
3838

    
3839
	// Cleanup firewall rules
3840
	if (isset($config['filter']['rule']) && is_array($config['filter']['rule'])) {
3841
		$rules = &$config['filter']['rule'];
3842
		$last_rule = count($rules) - 1;
3843
		// Process in reverse order to be able to unset items
3844
		for ($i = $last_rule; $i >= 0; $i--) {
3845
			if (isset($rules[$i]['interface']) && $rules[$i]['interface'] == 'pptp') {
3846
				config_del_path("filter/rule/{$i}");
3847
				continue;
3848
			}
3849
			if (isset($rules[$i]['source']['network']) && $rules[$i]['source']['network'] == 'pptp') {
3850
				config_del_path("filter/rule/{$i}");
3851
				continue;
3852
			}
3853
			if (isset($rules[$i]['destination']['network']) && $rules[$i]['destination']['network'] == 'pptp') {
3854
				config_del_path("filter/rule/{$i}");
3855
				continue;
3856
			}
3857
		}
3858
	}
3859

    
3860
	// Cleanup 1:1 NAT rules
3861
	if (isset($config['nat']['onetoone']) && is_array($config['nat']['onetoone'])) {
3862
		$onetoone = &$config['nat']['onetoone'];
3863
		$last_rule = count($onetoone) - 1;
3864
		// Process in reverse order to be able to unset items
3865
		for ($i = $last_rule; $i >= 0; $i--) {
3866
			if (isset($onetoone[$i]['interface']) && $onetoone[$i]['interface'] == 'pptp') {
3867
				config_del_path("nat/onetoone/{$i}");
3868
				continue;
3869
			}
3870
			if (isset($onetoone[$i]['source']['network']) && $onetoone[$i]['source']['network'] == 'pptp') {
3871
				config_del_path("nat/onetoone/{$i}");
3872
				continue;
3873
			}
3874
			if (isset($onetoone[$i]['destination']['network']) && $onetoone[$i]['destination']['network'] == 'pptp') {
3875
				config_del_path("nat/onetoone/{$i}");
3876
				continue;
3877
			}
3878
		}
3879
	}
3880

    
3881
	// Cleanup npt NAT rules
3882
	if (isset($config['nat']['npt']) && is_array($config['nat']['npt'])) {
3883
		$npt = &$config['nat']['npt'];
3884
		$last_rule = count($npt) - 1;
3885
		// Process in reverse order to be able to unset items
3886
		for ($i = $last_rule; $i >= 0; $i--) {
3887
			if (isset($npt[$i]['interface']) && $npt[$i]['interface'] == 'pptp') {
3888
				config_del_path("nat/npt/{$i}");
3889
				continue;
3890
			}
3891
		}
3892
	}
3893

    
3894
	// Cleanup Port-forward NAT rules
3895
	if (isset($config['nat']['rule']) && is_array($config['nat']['rule'])) {
3896
		$nat_rules = &$config['nat']['rule'];
3897
		$last_rule = count($nat_rules) - 1;
3898
		// Process in reverse order to be able to unset items
3899
		for ($i = $last_rule; $i >= 0; $i--) {
3900
			if (isset($nat_rules[$i]['interface']) && $nat_rules[$i]['interface'] == 'pptp') {
3901
				config_del_path("nat/rule/{$i}");
3902
				continue;
3903
			}
3904
			if (isset($nat_rules[$i]['source']['network']) && $nat_rules[$i]['source']['network'] == 'pptp') {
3905
				config_del_path("nat/rule/{$i}");
3906
				continue;
3907
			}
3908
			if (isset($nat_rules[$i]['destination']['network']) && $nat_rules[$i]['destination']['network'] == 'pptp') {
3909
				config_del_path("nat/rule/{$i}");
3910
				continue;
3911
			}
3912
		}
3913
	}
3914

    
3915
	// Cleanup Port-forward NAT rules
3916
	if (isset($config['nat']['outbound']['rule']) && is_array($config['nat']['outbound']['rule'])) {
3917
		$out_rules = &$config['nat']['outbound']['rule'];
3918
		$last_rule = count($out_rules) - 1;
3919
		// Process in reverse order to be able to unset items
3920
		for ($i = $last_rule; $i >= 0; $i--) {
3921
			if (isset($out_rules[$i]['interface']) && $out_rules[$i]['interface'] == 'pptp') {
3922
				config_del_path("nat/outbound/rule/{$i}");
3923
				continue;
3924
			}
3925
		}
3926
	}
3927
}
3928

    
3929
function upgrade_123_to_124() {
3930
	if (isset($config['system']['altpkgrepo'])) {
3931
		config_del_path('system/altpkgrepo');
3932
	}
3933

    
3934
	if (isset($config['theme'])) {
3935
		config_del_path('theme');
3936
	}
3937
}
3938

    
3939
function upgrade_124_to_125() {
3940
	global $config;
3941

    
3942
	/* Find interfaces with WEP configured. */
3943
	foreach ($config['interfaces'] as $ifname => $intf) {
3944
		if (!is_array($intf['wireless'])) {
3945
			continue;
3946
		}
3947

    
3948
		/* Generate a notice, disable interface, remove WEP settings */
3949
		if (isset($intf['wireless']['wep']['enable'])) {
3950
			if (!function_exists("file_notice")) {
3951
				require_once("notices.inc");
3952
			}
3953
			file_notice("WirelessSettings", sprintf(gettext("WEP is no longer supported. It will be disabled on the %s interface and the interface will be disabled. Please reconfigure the interface."), $ifname));
3954
			config_del_path("interfaces/{$ifname}/wireless/wep");
3955
			if (isset($intf['enable'])) {
3956
				config_del_path("interfaces/{$ifname}/enable");
3957
			}
3958
		}
3959
	}
3960
}
3961

    
3962
function upgrade_125_to_126() {
3963
	require_once("ipsec.inc");
3964
	global $config, $ipsec_log_cats, $ipsec_log_sevs;
3965

    
3966
	$def_loglevel = 1;
3967
	if (!is_array($config['ipsec'])) {
3968
		return;
3969
	}
3970

    
3971
	if (!isset($config['ipsec']['logging']) || !is_array($config['ipsec']['logging'])) {
3972
		$config['ipsec']['logging'] = array();
3973
	}
3974

    
3975
	/* subtract 2 from ipsec log levels. the value stored in the config.xml
3976
	 * will now match the strongswan level exactly.
3977
	 */
3978
	foreach (array_keys($ipsec_log_cats) as $cat) {
3979
		if (!isset($config['ipsec']["ipsec_{$cat}"])) {
3980
			$new_level = $def_loglevel;
3981
		} else {
3982
			$new_level = intval($config['ipsec']["ipsec_{$cat}"]) - 2;
3983
		}
3984

    
3985
		if (in_array($new_level, array_keys($ipsec_log_sevs))) {
3986
			$config['ipsec']['logging'][$cat] = $new_level;
3987
		} else {
3988
			$config['ipsec']['logging'][$cat] = $def_loglevel;
3989
		}
3990
		config_del_path("ipsec/ipsec_{$cat}");
3991
	}
3992
}
3993

    
3994
// prior to v2.3 <widgets><sequence> contains a list of widgets with display types:
3995
//		none, close, hide, & show
3996
// v2.3 & later uses:
3997
//		close & open
3998
// widgets not in use are simply not in the list
3999
function upgrade_126_to_127() {
4000
	global $config;
4001

    
4002
	if (!isset($config['widgets']['sequence'])) {
4003
		return;
4004
	}
4005

    
4006
	$cur_widgets = explode(',', trim($config['widgets']['sequence']));
4007
	$new_widgets = array();
4008

    
4009
	foreach ($cur_widgets as $widget) {
4010
		list($file, $col, $display) = explode(':', $widget);
4011

    
4012
		switch ($display) {
4013
			case 'hide':
4014
				$display = 'close';
4015
				break;
4016
			case 'show':
4017
				$display = 'open';
4018
				break;
4019
			case 'open':
4020
				break;
4021
			default:
4022
				continue 2;
4023
		}
4024

    
4025
		/* Remove '-container' from widget name */
4026
		$file = preg_replace('/-container$/', '', $file);
4027

    
4028
		$new_widgets[] = "{$file}:{$col}:{$display}";
4029
	}
4030

    
4031
	$config['widgets']['sequence'] = implode(',', $new_widgets);
4032

    
4033
}
4034

    
4035
function upgrade_127_to_128() {
4036
	global $config;
4037

    
4038
	// If bindip is not already specified then migrate the old SNMP bindlan flag to a bindip setting
4039
	if (isset($config['snmpd']['bindlan'])) {
4040
		if (!isset($config['snmpd']['bindip'])) {
4041
			$config['snmpd']['bindip'] = 'lan';
4042
		}
4043
		config_del_path('snmpd/bindlan');
4044
	}
4045
}
4046

    
4047
function upgrade_128_to_129() {
4048
	global $config;
4049

    
4050
	/* net.inet.ip.fastforwarding does not exist in 2.3. */
4051
	if (!isset($config['sysctl']['item']) ||
4052
	    !is_array($config['sysctl']['item'])) {
4053
		return;
4054
	}
4055

    
4056
	foreach ($config['sysctl']['item'] as $idx => $sysctl) {
4057
		if ($sysctl['tunable'] == "net.inet.ip.fastforwarding") {
4058
			config_del_path("sysctl/item/{$idx}");
4059
		}
4060
		if ($sysctl['tunable'] == "net.inet.ipsec.debug") {
4061
			$config['sysctl']['item'][$idx]['value'] = "0";
4062
		}
4063
	}
4064

    
4065
	/* IPSEC is always on in 2.3. */
4066
	if (isset($config['ipsec']['enable'])) {
4067
		config_del_path('ipsec/enable');
4068
	} else if (is_array($config['ipsec']['phase1'])) {
4069
		/*
4070
		 * If IPsec was globally disabled, disable all
4071
		 * phase1 entries
4072
		 */
4073
		foreach ($config['ipsec']['phase1'] as $idx => $p1) {
4074
			$config['ipsec']['phase1'][$idx]['disabled'] = true;
4075
		}
4076
	}
4077
}
4078

    
4079
function upgrade_129_to_130() {
4080
	global $config;
4081

    
4082
	/* Change OpenVPN topology_subnet checkbox into topology multi-select #5526 */
4083
	if (is_array($config['openvpn']) && is_array($config['openvpn']['openvpn-server'])) {
4084
		foreach ($config['openvpn']['openvpn-server'] as & $serversettings) {
4085
			if (strtolower($serversettings['topology_subnet']) == "yes") {
4086
				unset($serversettings['topology_subnet']);
4087
				$serversettings['topology'] = "subnet";
4088
			} else {
4089
				$serversettings['topology'] = "net30";
4090
			}
4091
		}
4092
	}
4093
}
4094

    
4095
function upgrade_130_to_131() {
4096
	global $config;
4097

    
4098
	// Default dpinger parameters at time of this upgrade (2.3)
4099
	$default_interval = 500;
4100
	$default_alert_interval = 1000;
4101
	$default_loss_interval = 2000;
4102
	$default_time_period = 60000;
4103

    
4104
	if (isset($config['syslog']['apinger'])) {
4105
		$config['syslog']['dpinger'] = true;
4106
		config_del_path('syslog/apinger');
4107
	}
4108

    
4109
	if (isset($config['system']['apinger_debug'])) {
4110
		config_del_path('system/apinger_debug');
4111
	}
4112

    
4113
	if (!isset($config['gateways']['gateway_item']) ||
4114
	    !is_array($config['gateways']['gateway_item'])) {
4115
		return;
4116
	}
4117

    
4118
	if (is_array($config['gateways']['gateway_item'])) {
4119
		foreach ($config['gateways']['gateway_item'] as &$gw) {
4120
			// dpinger uses milliseconds
4121
			if (isset($gw['interval']) &&
4122
				is_numeric($gw['interval'])) {
4123
				$gw['interval'] = $gw['interval'] * 1000;
4124
			}
4125

    
4126
			if (isset($gw['interval'])) {
4127
				$effective_interval = $gw['interval'];
4128
			} else {
4129
				$effective_interval = $default_interval;
4130
			}
4131

    
4132
			if (isset($gw['down']) &&
4133
				is_numeric($gw['down'])) {
4134
				$gw['time_period'] = $gw['down'] * 1000;
4135
				unset($gw['down']);
4136
			}
4137

    
4138
			if (isset($gw['time_period'])) {
4139
				$effective_time_period = $gw['time_period'];
4140
			} else {
4141
				$effective_time_period = $default_time_period;
4142
			}
4143

    
4144
			if (isset($gw['latencyhigh'])) {
4145
				// Default loss_interval is 2000, but must be set
4146
				// higher if latencyhigh is higher.
4147
				if ($gw['latencyhigh'] > $default_loss_interval) {
4148
					$gw['loss_interval'] = $gw['latencyhigh'];
4149
				}
4150
			}
4151

    
4152
			if (isset($gw['loss_interval'])) {
4153
				$effective_loss_interval = $gw['loss_interval'];
4154
			} else {
4155
				$effective_loss_interval = $default_loss_interval;
4156
			}
4157

    
4158
			if (isset($gw['interval'])) {
4159
				// Default alert_interval is 1000, but must be set
4160
				// higher if interval is higher.
4161
				if ($gw['interval'] > $default_alert_interval) {
4162
					$gw['alert_interval'] = $gw['interval'];
4163
				}
4164
			}
4165

    
4166
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4167
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4168
			}
4169

    
4170
			if (isset($gw['avg_delay_samples'])) {
4171
				unset($gw['avg_delay_samples']);
4172
			}
4173
			if (isset($gw['avg_delay_samples_calculated'])) {
4174
				unset($gw['avg_delay_samples_calculated']);
4175
			}
4176
			if (isset($gw['avg_loss_samples'])) {
4177
				unset($gw['avg_loss_samples']);
4178
			}
4179
			if (isset($gw['avg_loss_samples_calculated'])) {
4180
				unset($gw['avg_loss_samples_calculated']);
4181
			}
4182
			if (isset($gw['avg_loss_delay_samples'])) {
4183
				unset($gw['avg_loss_delay_samples']);
4184
			}
4185
			if (isset($gw['avg_loss_delay_samples_calculated'])) {
4186
				unset($gw['avg_loss_delay_samples_calculated']);
4187
			}
4188
		}
4189
	}
4190
}
4191

    
4192
function upgrade_131_to_132() {
4193
	global $config;
4194
	if (isset($config['system']['usefifolog'])) {
4195
		config_del_path('system/usefifolog');
4196
		clear_all_log_files(false);
4197
	}
4198
}
4199

    
4200
function upgrade_132_to_133() {
4201
	global $config;
4202

    
4203
	if (isset($config['ipsec']['phase1']) &&
4204
	    is_array($config['ipsec']['phase1'])) {
4205
		foreach ($config['ipsec']['phase1'] as &$p1) {
4206
			if (isset($p1['encryption-algorithm']['name']) &&
4207
			    $p1['encryption-algorithm']['name'] == 'des') {
4208
				$p1['disabled'] = true;
4209
				file_notice("IPsec",
4210
				    sprintf(gettext("DES is no longer supported, IPsec phase 1 item '%s' is being disabled."), $p1['descr']));
4211
			}
4212
		}
4213
	}
4214

    
4215
	if (isset($config['ipsec']['phase2']) &&
4216
	    is_array($config['ipsec']['phase2'])) {
4217
		foreach ($config['ipsec']['phase2'] as &$p2) {
4218
			if (!isset($p2['encryption-algorithm-option']) ||
4219
			    !is_array($p2['encryption-algorithm-option'])) {
4220
				continue;
4221
			}
4222

    
4223
			foreach ($p2['encryption-algorithm-option'] as $ealgo) {
4224
				if ($ealgo['name'] == 'des') {
4225
					$p2['disabled'] = true;
4226
					file_notice("IPsec",
4227
					    sprintf(gettext("DES is no longer supported, IPsec phase 2 item '%s' is being disabled."), $p2['descr']));
4228
				}
4229
			}
4230
		}
4231
	}
4232
}
4233

    
4234
// Determine the highest column number in use and set dashboardcolumns accordingly
4235
function upgrade_133_to_134() {
4236
	global $config;
4237

    
4238
	if (!isset($config['widgets']['sequence']) || isset($config['system']['webgui']['dashboardcolumns'])) {
4239
		return;
4240
	}
4241

    
4242
	$cur_widgets = explode(',', trim($config['widgets']['sequence']));
4243
	$maxcols = 2;
4244

    
4245
	foreach ($cur_widgets as $widget) {
4246
		list($file, $col, $display) = explode(':', $widget);
4247

    
4248
		if (($display != 'none') && ($display != 'hide')) {
4249
			preg_match('#[0-9]+$#', $col, $column);
4250
			if ($column[0] > $maxcols) {
4251
				$maxcols = $column[0];
4252
			}
4253
		}
4254
	}
4255

    
4256
	$config['system']['webgui']['dashboardcolumns'] = $maxcols % 10;
4257
}
4258

    
4259
function upgrade_134_to_135() {
4260
	global $config;
4261

    
4262
	if (isset($config['syslog']['nologlighttpd'])) {
4263
		config_del_path('syslog/nologlighttpd');
4264
		$config['syslog']['nolognginx'] = true;
4265
	}
4266
}
4267

    
4268
function upgrade_135_to_136() {
4269
	global $config;
4270

    
4271
	$l7_active = false;
4272
	if (isset($config['l7shaper'])) {
4273
		config_del_path('l7shaper');
4274
		if (is_array($config['filter']['rule'])) {
4275
			foreach ($config['filter']['rule'] as $idx => $rule) {
4276
				if (isset($rule['l7container'])) {
4277
					config_del_path("filter/rule/{$idx}/l7container");
4278
					$l7_active = true;
4279
				}
4280
			}
4281
		}
4282
		if ($l7_active) {
4283
			file_notice("L7shaper", gettext("Layer 7 shaping is no longer supported. Its configuration has been removed."));
4284
		}
4285
	}
4286
}
4287

    
4288
function upgrade_136_to_137() {
4289
	global $config;
4290

    
4291
	if (is_array($config['dhcpd'])) {
4292
		foreach ($config['dhcpd'] as &$dhcpd) {
4293
			if (!is_array($dhcpd['numberoptions']['item'])) {
4294
				continue;
4295
			}
4296

    
4297
			foreach ($dhcpd['numberoptions']['item'] as &$item) {
4298
				$item['value'] = base64_encode($item['value']);
4299
			}
4300
		}
4301
	}
4302

    
4303
	if (is_array($config['dhcpdv6'])) {
4304
		foreach ($config['dhcpdv6'] as &$dhcpdv6) {
4305
			if (!is_array($dhcpdv6['numberoptions']['item'])) {
4306
				continue;
4307
			}
4308

    
4309
			foreach ($dhcpdv6['numberoptions']['item'] as &$item) {
4310
				$item['value'] = base64_encode($item['value']);
4311
			}
4312
		}
4313
	}
4314
}
4315

    
4316
function upgrade_137_to_138() {
4317
	global $config;
4318

    
4319
	// the presence of unityplugin tag used to disable loading of unity plugin
4320
	// it's now disabled by default, and config tag is to enable. Unset accordingly.
4321
	if (is_array($config['ipsec'])) {
4322
		if (isset($config['ipsec']['unityplugin'])) {
4323
			config_del_path('ipsec/unityplugin');
4324
		}
4325
	}
4326
}
4327

    
4328
function upgrade_138_to_139() {
4329
	global $config;
4330

    
4331
	// clean up state killing on gateway failure. having kill_states set used to mean it was disabled
4332
	// now set gw_down_kill_states if enabled.
4333
	if (!isset($config['system']['kill_states'])) {
4334
		$config['system']['gw_down_kill_states'] = true;
4335
	} else {
4336
		config_del_path('system/kill_states');
4337
	}
4338
}
4339

    
4340
function upgrade_139_to_140() {
4341
	global $config;
4342

    
4343
	if (is_array($config['virtualip']['vip'])) {
4344
		foreach ($config['virtualip']['vip'] as $idx => $vip) {
4345
			if ($vip['mode'] == "carp") {
4346
				if (!isset($vip['uniqid'])) {
4347
					$config['virtualip']['vip'][$idx]['uniqid'] = uniqid();
4348
				}
4349
			}
4350
		}
4351
	}
4352
}
4353

    
4354
function upgrade_140_to_141() {
4355
	global $config;
4356

    
4357
	// retain OpenVPN's net30 default topology for upgraded client configs so they still work
4358
	// This is for 2.3 ALPHA to a later 2.3, not 2.2.x upgrades, which had no topology setting on clients
4359
	if (is_array($config['openvpn']) && is_array($config['openvpn']['openvpn-client'])) {
4360
		foreach ($config['openvpn']['openvpn-client'] as $idx => $ovpnclient) {
4361
			if (!isset($ovpnclient['topology'])) {
4362
				$config['openvpn']['openvpn-client'][$idx]['topology'] = "net30";
4363
			}
4364
		}
4365
	}
4366

    
4367
	// repeat addition of filter tracker IDs from 106_to_107 where missing since associated filter rules were missing them
4368
	if (is_array($config['filter']) && is_array($config['filter']['rule'])) {
4369
		$tracker = (int)microtime(true);
4370
		foreach ($config['filter']['rule'] as $ridx => $rule) {
4371
			if (empty($rule['tracker'])) {
4372
				$config['filter']['rule'][$ridx]['tracker'] = $tracker;
4373
				$tracker++;
4374
			}
4375
		}
4376
		unset($tracker, $ridx);
4377
	}
4378

    
4379
}
4380

    
4381
function upgrade_141_to_142() {
4382
	global $config;
4383
	/* Convert Namecheap type DynDNS entries to the new split hostname and domain format */
4384

    
4385
	init_config_arr(array('dyndnses', 'dyndns'));
4386
	$a_dyndns = &$config['dyndnses']['dyndns'];
4387

    
4388
	foreach ($a_dyndns as &$dyndns) {
4389
		if ($dyndns['type'] == "namecheap") {
4390
			/* Use the old style logic to split the host and domain one last time. */
4391
			$dparts = explode(".", trim($dyndns['host']));
4392
			$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
4393
			$domain_offset = count($dparts) - $domain_part_count;
4394
			$dyndns['host'] = implode(".", array_slice($dparts, 0, $domain_offset));
4395
			$dyndns['domainname'] = implode(".", array_slice($dparts, $domain_offset));
4396
		}
4397
	}
4398

    
4399
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
4400
	if (is_array($config['cron']['item'])) {
4401
		foreach ($config['cron']['item'] as $idx => $cronitem) {
4402
			if ($cronitem['command'] == "/etc/pppoerestart") {
4403
				config_del_path("cron/item/{$idx}");
4404
			}
4405
		}
4406
	}
4407
}
4408

    
4409
// Updated to check for empty separator definitions via is_array()
4410
function upgrade_142_to_143() {
4411
	global $config;
4412

    
4413
	/* Re-index firewall rule separators per interface */
4414
	if (is_array($config['filter']['separator'])) {
4415
		foreach ($config['filter']['separator'] as $interface => $separators) {
4416

    
4417
			if (is_array($separators)) {
4418
				foreach ($separators as $sepn => $separator) {
4419

    
4420
					$seprow = substr($separator['row']['0'], 2);
4421
					$sepif  = $separator['if'];
4422

    
4423
					// Determine position of separator within the interface rules.
4424
					$i = -1; $j = 0;
4425
					foreach ($config['filter']['rule'] as $rulen => $filterent) {
4426

    
4427
						if ($i == $seprow) {
4428
							// Set separator row to it's position within the interface rules.
4429
							$config['filter']['separator'][$sepif][$sepn]['row'] = 'fr' . $j;
4430
							continue 2;	// Advance to next separator
4431
						}
4432

    
4433
						// Position within the interface rules.
4434
						if (($filterent['interface'] == $sepif && !isset($filterent['floating'])) || (isset($filterent['floating']) && "floatingrules" == $sepif)) {
4435
							$j++;
4436
						}
4437
						$i++;
4438
					}
4439
				}
4440
			}
4441
		}
4442
	}
4443

    
4444
	/* Re-index nat rule separators */
4445
	if (is_array($config['nat']['separator'])) {
4446
		foreach ($config['nat']['separator'] as $sepn => $separator) {
4447
			if (is_array($separator)) {
4448
				$seprow = substr($separator['row']['0'], 2);
4449
				$config['nat']['separator'][$sepn]['row'] = 'fr' . ($seprow + 1);
4450
			}
4451
		}
4452
	}
4453
}
4454

    
4455
function get_vip_from_ip_alias($ipalias) {
4456
	global $config;
4457

    
4458
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4459
		if ($vip['mode'] != "ipalias") {
4460
			continue;
4461
		}
4462
		if ($ipalias == $vip['subnet']) {
4463
			return ("_vip{$vip['uniqid']}");
4464
		}
4465
	}
4466

    
4467
	return ($ipalias);
4468
}
4469

    
4470
function get_vip_from_oldcarp($carp) {
4471
	global $config;
4472

    
4473
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4474
		if ($vip['mode'] != "carp") {
4475
			continue;
4476
		}
4477
		if ($carp == "{$vip['interface']}_vip{$vip['vhid']}") {
4478
			return ("_vip{$vip['uniqid']}");
4479
		}
4480
	}
4481

    
4482
	return ($carp);
4483
}
4484

    
4485
function upgrade_143_to_144() {
4486
	global $config;
4487

    
4488
	if (is_array($config['virtualip']['vip'])) {
4489
		foreach ($config['virtualip']['vip'] as $idx => $vip) {
4490
			if ($vip['mode'] == "ipalias") {
4491
				if (!isset($vip['uniqid'])) {
4492
					$config['virtualip']['vip'][$idx]['uniqid'] = uniqid();
4493
				}
4494
			}
4495
		}
4496
	}
4497

    
4498
	/* Convert IPsec phase 1 entries. */
4499
	if (is_array($config['ipsec']['phase1'])) {
4500
		foreach ($config['ipsec']['phase1'] as $idx => $ph1ent) {
4501
			if (is_ipaddr($ph1ent['interface']) || is_ipaddrv6($ph1ent['interface'])) {
4502
				$config['ipsec']['phase1'][$idx]['interface'] = get_vip_from_ip_alias($ph1ent['interface']);
4503
			} else if (strpos($ph1ent['interface'], "_vip")) {
4504
				$config['ipsec']['phase1'][$idx]['interface'] = get_vip_from_oldcarp($ph1ent['interface']);
4505
			}
4506
		}
4507
	}
4508

    
4509
	/* Convert openvpn. */
4510
	if (is_array($config['openvpn']['openvpn-server'])) {
4511
		foreach ($config['openvpn']['openvpn-server'] as $idx => $ovpn) {
4512
			if (empty($ovpn['interface'])) {
4513
				continue;
4514
			}
4515
			if (is_ipaddr($ovpn['interface']) || is_ipaddrv6($ovpn['interface'])) {
4516
				$config['openvpn']['openvpn-server'][$idx]['interface'] = get_vip_from_ip_alias($ovpn['interface']);
4517
			} else if (strpos($ovpn['interface'], "_vip")) {
4518
				$config['openvpn']['openvpn-server'][$idx]['interface'] = get_vip_from_oldcarp($ovpn['interface']);
4519
			}
4520
		}
4521
	}
4522
	if (is_array($config['openvpn']['openvpn-client'])) {
4523
		foreach ($config['openvpn']['openvpn-client'] as $idx => $ovpn) {
4524
			if (empty($ovpn['interface'])) {
4525
				continue;
4526
			}
4527
			if (is_ipaddr($ovpn['interface']) || is_ipaddrv6($ovpn['interface'])) {
4528
				$config['openvpn']['openvpn-client'][$idx]['interface'] = get_vip_from_ip_alias($ovpn['interface']);
4529
			} else if (strpos($ovpn['interface'], "_vip")) {
4530
				$config['openvpn']['openvpn-client'][$idx]['interface'] = get_vip_from_oldcarp($ovpn['interface']);
4531
			}
4532
		}
4533
	}
4534

    
4535
	/* Convert unbound. */
4536
	if (is_array($config['unbound']) && !empty($config['unbound']['active_interface'])) {
4537
		$active_ifs = explode(",", $config['unbound']['active_interface']);
4538
		$ifs = array();
4539
		foreach ($active_ifs as $if) {
4540
			if (is_ipaddr($if) || is_ipaddrv6($if)) {
4541
				$ifs[] = get_vip_from_ip_alias($if);
4542
			} else if (strpos($if, "_vip")) {
4543
				$ifs[] = get_vip_from_oldcarp($if);
4544
			} else {
4545
				$ifs[] = $if;
4546
			}
4547
		}
4548
		$config['unbound']['active_interface'] = implode(",", $ifs);
4549
	}
4550

    
4551
	/* Convert dnsmasq. */
4552
	if (is_array($config['dnsmasq']) && !empty($config['dnsmasq']['interface'])) {
4553
		$active_ifs = explode(",", $config['dnsmasq']['interface']);
4554
		$ifs = array();
4555
		foreach ($active_ifs as $if) {
4556
			if (is_ipaddr($if) || is_ipaddrv6($if)) {
4557
				$ifs[] = get_vip_from_ip_alias($if);
4558
			} else if (strpos($if, "_vip")) {
4559
				$ifs[] = get_vip_from_oldcarp($if);
4560
			} else {
4561
				$ifs[] = $if;
4562
			}
4563
		}
4564
		$config['dnsmasq']['interface'] = implode(",", $ifs);
4565
	}
4566
}
4567

    
4568
function upgrade_144_to_145() {
4569
	global $config;
4570

    
4571
	// Enable DHCPv6 server and radvd config for track6 interfaces,
4572
	// matching what used to be automatically enabled with no user
4573
	// configurability.
4574
	if (is_array($config['interfaces'])) {
4575
		foreach ($config['interfaces'] as $ifname => $ifcfg) {
4576
			if (isset($ifcfg['enable'])) {
4577
				if ($ifcfg['ipaddrv6'] == "track6") {
4578
					init_config_arr(array('dhcpdv6', $ifname, 'range'));
4579
					$config['dhcpdv6'][$ifname]['enable'] = true;
4580
					$config['dhcpdv6'][$ifname]['range']['from'] = "::1000";
4581
					$config['dhcpdv6'][$ifname]['range']['to'] = "::2000";
4582
					$config['dhcpdv6'][$ifname]['ramode'] = "assist";
4583
					$config['dhcpdv6'][$ifname]['rapriority'] = "medium";
4584
				}
4585
			}
4586
		}
4587
	}
4588
}
4589

    
4590
function upgrade_145_to_146() {
4591
	// Add standard deviation to the quality rrds
4592
	global $config, $g;
4593

    
4594
	$rrddbpath = "/var/db/rrd";
4595
	$rrdtool = "/usr/local/bin/rrdtool";
4596

    
4597
	$awkcmd = "/usr/bin/awk '";
4598
	$awkcmd .= "{\n";
4599
	$awkcmd .= "    if (sub(/<\\/v><\\/row>/, \"</v><v>NaN</v></row>\") == 0)\n";
4600
	$awkcmd .= "    {\n";
4601
	$awkcmd .= "        if (/<\\/cdp_prep>/)\n";
4602
	$awkcmd .= "        {\n";
4603
	$awkcmd .= "            print \"			<ds>\"\n";
4604
	$awkcmd .= "            print \"			<primary_value> 0.0000000000e+00 </primary_value>\"\n";
4605
	$awkcmd .= "            print \"			<secondary_value> 0.0000000000e+00 </secondary_value>\"\n";
4606
	$awkcmd .= "            print \"			<value> NaN </value>\"\n";
4607
	$awkcmd .= "            print \"			<unknown_datapoints> 0 </unknown_datapoints>\"\n";
4608
	$awkcmd .= "            print \"			</ds>\"\n";
4609
	$awkcmd .= "        }\n";
4610
	$awkcmd .= "        else if (/<!-- Round Robin Archives -->/)\n";
4611
	$awkcmd .= "        {\n";
4612
	$awkcmd .= "            print \"	<ds>\"\n";
4613
	$awkcmd .= "            print \"		<name> stddev </name>\"\n";
4614
	$awkcmd .= "            print \"		<type> GAUGE </type>\"\n";
4615
	$awkcmd .= "            print \"		<minimal_heartbeat> 120 </minimal_heartbeat>\"\n";
4616
	$awkcmd .= "            print \"		<min> 0.0000000000e+00 </min>\"\n";
4617
	$awkcmd .= "            print \"		<max> 1.0000000000e+05 </max>\\n\"\n";
4618
	$awkcmd .= "            print \"		<!-- PDP Status -->\"\n";
4619
	$awkcmd .= "            print \"		<last_ds> 0 </last_ds>\"\n";
4620
	$awkcmd .= "            print \"		<value> 0.0000000000e+00 </value>\"\n";
4621
	$awkcmd .= "            print \"		<unknown_sec> 0 </unknown_sec>\"\n";
4622
	$awkcmd .= "            print \"	</ds>\\n\"\n";
4623
	$awkcmd .= "        }\n";
4624
	$awkcmd .= "    }\n";
4625
	$awkcmd .= "    print;\n";
4626
	$awkcmd .= "}'";
4627

    
4628
	$databases = return_dir_as_array($rrddbpath, '/-quality\.rrd$/');
4629
	foreach ($databases as $database) {
4630
		$xmldump = "{$g['tmp_path']}/{$database}.xml";
4631

    
4632
		if (platform_booting()) {
4633
			echo "Update RRD database {$database}.\n";
4634
		}
4635

    
4636
		exec("$rrdtool dump {$rrddbpath}/{$database} | {$awkcmd} > {$xmldump}");
4637
		exec("$rrdtool restore -f {$xmldump} {$rrddbpath}/{$database}");
4638
		@unlink("{$xmldump}");
4639
	}
4640

    
4641
	if (!platform_booting()) {
4642
		enable_rrd_graphing();
4643
	}
4644
	/* Let's save the RRD graphs after we run enable RRD graphing */
4645
	/* The function will restore the rrd.tgz so we will save it after */
4646
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
4647
}
4648

    
4649
function upgrade_bgpd_146_to_147() {
4650
	global $config;
4651

    
4652
	if (!isset($config['installedpackages']['openbgpd']['config']) ||
4653
	    !is_array($config['installedpackages']['openbgpd']['config'])) {
4654
		return;
4655
	}
4656
	$openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0];
4657
	if (!isset($openbgpd_conf['carpstatusip']) &&
4658
	    !is_ipaddr($openbgpd_conf['carpstatusip'])) {
4659
		return;
4660
	}
4661

    
4662
	if (!is_array($config['virtualip']['vip']))
4663
		return;
4664
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4665
		if ($vip['subnet'] == $openbgpd_conf['carpstatusip']) {
4666
			$openbgpd_conf['carpstatusvid'] = "_vip{$vip['uniqid']}";
4667
			unset($openbgpd_conf['carpstatusip']);
4668
			return;
4669
		}
4670
	}
4671
}
4672

    
4673
function upgrade_quagga_146_to_147() {
4674
	global $config;
4675

    
4676
	if (!isset($config['installedpackages']['quaggaospfd']['config']) ||
4677
	    !is_array($config['installedpackages']['quaggaospfd']['config'])) {
4678
		return;
4679
	}
4680
	$ospfd_conf = &$config['installedpackages']['quaggaospfd']['config'][0];
4681
	if (!isset($ospfd_conf['carpstatusip']) &&
4682
	    !is_ipaddr($ospfd_conf['carpstatusip'])) {
4683
		return;
4684
	}
4685

    
4686
	if (!is_array($config['virtualip']['vip']))
4687
		return;
4688
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4689
		if ($vip['subnet'] == $ospfd_conf['carpstatusip']) {
4690
			$ospfd_conf['carpstatusvid'] = "_vip{$vip['uniqid']}";
4691
			unset($ospfd_conf['carpstatusip']);
4692
			return;
4693
		}
4694
	}
4695
}
4696

    
4697
function upgrade_146_to_147() {
4698

    
4699
	upgrade_bgpd_146_to_147();
4700
	upgrade_quagga_146_to_147();
4701
}
4702

    
4703
function upgrade_147_to_148() {
4704
	global $config;
4705

    
4706
	// Ensure there are no spaces in group names by
4707
	// replacing spaces with underscores
4708
	if (is_array($config['system']['group'])) {
4709
		$cleargroups = false;
4710
		foreach ($config['system']['group'] as $idx => $grp) {
4711
			if (strstr($grp['name'], " ")) {
4712
				$cleargroups = true;
4713
				$config['system']['group'][$idx]['scope'] = "remote";
4714
			}
4715
		}
4716

    
4717
		// if there was a space in a group name, there may be multiple
4718
		// groups with the same name in the group file. To prevent pw
4719
		// from getting into a neverending loop, delete all user-defined
4720
		// groups here. local_reset_accounts will run shortly after this
4721
		// and add them back. redmine #6012
4722
		if ($cleargroups) {
4723
			foreach ($config['system']['group'] as $grp) {
4724
				mwexec("/usr/sbin/pw groupdel -g {$grp['gid']}");
4725
			}
4726
		}
4727
	}
4728
}
4729

    
4730
function upgrade_148_to_149() {
4731
	global $config;
4732
	global $altq_list_queues;
4733

    
4734
        if (!isset($config['shaper']['queue']) || !is_array($config['shaper']['queue']))
4735
                return;
4736

    
4737
	read_altq_config();
4738

    
4739
	/* Set root queue bandwidth. */
4740
	foreach ($altq_list_queues as $altq) {
4741
		$sum = $altq->GetTotalBw();
4742
		while ($sum > get_queue_bandwidth($altq)) {
4743
			if (intval(($sum / 1000) * 1.2) < (1024 * 1024)) {
4744
				/* 1Gb where possible. */
4745
				$bw = 1024 * 1024;
4746
			} else {
4747
				/* Increase by 20% until it fits. */
4748
				$bw = intval(($sum / 1000) * 1.2);
4749
			}
4750
			$altq->SetBandwidth($bw);
4751
			$altq->SetBwscale("Kb");
4752
			$altq->wconfig();
4753
			$sum = $altq->GetTotalBw();
4754
		}
4755
	}
4756
}
4757

    
4758
function upgrade_149_to_150() {
4759
	global $config;
4760

    
4761
	if (is_array($config['dhcpdv6'])) {
4762
                foreach ($config['dhcpdv6'] as &$dhcpdv6) {
4763
			if (isset($dhcpdv6['rainterface'])) {
4764
				if (strstr($dhcpdv6['rainterface'], "_vip")) {
4765
					$dhcpdv6['rainterface'] = get_vip_from_oldcarp($dhcpdv6['rainterface']);
4766
				}
4767
			}
4768
		}
4769
	}
4770
}
4771

    
4772
function upgrade_150_to_151() {
4773
	global $config;
4774

    
4775
	// Default dpinger parameters at time of this upgrade (2.3.1)
4776
	$default_interval = 500;
4777
	$default_alert_interval = 1000;
4778
	$default_loss_interval = 2000;
4779
	$default_time_period = 60000;
4780
	$default_latencyhigh = 500;
4781

    
4782
	// Check advanced gateway parameter relationships in case they are incorrect
4783
	if (is_array($config['gateways']['gateway_item'])) {
4784
		foreach ($config['gateways']['gateway_item'] as &$gw) {
4785
			if (isset($gw['interval'])) {
4786
				$effective_interval = $gw['interval'];
4787
			} else {
4788
				$effective_interval = $default_interval;
4789
			}
4790

    
4791
			if (isset($gw['alert_interval'])) {
4792
				$effective_alert_interval = $gw['alert_interval'];
4793
			} else {
4794
				$effective_alert_interval = $default_alert_interval;
4795
			}
4796

    
4797
			if (isset($gw['loss_interval'])) {
4798
				$effective_loss_interval = $gw['loss_interval'];
4799
			} else {
4800
				$effective_loss_interval = $default_loss_interval;
4801
			}
4802

    
4803
			if (isset($gw['time_period'])) {
4804
				$effective_time_period = $gw['time_period'];
4805
			} else {
4806
				$effective_time_period = $default_time_period;
4807
			}
4808

    
4809
			if (isset($gw['latencyhigh'])) {
4810
				$effective_latencyhigh = $gw['latencyhigh'];
4811
			} else {
4812
				$effective_latencyhigh = $default_latencyhigh;
4813
			}
4814

    
4815
			// Loss interval has to be at least as big as high latency.
4816
			if ($effective_latencyhigh > $effective_loss_interval) {
4817
				$effective_loss_interval = $gw['loss_interval'] = $effective_latencyhigh;
4818
			}
4819

    
4820
			// Alert interval has to be at least as big as probe interval.
4821
			if ($effective_interval > $effective_alert_interval) {
4822
				$gw['alert_interval'] = $effective_interval;
4823
			}
4824

    
4825
			// The time period for averaging has to be more than 2 probes plus the loss interval.
4826
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4827
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4828
			}
4829
		}
4830
	}
4831
}
4832

    
4833
function upgrade_151_to_152() {
4834
	global $g, $config;
4835

    
4836
	require_once("/etc/inc/services.inc");
4837

    
4838
	// Remove these cron jobs on full install if not using ramdisk.
4839
	if (!isset($config['system']['use_mfs_tmpvar'])) {
4840
		/* See #7146 for detail on why the extra parameters are needed for the time being. */
4841
		install_cron_job("/etc/rc.backup_rrd.sh", false, null, null, null, null, null, null, false);
4842
		install_cron_job("/etc/rc.backup_dhcpleases.sh", false, null, null, null, null, null, null, false);
4843
	}
4844
}
4845

    
4846
function upgrade_152_to_153() {
4847
	global $config;
4848

    
4849
	if (is_array($config['virtualip']['vip'])) {
4850
		foreach ($config['virtualip']['vip'] as $idx => $vip) {
4851
			if (substr($vip['interface'], 0, 4) == "_vip") {
4852
				// using new VIP format
4853
				continue;
4854
			} else if (strstr($vip['interface'], "_vip")) {
4855
				// using old VIP format, update
4856
				$config['virtualip']['vip'][$idx]['interface'] = get_vip_from_oldcarp($vip['interface']);
4857
			}
4858
		}
4859
	}
4860

    
4861
	// upgrade GIFs using VIP to new format
4862
	if (is_array($config['gifs']['gif'])) {
4863
		foreach ($config['gifs']['gif'] as $idx => $gif) {
4864
			if (substr($gif['if'], 0, 4) == "_vip") {
4865
				// using new VIP format
4866
				continue;
4867
			} else if (strstr($gif['if'], "_vip")) {
4868
				// using old VIP format, update
4869
				$config['gifs']['gif'][$idx]['if'] = get_vip_from_oldcarp($gif['if']);
4870
			}
4871
		}
4872
	}
4873

    
4874
	// upgrade GREs using VIP to new format
4875
	if (is_array($config['gres']['gre'])) {
4876
		foreach ($config['gres']['gre'] as $idx => $gre) {
4877
			if (substr($gre['if'], 0, 4) == "_vip") {
4878
				// using new VIP format
4879
				continue;
4880
			} else if (strstr($gre['if'], "_vip")) {
4881
				// using old VIP format, update
4882
				$config['gres']['gre'][$idx]['if'] = get_vip_from_oldcarp($gre['if']);
4883
			}
4884
		}
4885
	}
4886

    
4887
	// upgrade gateway groups using VIPs
4888
	if (is_array($config['gateways']['gateway_group'])) {
4889
		foreach ($config['gateways']['gateway_group'] as $idx => $gw) {
4890
			if (is_array($gw['item'])) {
4891
				$newitems = array();
4892
				$gwvipchange = false;
4893
				foreach ($gw['item'] as $item) {
4894
					if (strstr($item, "|_vip")) {
4895
						// using new VIP format
4896
						$newitems[] = $item;
4897
						continue;
4898
					} else if (strstr($item, "_vip")) {
4899
						// using old VIP format, update
4900
						$gwitemarr = explode("|", $item);
4901
						$gwitemarr[2] = get_vip_from_oldcarp($gwitemarr[2]);
4902
						$newitems[] = implode("|", $gwitemarr);
4903
						$gwvipchange = true;
4904
					} else {
4905
						$newitems[] = $item;
4906
					}
4907
				}
4908
				if ($gwvipchange) {
4909
					$config['gateways']['gateway_group'][$idx]['item'] = $newitems;
4910
				}
4911
			}
4912
		}
4913
	}
4914
}
4915

    
4916
function upgrade_153_to_154() {
4917
	/* NOTE: This upgrade code was reverted. See redmine ticket #6118 and
4918
	   https://github.com/pfsense/pfsense/commit/538a3c04a6b6671151e913b06b2f340b6f8ee222 */
4919
}
4920

    
4921
/* Clean up old GRE/GIF options. See Redmine tickets #6586 and #6587 */
4922
function upgrade_154_to_155() {
4923
	global $config;
4924

    
4925
	if (is_array($config['gifs']['gif'])) {
4926
		foreach ($config['gifs']['gif'] as $idx => $gif) {
4927
			if (isset($gif['link0'])) {
4928
				config_del_path("gifs/gif/{$idx}/link0");
4929
			}
4930
		}
4931
	}
4932

    
4933
	if (is_array($config['gres']['gre'])) {
4934
		foreach ($config['gres']['gre'] as $idx => $gre) {
4935
			if (isset($gre['link0'])) {
4936
				config_del_path("gres/gre/{$idx}/link0");
4937
			}
4938
			if (isset($gre['link2'])) {
4939
				config_del_path("gres/gre/{$idx}/link2");
4940
			}
4941
		}
4942
	}
4943
}
4944

    
4945
function upgrade_155_to_156() {
4946
	// Unused
4947
}
4948

    
4949
function upgrade_156_to_157() {
4950
	global $config;
4951
	/* Convert Cloudflare and GratisDNS type DynDNS entries to the new split hostname and domain format */
4952

    
4953
	init_config_arr(array('dyndnses', 'dyndns'));
4954
	$a_dyndns = &$config['dyndnses']['dyndns'];
4955

    
4956
	foreach ($a_dyndns as &$dyndns) {
4957
		if (($dyndns['type'] == "cloudflare") || ($dyndns['type'] == "cloudflare-v6") || ($dyndns['type'] == "gratisdns")) {
4958
			/* Use the old style logic to split the host and domain one last time. */
4959
			$dparts = explode(".", trim($dyndns['host']));
4960
			$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
4961
			$domain_offset = count($dparts) - $domain_part_count;
4962
			$dyndns['host'] = implode(".", array_slice($dparts, 0, $domain_offset));
4963
			$dyndns['domainname'] = implode(".", array_slice($dparts, $domain_offset));
4964
		}
4965
	}
4966

    
4967
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
4968
	if (is_array($config['cron']['item'])) {
4969
		foreach ($config['cron']['item'] as $idx => $cronitem) {
4970
			if ($cronitem['command'] == "/etc/pppoerestart") {
4971
				config_del_path("cron/item/{$idx}");
4972
			}
4973
		}
4974
	}
4975
}
4976

    
4977
function upgrade_157_to_158() {
4978
	global $config;
4979
	/* Convert Dynamic DNS passwords to base64 encoding. Redmine #6688 */
4980

    
4981
	init_config_arr(array('dyndnses', 'dyndns'));
4982
	$a_dyndns = &$config['dyndnses']['dyndns'];
4983

    
4984
	foreach ($a_dyndns as &$dyndns) {
4985
		$dyndns['password'] = base64_encode($dyndns['password']);
4986
	}
4987
}
4988

    
4989
/* Unset references to glxsb in the config. See #6755 */
4990
function upgrade_158_to_159() {
4991
	global $config;
4992

    
4993
	if ($config['system']['crypto_hardware'] == "glxsb") {
4994
		config_del_path('system/crypto_hardware');
4995
	}
4996
}
4997

    
4998
/* Convert OpenVPN "protocol" to new style for OpenVPN 2.4, old udp/tcp was
4999
 * IPv4 only, now is dual stack, so change it to udp4/tcp4
5000
 */
5001
function upgrade_159_to_160() {
5002
	global $config;
5003

    
5004
	if (isset($config['openvpn']) && is_array($config['openvpn'])) {
5005
		if (is_array($config['openvpn']['openvpn-server'])) {
5006
			foreach ($config['openvpn']['openvpn-server'] as &$vpn) {
5007
				if ($vpn['protocol'] == "UDP") {
5008
					$vpn['protocol'] = "UDP4";
5009
				}
5010
				if ($vpn['protocol'] == "TCP") {
5011
					$vpn['protocol'] = "TCP4";
5012
				}
5013
			}
5014
		}
5015
		if (is_array($config['openvpn']['openvpn-client'])) {
5016
			foreach ($config['openvpn']['openvpn-client'] as &$vpn) {
5017
				if ($vpn['protocol'] == "UDP") {
5018
					$vpn['protocol'] = "UDP4";
5019
				}
5020
				if ($vpn['protocol'] == "TCP") {
5021
					$vpn['protocol'] = "TCP4";
5022
				}
5023
			}
5024
		}
5025
	}
5026
}
5027

    
5028
/* RAM Disk Management */
5029
function upgrade_160_to_161() {
5030
	global $g, $config;
5031

    
5032
	if (!isset($config['system']['use_mfs_tmpvar'])) {
5033
		return;
5034
	}
5035

    
5036
	// Move existing RRD backup to the RAM Disk Store if it don't already exist there.
5037
	// Restore existing RRD XML dump backup.
5038
	if (file_exists("{$g['cf_conf_path']}/rrd.tgz") && !file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/rrd.tgz")) {
5039
		$rrddbpath = "{$g['vardb_path']}/rrd/";
5040
		$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
5041

    
5042
		$rrdrestore = "";
5043
		$rrdreturn = "";
5044
		unlink_if_exists("{$rrddbpath}/*.xml");
5045

    
5046
		unset($rrdrestore);
5047
		$_gb = exec("LANG=C /usr/bin/tar -tf {$g['cf_conf_path']}/rrd.tgz", $rrdrestore, $rrdreturn);
5048
		if ($rrdreturn != 0) {
5049
			log_error(sprintf(gettext('RRD restore failed exited with %1$s, the error is: %2$s'), $rrdreturn, $rrdrestore));
5050
		} else {
5051
			foreach ($rrdrestore as $xml_file) {
5052
				$rrd_file = '/' . substr($xml_file, 0, -4) . '.rrd';
5053
				unlink_if_exists("{$rrd_file}");
5054

    
5055
				file_put_contents("{$g['tmp_path']}/rrd_restore", $xml_file);
5056
				$_gb = exec("LANG=C /usr/bin/tar -xf {$g['cf_conf_path']}/rrd.tgz -C / -T {$g['tmp_path']}/rrd_restore");
5057
				if (!file_exists("/{$xml_file}")) {
5058
					log_error(sprintf(gettext("Could not extract %s RRD xml file from archive!"), $xml_file));
5059
					continue;
5060
				}
5061
				$_gb = exec("$rrdtool restore -f '/{$xml_file}' '{$rrd_file}'", $output, $status);
5062
				if ($status) {
5063
					log_error(sprintf(gettext("rrdtool restore -f '%1\$s' '%2\$s' failed returning %3\$s."), $xml_file, $rrd_file, $status));
5064
					continue;
5065
				}
5066
				unset($output);
5067
				@unlink("/{$xml_file}");
5068
			}
5069
			unset($rrdrestore);
5070
			@unlink("{$g['tmp_path']}/rrd_restore");
5071

    
5072
			// Create a new RRD backup to the RAM Disk Store (without RRD XML dump).
5073
			exec("/etc/rc.backup_rrd.sh");
5074
			$ramds_updated = true;
5075

    
5076
			// Rename previous RRD backup so it will not restore again.  Don't delete in case needed for recovery.
5077
			rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/rrd.tgz.old");
5078
		}
5079
	}
5080

    
5081
	// Move existing DHCP leases backup to the RAM Disk Store if it don't already exist there.
5082
	if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz") && ! file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/dhcpleases.tgz")) {
5083
		rename("{$g['cf_conf_path']}/dhcpleases.tgz", "{$g['cf_conf_path']}/RAM_Disk_Store/dhcpleases.tgz");
5084
		$ramds_updated = true;
5085
	}
5086

    
5087
	// Move existing alias table backups to the RAM Disk Store if they don't already exist there.
5088
	$dbpath = "{$g['vardb_path']}/aliastables/";
5089
	$files = glob("{$g['cf_conf_path']}/RAM_Disk_Store{$dbpath}*.tgz");
5090
	if (count($files)) {
5091
		foreach ($files as $file) {
5092
			if (! file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/".basename($file))) {
5093
				rename($file, "{$g['cf_conf_path']}/RAM_Disk_Store/".basename($file));
5094
				$ramds_updated = true;
5095
			}
5096
		}
5097
		// Remove existing alias table backups directory if empty.
5098
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/db/aliastables");
5099
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/db/");
5100
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/");
5101
	}
5102

    
5103
	// Restore RAM Disk Store if updated.
5104
	if ($ramds_updated) {
5105
		exec("/etc/rc.restore_ramdisk_store");
5106
	}
5107
}
5108

    
5109
/* Previous versions of pfSense had cryptodev built into the kernel.
5110
 * To retain the expected behavior on upgrade, load the cryptodev
5111
 * module for users that did not choose a module.
5112
 */
5113
function upgrade_161_to_162() {
5114
	global $config;
5115
	if (empty($config['system']['crypto_hardware'])) {
5116
		$config['system']['crypto_hardware'] = "cryptodev";
5117
	}
5118
}
5119

    
5120
/* Traffic graphs widget settings are now stored in a layout similar
5121
 * to other widgets. Migrate any old settings.
5122
 */
5123
function upgrade_162_to_163() {
5124
	require_once("ipsec.inc");
5125
	global $config;
5126

    
5127
	foreach (array('refreshinterval', 'invert', 'size', 'backgroundupdate') as $setting) {
5128
		if (isset($config['widgets']['trafficgraphs'][$setting])) {
5129
			$config['widgets']['traffic_graphs'][$setting] = config_get_path("widgets/trafficgraphs/{$setting}");
5130
			config_del_path("widgets/trafficgraphs/{$setting}");
5131
		}
5132
	}
5133

    
5134
	if (isset($config['widgets']['trafficgraphs']['shown'])) {
5135
		if (is_array($config['widgets']['trafficgraphs']['shown']['item'])) {
5136
			$ifdescrs = get_configured_interface_with_descr();
5137

    
5138
			if (ipsec_enabled()) {
5139
				$ifdescrs['enc0'] = "IPsec";
5140
			}
5141

    
5142
			$validNames = array();
5143

    
5144
			foreach ($ifdescrs as $ifdescr => $ifname) {
5145
				array_push($validNames, $ifdescr);
5146
			}
5147

    
5148
			$config['widgets']['traffic_graphs']['filter'] = implode(',', array_diff($validNames, $config['widgets']['trafficgraphs']['shown']['item']));
5149
		}
5150

    
5151
		config_del_path('widgets/trafficgraphs/shown');
5152
	}
5153
}
5154

    
5155
/* Dashboard widget settings config format has changed to support having possibly multiple
5156
 * of a widget on the dashboard. Migrate any old settings.
5157
 */
5158
function convert_widget_164($oldname, $newname, $settings_keys) {
5159
	global $config;
5160

    
5161
	if ($newname == '') {
5162
		$newname = $oldname . '-0';
5163
	}
5164

    
5165
	if ($oldname == '') {
5166
		// These settings were stored directly in $config['widgets']
5167
		// Move them down under their new key.
5168
		// e.g. $config['widgets']['filterlogentries']
5169
		// becomes $config['widgets']['log-0']['filterlogentries']
5170
		foreach ($settings_keys as $oldkey => $newkey) {
5171
			if ($newkey == '') {
5172
				$newkey = $oldkey;
5173
			}
5174

    
5175
			// Modify the system-wide entry
5176
			if (isset($config['widgets'][$oldkey])) {
5177
				$config['widgets'][$newname][$newkey] = config_get_path("widgets/{$oldkey}");
5178
				config_del_path("widgets/{$oldkey}");
5179
			}
5180

    
5181
			// Modify any user-specific entries
5182
			foreach ($config['system']['user'] as & $user) {
5183
				if (isset($user['widgets'][$oldkey])) {
5184
					$user['widgets'][$newname][$newkey] = $user['widgets'][$oldkey];
5185
					unset($user['widgets'][$oldkey]);
5186
				}
5187
			}
5188
		}
5189
	} else {
5190
		// These settings were stored in some key under 'widgets',
5191
		// e.g. $config['widgets']['gateways_widget']['display_type']
5192
		// becomes $config['widgets']['gateways-0']['display_type']
5193
		foreach ($settings_keys as $oldkey => $newkey) {
5194
			if ($newkey == '') {
5195
				$newkey = $oldkey;
5196
			}
5197

    
5198
			// Modify the system-wide entry
5199
			if (isset($config['widgets'][$oldname][$oldkey])) {
5200
				$config['widgets'][$newname][$newkey] = config_get_path("widgets/{$oldname}/{$oldkey}");
5201
				config_del_path("widgets/{$oldname}/{$oldkey}");
5202
			}
5203

    
5204
			// Modify any user-specific entries
5205
			foreach ($config['system']['user'] as & $user) {
5206
				if (isset($user['widgets'][$oldname][$oldkey])) {
5207
					$user['widgets'][$newname][$newkey] = $user['widgets'][$oldname][$oldkey];
5208
					unset($user['widgets'][$oldname][$oldkey]);
5209
				}
5210

    
5211
				if (isset($user['widgets'][$oldname])) {
5212
					unset($user['widgets'][$oldname]);
5213
				}
5214
			}
5215
		}
5216

    
5217
		if (isset($config['widgets'][$oldname])) {
5218
			config_del_path("widgets/{$oldname}");
5219
		}
5220
	}
5221
}
5222

    
5223
function upgrade_163_to_164() {
5224
	global $config;
5225

    
5226
	convert_widget_164('dyn_dns_status', '', array('filter' => ''));
5227
	convert_widget_164('gateways_widget', 'gateways-0', array('display_type' => '', 'gatewaysfilter' => ''));
5228
	convert_widget_164('interface_statistics', '', array('iffilter' => ''));
5229
	convert_widget_164('interfaces', '', array('iffilter' => ''));
5230
	convert_widget_164('', 'log-0',
5231
		array(
5232
			'filterlogentries' => '',
5233
			'filterlogentriesacts' => '',
5234
			'filterlogentriesinterfaces' => '',
5235
			'filterlogentriesinterval' => ''));
5236
	convert_widget_164('openvpn', '', array('filter' => ''));
5237
	convert_widget_164('', 'picture-0', array('picturewidget' => '', 'picturewidget_filename' => ''));
5238
	convert_widget_164('', 'rss-0', array('rssfeed' => '', 'rssmaxitems' => '', 'rsswidgetheight' => '', 'rsswidgettextlength' => ''));
5239
	convert_widget_164('', 'services_status-0', array('servicestatusfilter' => 'filter'));
5240
	convert_widget_164('smart_status', '', array('filter' => ''));
5241
	convert_widget_164('system_information', '', array('filter' => ''));
5242
	convert_widget_164('thermal_sensors_widget', 'thermal_sensors-0',
5243
		array(
5244
			'thermal_sensors_widget_zone_warning_threshold' => '',
5245
			'thermal_sensors_widget_zone_critical_threshold' => '',
5246
			'thermal_sensors_widget_core_warning_threshold' => '',
5247
			'thermal_sensors_widget_core_critical_threshold' => '',
5248
			'thermal_sensors_widget_show_raw_output' => '',
5249
			'thermal_sensors_widget_show_full_sensor_name' => '',
5250
			'thermal_sensors_widget_pulsate_warning' => '',
5251
			'thermal_sensors_widget_pulsate_critical' => ''
5252
		));
5253
	convert_widget_164('wol', 'wake_on_lan-0', array('filter' => ''));
5254
}
5255

    
5256
/* Work around broken wizard rules. See https://redmine.pfsense.org/issues/7434 */
5257
function upgrade_164_to_165() {
5258
	global $config;
5259
	foreach ($config['filter']['rule'] as & $rule) {
5260
		if ($rule['destination']['port'] == "137-139-137-139") {
5261
			$rule['destination']['port'] = "137-139";
5262
		}
5263
	}
5264
}
5265

    
5266
/* Fixup digest algorithm selection for OpenVPN clients and servers so they do not use aliased names. */
5267
function upgrade_165_to_166() {
5268
	require_once('openvpn.inc');
5269
	global $config;
5270

    
5271
	if (isset($config['openvpn']) && is_array($config['openvpn'])) {
5272
		if (is_array($config['openvpn']['openvpn-server'])) {
5273
			foreach ($config['openvpn']['openvpn-server'] as &$vpn) {
5274
				$vpn['digest'] = openvpn_remap_digest($vpn['digest']);
5275
			}
5276
		}
5277
		if (is_array($config['openvpn']['openvpn-client'])) {
5278
			foreach ($config['openvpn']['openvpn-client'] as &$vpn) {
5279
				$vpn['digest'] = openvpn_remap_digest($vpn['digest']);
5280
			}
5281
		}
5282
	}
5283
}
5284

    
5285
/* Force the Netgate Services and Support widget to be active on upgrade.
5286
   New widget is added at the top of column 2 */
5287
function upgrade_166_to_167() {
5288
	global $config;
5289

    
5290
	if (strpos($config['widgets']['sequence'],
5291
	    'netgate_services_and_support') === false) {
5292
		$widgets = explode(",", $config['widgets']['sequence']);
5293
		$cnt = count($widgets);
5294
		$col2 = $cnt;
5295
		$newsequence = array();
5296

    
5297
		// Locate the firt column 2 widget
5298
		for ($idx=0;$idx<$cnt;$idx++) {
5299
			if (strpos($widgets[$idx], 'col2') !== false) {
5300
				$col2 = $idx;
5301
				break;
5302
			}
5303
		}
5304

    
5305
		/*
5306
		 * Loop through the widgets inserting the new widget before
5307
		 * the first col2 widget
5308
		 */
5309
		for ($old=0,$new=0;$old<$cnt;$old++,$new++) {
5310
			$newsequence[$new] = $widgets[$old];
5311

    
5312
			if ($old != ($col2 - 1)) {
5313
				continue;
5314
			}
5315
			$new++;
5316
			$newsequence[$new] =
5317
			    "netgate_services_and_support:col2:open:0";
5318
		}
5319

    
5320
		$config['widgets']['sequence'] = implode(",", $newsequence);
5321
	}
5322
}
5323

    
5324
function upgrade_167_to_168() {
5325
	upgrade_166_to_167();
5326
}
5327

    
5328
function upgrade_168_to_169() {
5329
	global $config;
5330

    
5331
	config_del_path('cron/rc_update_pkg_metadata');
5332

    
5333
	$command = '/usr/bin/nice -n20 /etc/rc.update_pkg_metadata';
5334
	if (!is_array($config['cron'])) {
5335
		$config['cron'] = array();
5336
	}
5337
	if (!is_array($config['cron']['item'])) {
5338
		$config['cron']['item'] = array();
5339
	}
5340
	if (is_array($config['cron']['item'])) {
5341
		foreach ($config['cron']['item'] as $entry) {
5342
			if ($entry['command'] == $command) {
5343
				return;
5344
			}
5345
		}
5346
	}
5347

    
5348
	$config['cron']['item'][] = array(
5349
		'minute' => '1',
5350
		'hour' => '0',
5351
		'mday' => '*',
5352
		'month' => '*',
5353
		'wday' => '*',
5354
		'who' => 'root',
5355
		'command' => $command
5356
	);
5357
}
5358

    
5359
/* Upgrade wireless interfaces to the format required for 2.4
5360
 * Each wireless interface now needs to be a cloned instance, the card itself
5361
 * Can no longer be assigned. https://redmine.pfsense.org/issues/6770 */
5362
function upgrade_169_to_170() {
5363
	global $config;
5364
	foreach ($config['interfaces'] as $friendly => & $iface) {
5365
		if (is_array($iface['wireless']) && !empty($iface['wireless']['mode'])) {
5366
			/* This test can only be true for one instance per card, so it is safe. */
5367
			if (stristr($iface['if'], '_wlan') === false) {
5368
				$wlan = array();
5369
				$wlan['if'] = $iface['if'];
5370
				$wlan['mode'] = $iface['wireless']['mode'];
5371
				$wlan['descr'] = "Wireless interface {$friendly}";
5372
				/* It was not possible to create clones of _wlan0 before, so this is safe. */
5373
				$wlan['cloneif'] = "{$iface['if']}_wlan0";
5374
				/* Make sure this entry is placed in the list of wireless interface clones. */
5375
				if (!is_array($config['wireless'])) {
5376
					$config['wireless'] = array();
5377
					$config['wireless']['clone'] = array();
5378
				}
5379
				$config['wireless']['clone'][] = $wlan;
5380
				/* The interface assignment must now be the cloned interface name. */
5381
				$iface['if'] = $wlan['cloneif'];
5382
			}
5383
		}
5384
	}
5385
}
5386

    
5387
/* Upgrade the VLAN interface names to use $if.$tag instead of $if_vlan$tag.
5388
 * This helps keep the interface names smaller than the limit.
5389
 */
5390
function upgrade_170_to_171() {
5391
	global $config;
5392

    
5393
	if (!is_array($config['vlans']['vlan']) || count($config['vlans']['vlan']) == 0) {
5394
		return;
5395
	}
5396
	$iflist = get_configured_interface_list(true);
5397
	foreach ($config['vlans']['vlan'] as $id => $vlan) {
5398
		/* Make sure to update the interfaces section with the new name. */
5399
		$vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}";
5400
		foreach ($iflist as $ifname) {
5401
			if ($config['interfaces'][$ifname]['if'] == $vlan_name) {
5402
				$config['interfaces'][$ifname]['if'] = vlan_interface($vlan);
5403
			}
5404
		}
5405
		$config['vlans']['vlan'][$id]['vlanif'] = vlan_interface($vlan);
5406
	}
5407
}
5408

    
5409
/* Upgrade the QinQ interface names to use $if.$tag instead of $if_$tag.
5410
 * This helps keep the interface names smaller than the limit (but they are still
5411
 * big with the QinQ subtag).
5412
 */
5413
function upgrade_171_to_172() {
5414
	global $config;
5415

    
5416
	if (!is_array($config['qinqs']['qinqentry']) || count($config['qinqs']['qinqentry']) == 0) {
5417
		return;
5418
	}
5419
	$iflist = get_configured_interface_list(true);
5420
	foreach ($config['qinqs']['qinqentry'] as $id => $qinq) {
5421
		$config['qinqs']['qinqentry'][$id]['vlanif'] = vlan_interface($qinq);
5422

    
5423
		if (!isset($qinq['members'])) {
5424
			continue;
5425
		}
5426
		foreach (explode(" ", $qinq['members']) as $tag) {
5427
			/* Make sure to update the interfaces section with the new name. */
5428
			$vlan_name = "{$qinq['if']}_{$qinq['tag']}_{$tag}";
5429
			foreach ($iflist as $ifname) {
5430
				if ($config['interfaces'][$ifname]['if'] == $vlan_name) {
5431
					$config['interfaces'][$ifname]['if'] = qinq_interface($qinq, $tag);
5432
				}
5433
			}
5434
		}
5435
	}
5436
}
5437

    
5438
/*
5439
 * Upgrade the VLAN interface names to use $if.$tag on PPP items
5440
 */
5441
function upgrade_172_to_173() {
5442
	global $config;
5443

    
5444
	if (!is_array($config['ppps']['ppp']) ||
5445
	    count($config['ppps']['ppp']) == 0) {
5446
		return;
5447
	}
5448
	$iflist = get_configured_interface_list(true);
5449
	foreach ($config['ppps']['ppp'] as $id => $ppp) {
5450
		if (empty($ppp['ports']) ||
5451
		    strpos($ppp['ports'], "_vlan") == false) {
5452
			continue;
5453
		}
5454

    
5455
		$config['ppps']['ppp'][$id]['ports'] = str_replace('_vlan', '.',
5456
		    $ppp['ports']);
5457
	}
5458
}
5459

    
5460
/*
5461
 * Dynamic DNS nsupdate keyfiles have been replaced with a simpler ddns-confgen style file.
5462
 */
5463
function upgrade_173_to_174() {
5464
	global $config;
5465

    
5466
	/* Stop if there is nothing to do. */
5467
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
5468
		return;
5469
	}
5470
	/* Remove unused keytype field. */
5471
	foreach ($config['dnsupdates']['dnsupdate'] as $i => &$dnsupdate) {
5472
		unset($dnsupdate['keytype']);
5473
	}
5474
}
5475

    
5476
/* IPsec Phase1 now supports multiple authentication ciphers to be specified from the webgui.
5477
 * This is useful for mobile users using different OS's supporting different ciphers.
5478
 */
5479
function upgrade_174_to_175() {
5480
	global $config;
5481
	init_config_arr(array('ipsec', 'phase1'));
5482
	if (count($config['ipsec']['phase1'])) {
5483
		$a_phase1 = &$config['ipsec']['phase1'];
5484
		foreach($a_phase1 as &$phase1) {
5485
			if (empty($phase1) || !is_array($phase1)) {
5486
				continue;
5487
			}
5488
			$item = array();
5489
			if (isset($phase1['encryption-algorithm']) && !empty($phase1['encryption-algorithm'])) {
5490
				$item['encryption-algorithm'] = $phase1['encryption-algorithm'];
5491
				unset($phase1['encryption-algorithm']);
5492
			}
5493
			if (isset($phase1['hash-algorithm']) && !empty($phase1['hash-algorithm'])) {
5494
				$item['hash-algorithm'] = $phase1['hash-algorithm'];
5495
				unset($phase1['hash-algorithm']);
5496
			}
5497
			if (isset($phase1['dhgroup']) && !empty($phase1['dhgroup'])) {
5498
				$item['dhgroup'] = $phase1['dhgroup'];
5499
				unset($phase1['dhgroup']);
5500
			}
5501
			if (!empty($item)) {
5502
				if (!is_array($phase1['encryption'])) {
5503
					$phase1['encryption'] = array();
5504
				}
5505
				if (!is_array($phase1['encryption']['item'])) {
5506
					$phase1['encryption']['item'] = array();
5507
				}
5508
				$phase1['encryption']['item'][] = $item;
5509
			}
5510
		}
5511
	}
5512
}
5513

    
5514
/* igmp always was enabled by default if settings were present.
5515
 * So enable it once on upgrade if settings are there.
5516
 * And provide the option through gui to disable it again
5517
 */
5518
function upgrade_175_to_176() {
5519
	global $config;
5520
	if (is_array($config['igmpproxy']['igmpentry']) && (count($config['igmpproxy']['igmpentry']) > 0)) {
5521
		$config['igmpproxy']['enable'] = true;
5522
	}
5523
}
5524

    
5525
/* Placeholder for a factory update. */
5526
function upgrade_176_to_177() {
5527
}
5528

    
5529
// The image displayed by the picture widget is now stored on the file system
5530
function upgrade_177_to_178() {
5531
	global $config;
5532

    
5533
	if (isset($config['widgets'])) {
5534
		$idx = 0;
5535

    
5536
		while (isset($config['widgets']['picture-' . $idx])) {
5537
			file_put_contents("/conf/widget_image.picture-" . $idx, base64_decode($config['widgets']['picture-' . $idx]['picturewidget']));
5538
			$config['widgets']['picture-' . $idx]['picturewidget'] = "/conf/widget_image.picture-". $idx;
5539
			$idx++;
5540
		}
5541
	}
5542
}
5543

    
5544
/* Placeholder for a factory update. */
5545
function upgrade_178_to_179() {
5546
}
5547

    
5548
function upgrade_179_to_180() {
5549
	global $config, $g;
5550

    
5551
	/* Change default to 400000 to make sure bogonsv6 works */
5552
	if (empty($config['system']['maximumtableentries'])) {
5553
		$config['system']['maximumtableentries'] =
5554
		    g_get('minimumtableentries_bogonsv6');
5555
	}
5556
}
5557

    
5558
/*
5559
 * Automatically enable retrieving captive portal bandwidth limits from RADIUS for each captive portal
5560
 */
5561
function upgrade_180_to_181() {
5562
	global $config;
5563

    
5564
	if (is_array($config['captiveportal'])) {
5565
		foreach ($config['captiveportal'] as $cpzone => $cpcfg) {
5566
			if ($cpcfg['auth_method'] == "radius") {
5567
				$config['captiveportal'][$cpzone]['radiusperuserbw'] = true;
5568
			}
5569
		}
5570
	}
5571
}
5572

    
5573
function upgrade_181_to_182() {
5574
	global $config;
5575

    
5576
	/*
5577
	 * Some gateways did not have an ipprotocol set, and some configurations
5578
	 * did not have a default set so one was assumed. To avoid leaving the
5579
	 * user without a default, fix these situations first.
5580
	 */
5581
	$defgw_v4_found = false;
5582
	$defgw_v6_found = false;
5583
	$defgw_v4_candidate = array();
5584
	$defgw_v6_candidate = array();
5585
	if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
5586
		foreach($config['gateways']['gateway_item'] as &$item) {
5587
			/* Attempt to determine IP protocol for static gateways
5588
			 * missing the protocol definition */
5589
			if (empty($item['ipprotocol'])) {
5590
				if (is_ipaddrv4($item['gateway'])) {
5591
					$item['ipprotocol'] = 'inet';
5592
				} elseif (is_ipaddrv6($item['gateway'])) {
5593
					$item['ipprotocol'] = 'inet6';
5594
				}
5595
			}
5596
			/* Check if we have found a default gw */
5597
			if (isset($item['defaultgw'])) {
5598
				if ($item['ipprotocol'] == 'inet') {
5599
					$defgw_v4_found = true;
5600
				} elseif ($item['ipprotocol'] == 'inet6') {
5601
					$defgw_v6_found = true;
5602
				}
5603
			} else {
5604
				/* This isn't a default gateway, but could it be? */
5605
				if ($item['ipprotocol'] == 'inet') {
5606
					if (!$defgw_v4_found &&
5607
					    ($item['interface'] == "wan")) {
5608
						$defgw_v4_candidate = &$item;
5609
					}
5610
				} elseif ($item['ipprotocol'] == 'inet6') {
5611
					if (!$defgw_v6_found &&
5612
					    ($item['interface'] == "wan")) {
5613
						$defgw_v6_candidate = &$item;
5614
					}
5615
				}
5616
			}
5617
		}
5618
	}
5619
	/* If there was no other default gateway, use the one of last resort. */
5620
	if (!$defgw_v4_found && !empty($defgw_v4_candidate)) {
5621
		$defgw_v4_candidate['defaultgw'] = true;
5622
	}
5623
	if (!$defgw_v6_found && !empty($defgw_v6_candidate)) {
5624
		$defgw_v6_candidate['defaultgw'] = true;
5625
	}
5626

    
5627
	if (isset($config['system']['gw_switch_default'])) {
5628
		// default gateway switching was enabled, convert gatewaygroup
5629
		$newgroup4 = array();
5630
		$newgroup6 = array();
5631
		$tiernr4 = 2;
5632
		$tiernr6 = 2;
5633
		if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
5634
			foreach($config['gateways']['gateway_item'] as &$item) {
5635
				if ($item['ipprotocol'] == 'inet') {
5636
					if (isset($item['defaultgw'])) {
5637
						$tier = 1;
5638
						unset($item['defaultgw']);
5639
					} else {
5640
						$tier = $tiernr4;
5641
					}
5642
					$newgroup4['item'][] = $item['name']."|$tier|address";
5643
					if ($tiernr4 < 5) {
5644
						$tiernr4++;
5645
					}
5646
				}
5647
				if ($item['ipprotocol'] == 'inet6') {
5648
					if (isset($item['defaultgw'])) {
5649
						$tier = 1;
5650
						unset($item['defaultgw']);
5651
					} else {
5652
						$tier = $tiernr6;
5653
					}
5654
					$newgroup6['item'][] = $item['name']."|$tier|address";
5655
					if ($tiernr6 < 5) {
5656
						$tiernr6++;
5657
					}
5658
				}
5659
			}
5660
		}
5661
		if (is_array($newgroup4['item']) && count($newgroup4['item']) > 0) {
5662
			$newname = "Default_Gateway_Group_ipv4";
5663
			if (gateway_or_gwgroup_exists($newname)) { //make sure we create a new name
5664
				$id = 2;
5665
				while (gateway_or_gwgroup_exists($newname."_".$id)) {
5666
					$id++;
5667
				}
5668
				$newname .= "_".$id;
5669
			}
5670
			$newgroup4['name'] = $newname;
5671
			$newgroup4['trigger'] = 0;
5672
			$newgroup4['descr'] = "Default gateway group IPv4";
5673
			$config['gateways']['gateway_group'][] = $newgroup4;
5674
			$config['gateways']['defaultgw4'] = $newname;
5675
		}
5676
		if (is_array($newgroup6['item']) && count($newgroup6['item']) > 0) {
5677
			$newname = "Default_Gateway_Group_ipv6";
5678
			if (gateway_or_gwgroup_exists($newname)) { //make sure we create a new name
5679
				$id = 2;
5680
				while (gateway_or_gwgroup_exists($newname."_".$id)) {
5681
					$id++;
5682
				}
5683
				$newname .= "_".$id;
5684
			}
5685
			$newgroup6['name'] = $newname;
5686
			$newgroup6['trigger'] = 0;
5687
			$newgroup6['descr'] = "Default gateway group IPv6";
5688
			$config['gateways']['gateway_group'][] = $newgroup6;
5689
			$config['gateways']['defaultgw6'] = $newname;
5690
		}
5691
		config_del_path('system/gw_switch_default');// remove old setting, if a group is used switching is already implied
5692
	} else {
5693
		// set new defaultgw selection boxes to old selected default
5694
		if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
5695
			foreach($config['gateways']['gateway_item'] as &$item) {
5696
				if (isset($item['defaultgw'])) {
5697
					if ($item['ipprotocol'] == 'inet') {
5698
						$config['gateways']['defaultgw4'] = $item['name'];
5699
					} else {
5700
						$config['gateways']['defaultgw6'] = $item['name'];
5701
					}
5702
					unset($item['defaultgw']);
5703
				}
5704
			}
5705
		}
5706
	}
5707
}
5708

    
5709
/* Correct gateway group trigger level values.
5710
 * See https://redmine.pfsense.org/issues/8586
5711
 */
5712
function upgrade_182_to_183() {
5713
	global $config;
5714
	if (!is_array($config['gateways']) ||
5715
	    !is_array($config['gateways']['gateway_group'])) {
5716
		/* No gateway groups, nothing to do. */
5717
		return;
5718
	}
5719
	foreach ($config['gateways']['gateway_group'] as &$gwg) {
5720
		switch ($gwg['trigger']) {
5721
			case "0":
5722
				/* '0' => gettext('Member down'), */
5723
				/* 'down' => gettext("Member Down"), */
5724
				$gwg['trigger'] = "down";
5725
				break;
5726
			case "1":
5727
				/* '1' => gettext('Packet Loss'), */
5728
				/* 'downloss' => gettext("Packet Loss"), */
5729
				$gwg['trigger'] = "downloss";
5730
				break;
5731
			case "2":
5732
				/* '2' => gettext('High Latency'), */
5733
				/* 'downlatency' => gettext("High Latency"), */
5734
				$gwg['trigger'] = "downlatency";
5735
				break;
5736
			case "3":
5737
				/* '3' => gettext('Packet Loss or High latency') */
5738
				/* 'downlosslatency' => gettext("Packet Loss or High Latency")); */
5739
				$gwg['trigger'] = "downlosslatency";
5740
				break;
5741
		}
5742
	}
5743
}
5744

    
5745
function upgrade_183_to_184() {
5746
	/* 'none' was kinda confusing and didnt really do none
5747
	 * now use the new 'automatic' mode if it was set to none. */
5748
	global $config;
5749
	$gw4 = config_get_path('gateways/defaultgw4', "");
5750
	$gw6 = config_get_path('gateways/defaultgw6', "");
5751
	if ($gw4 === "-") {
5752
		$gw4 = "";
5753
	}
5754
	if ($gw6 === "-") {
5755
		$gw6 = "";
5756
	}
5757
}
5758

    
5759
// Migrate AutoConfigBackup package settings to integrated ACB system
5760
// and remove package
5761
function upgrade_184_to_185() {
5762
	global $config;
5763

    
5764
	if (is_array($config['installedpackages']['autoconfigbackup']['config'][0])) {
5765
		$acbpkg = &$config['installedpackages']['autoconfigbackup']['config'][0];
5766

    
5767
		init_config_arr(array('system', 'acb'));
5768
		$acb = &$config['system']['acb'];
5769
		$acb['enable'] = ($acbpkg['enable_acb'] != 'disabled') ?  'yes':'no';
5770
		$acb['gold_encryption_password'] = $acbpkg['crypto_password'];
5771

    
5772
		// If no encryption password has been set up yet, we might as well import the "Gold" password
5773
		// The user can update it later
5774
		if (!isset($acb['encryption_password'])) {
5775
			$acb['encryption_password'] = $acbpkg['crypto_password'];
5776
		}
5777

    
5778
		$acb['gold_password'] = $acbpkg['password'];
5779
		$acb['gold_username'] = $acbpkg['username'];
5780

    
5781
		config_del_path('installedpackages/autoconfigbackup/config');
5782
	}
5783
}
5784

    
5785
function upgrade_185_to_186() {
5786
	global $config;
5787

    
5788
	/* FEC LAGG is deprecated, replace with loadbalance */
5789
	if (!function_exists("file_notice")) {
5790
		require_once("notices.inc");
5791
	}
5792
	if (is_array($config['laggs']) &&
5793
	    is_array($config['laggs']['lagg'])) {
5794
		foreach ($config['laggs']['lagg'] as &$lagg) {
5795
			if ($lagg['proto'] == 'fec') {
5796
				$lagg['proto'] = 'failover';
5797
				file_notice("Interfaces", sprintf(gettext("The FEC LAGG protocol is deprecated. The %s LAGG interface has been set to failover."), $lagg['laggif']));
5798
			}
5799
		}
5800
	}
5801
}
5802

    
5803
function generate_usermanager_radius_config($cpzone, $counter, $protocol, $ip, $key, $port, $radiussrcip_attribute, $is_accounting=false, $accounting_port=false) {
5804
	global $config;
5805
	$pconfig = array();
5806

    
5807
	if (!is_array($config['system']['authserver'])) {
5808
		$config['system']['authserver'] = array();
5809
	}
5810

    
5811
	$pconfig['name'] = "Auto generated from Captive Portal {$cpzone}";
5812
	if ($counter != 1) {
5813
		$pconfig['name'] .= " {$counter}";
5814
	}
5815
	$pconfig['radius_srvcs'] = "auth";
5816
	$pconfig['type'] = 'radius';
5817
	$pconfig['radius_protocol'] = $protocol;
5818
	$pconfig['host'] = $ip;
5819
	$pconfig['radius_secret'] = $key;
5820
	$pconfig['radius_timeout'] = 3;
5821
	$pconfig['radius_auth_port'] = $port;
5822
	$pconfig['radius_nasip_attribute'] = $radiussrcip_attribute;
5823

    
5824
	if($is_accounting) {
5825
		$pconfig['radius_srvcs'] = "both";
5826
		$pconfig['radius_acct_port'] = $accounting_port;
5827
	}
5828

    
5829
	$config['system']['authserver'][] = $pconfig;
5830

    
5831
	return 'radius - '.$pconfig['name'];
5832
}
5833

    
5834
function upgrade_186_to_187() {
5835
	global $config;
5836
	global $g;
5837

    
5838
	if (is_array($config['captiveportal'])) {
5839
		foreach ($config['captiveportal'] as $cpzone => $cp) {
5840
			// we flush any existing sqlite3 db.
5841
			// It will be automatically re-generated on next captiveportal_readdb()/captiveportal_writedb()
5842
			$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
5843
			unlink_if_exists($db_path);
5844

    
5845
			if ($cp['auth_method'] === 'radius') { // Radius Auth
5846
				$auth_servers = array();
5847
				$auth_servers2 = array();
5848
				$radiuscounter = 1;
5849

    
5850
				if (intval($cp['radiusport']) == 0) {
5851
					$cp['radiusport'] = 1812;
5852
				}
5853
				if (intval($cp['radiusacctport']) == 0) {
5854
					$cp['radiusacctport'] = 1813;
5855
				}
5856
				if (!isset($cp['radiussrcip_attribute'])) {
5857
					$cp['radiussrcip_attribute'] = 'wan';
5858
				}
5859
				$auth_servers[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip'], $cp['radiuskey'], $cp['radiusport'], $cp['radiussrcip_attribute'], isset($cp['radacct_enable']), $cp['radiusacctport']);
5860

    
5861
				if (!empty($cp['radiusip2'])) {
5862
					$radiuscounter++;
5863
					if (intval($cp['radiusport2']) == 0) {
5864
						$cp['radiusport2'] = 1812;
5865
					}
5866
					$auth_servers[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip2'], $cp['radiuskey2'], $cp['radiusport2'], $cp['radiussrcip_attribute'], false, 0);
5867
				}
5868
				if (!empty($cp['radiusip3'])) {
5869
					$radiuscounter++;
5870
					if (intval($cp['radiusport3']) == 0) {
5871
						$cp['radiusport3'] = 1812;
5872
					}
5873
					$auth_servers2[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip3'], $cp['radiuskey3'], $cp['radiusport3'], $cp['radiussrcip_attribute'], false, 0);
5874
				}
5875
				if (!empty($cp['radiusip4'])) {
5876
					$radiuscounter++;
5877
					if (intval($cp['radiusport4']) == 0) {
5878
						$cp['radiusport4'] = 1812;
5879
					}
5880
					$auth_servers2[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip4'], $cp['radiuskey4'], $cp['radiusport4'], $cp['radiussrcip_attribute'], false, 0);
5881
				}
5882

    
5883
				$cp['auth_method'] = 'authserver';
5884
				$cp['auth_server'] = implode(",", $auth_servers);
5885
				$cp['auth_server2'] = implode(",", $auth_servers2);
5886

    
5887
				if (isset($cp['radmac_enable'])) { // RadMac
5888
					$cp['auth_method'] = 'radmac';
5889
				}
5890
				if (isset($cp['radacct_enable'])) { // If accounting was enabled : we select the primary radius server for accounting
5891
					$cp['radacct_server'] = "Auto generated from Captive Portal {$cpzone}";
5892
					if ($cp['reauthenticateacct'] === "") {
5893
						$cp['reauthenticateacct'] = 'none';
5894
					}
5895
				}
5896
			} elseif ($cp['auth_method'] === 'local') { // Local Auth
5897
				$cp['auth_method'] = 'authserver';
5898
				$cp['auth_server'] = "Local Auth - Local Database";
5899
			}
5900
			// we don't need to update anything when "none" auth method is selected
5901

    
5902
			$config['captiveportal'][$cpzone] = $cp;
5903
		}
5904
	}
5905
}
5906

    
5907
function upgrade_187_to_188() {
5908
	global $config;
5909

    
5910
	$old_cmd = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshlockout";
5911
	$new_cmd = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard";
5912
	if (!is_array($config['cron'])) {
5913
		$config['cron'] = array();
5914
	}
5915
	if (!is_array($config['cron']['item'])) {
5916
		$config['cron']['item'] = array();
5917
	}
5918
	if (is_array($config['cron']['item'])) {
5919
		foreach ($config['cron']['item'] as $idx => $entry) {
5920
			if ($entry['command'] == $old_cmd) {
5921
				$config['cron']['item'][$idx]['command'] = $new_cmd;
5922
				break;
5923
			}
5924
		}
5925
	}
5926
}
5927

    
5928
function upgrade_188_to_189() {
5929
	global $config;
5930

    
5931
	/* Migrate ssh setting to new location */
5932
	if (isset($config['system']['enablesshd'])) {
5933
		init_config_arr(array('system', 'ssh'));
5934
		$config['system']['ssh']['enable'] = "enabled";
5935
		config_del_path('system/enablesshd');
5936
	}
5937
	/* Remove accidentally duplicated ssh config
5938
	 * See https://redmine.pfsense.org/issues/8974 */
5939
	if (isset($config['system']['sshd'])) {
5940
		config_del_path('system/sshd');
5941
	}
5942
}
5943

    
5944
/* Older preexisting IPsec P1 entries may not have had the protocol explicitly
5945
 * defined. Fill in the default value of 'inet'.
5946
 * https://redmine.pfsense.org/issues/9207 */
5947
function upgrade_189_to_190() {
5948
	global $config;
5949
	init_config_arr(array('ipsec', 'phase1'));
5950
	foreach ($config['ipsec']['phase1'] as & $ph1ent) {
5951
		if (empty($ph1ent)) {
5952
			continue;
5953
		}
5954
		if (!isset($ph1ent['protocol']) || empty($ph1ent['protocol'])) {
5955
			$ph1ent['protocol'] = 'inet';
5956
		}
5957
	}
5958
}
5959

    
5960
/* sshguard cron jobs are not necessary.
5961
 * See https://redmine.pfsense.org/issues/9223 */
5962
function upgrade_190_to_191() {
5963
	global $config;
5964
	install_cron_job("/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard", false, null, null, null, null, null, null, false);
5965
	install_cron_job("/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 webConfiguratorlockout", false, null, null, null, null, null, null, false);
5966
}
5967

    
5968
/* Deprecate relayd Load Balancer
5969
 * See https://redmine.pfsense.org/issues/9386 */
5970
function upgrade_191_to_192() {
5971
	global $config;
5972

    
5973
	/* Backup LB config */
5974
	$backup_file = "/conf/deprecated_load_balancer.xml";
5975
	unlink_if_exists($backup_file);
5976
	file_put_contents($backup_file, backup_config_section('load_balancer'));
5977

    
5978
	/* Determine if LB was active and notify (or log if not) */
5979
	$deprecation_notice = sprintf(gettext("The built-in Load Balancer service has been deprecated. The active Load Balancer configuration has been stored in %s. Consider migrating to the HAProxy package."), $backup_file);
5980
	if (is_array($config['load_balancer']['virtual_server']) &&
5981
	    count($config['load_balancer']['virtual_server']) &&
5982
	    count($config['load_balancer']['lbpool'])) {
5983

    
5984
		if (!function_exists("file_notice")) {
5985
			require_once("notices.inc");
5986
		}
5987
		file_notice("Load Balancer", $deprecation_notice);
5988
	} else {
5989
		log_error("INFO: {$deprecation_notice}");
5990
	}
5991

    
5992
	config_del_path('load_balancer');
5993

    
5994
	/* Remove LB HA Sync Config */
5995
	if (isset($config['hasync']) &&
5996
	    is_array($config['hasync']) &&
5997
	    isset($config['hasync']['synchronizelb'])) {
5998
		config_del_path('hasync/synchronizelb');
5999
	}
6000

    
6001
	/* If the LB widget is present, remove it*/
6002
	if (isset($config['widgets']) &&
6003
	    isset($config['widgets']['sequence']) &&
6004
	    (strpos($config['widgets']['sequence'], 'load_balancer_status') !== false)) {
6005
		$widgets = explode(',', trim($config['widgets']['sequence']));
6006
		foreach ($widgets as $idx => &$widget) {
6007
			if (substr( $widget, 0, 20 ) === "load_balancer_status") {
6008
				unset($widgets[$idx]);
6009
			}
6010
		}
6011
		$config['widgets']['sequence'] = implode(',', $widgets);
6012
	}
6013

    
6014
	/* Per-log settings */
6015
	if (isset($config['syslog']) &&
6016
	    is_array($config['syslog']) &&
6017
	    isset($config['syslog']['relayd_settings'])) {
6018
		config_del_path('syslog/relayd_settings');
6019
	}
6020
}
6021

    
6022
/* Deprecate growl notifications */
6023
function upgrade_192_to_193() {
6024
	global $config;
6025

    
6026
	if (isset($config['notifications']['growl'])) {
6027
		config_del_path('notifications/growl');
6028
	}
6029
}
6030

    
6031
function upgrade_193_to_194() {
6032
	global $config, $g;
6033

    
6034
	if (is_array($config['captiveportal'])) {
6035
		foreach ($config['captiveportal'] as $cpzone => $cp) {
6036
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
6037
		}
6038
	}
6039
}
6040

    
6041
/*
6042
 * Reset all log files, including package logs, on upgrade since old logs are in
6043
 * binary clog format.
6044
 * Conversion is not possible since the clog binary will not be present.
6045
 * https://redmine.pfsense.org/issues/8350
6046
 */
6047
function upgrade_194_to_195() {
6048
	global $g;
6049

    
6050
	$logfiles = system_syslogd_get_all_logfilenames();
6051

    
6052
	foreach ($logfiles as $logfile) {
6053
		if (substr($logfile, -4) != '.log') {
6054
			$logfile .= ".log";
6055
		}
6056
		$logpath = "{$g['varlog_path']}/{$logfile}";
6057
		exec("/usr/bin/truncate -s 0 " . escapeshellarg($logpath));
6058
	}
6059
}
6060

    
6061
/* Skipped. See https://redmine.pfsense.org/issues/9730 */
6062
function upgrade_195_to_196() {
6063
}
6064

    
6065
/* Add newsyslog cron job */
6066
function upgrade_196_to_197() {
6067
	global $g, $config;
6068

    
6069
	install_cron_job('/usr/sbin/newsyslog', true, "*/1", '*', '*', '*', '*', 'root', false);
6070
}
6071

    
6072
/* Add periodic cron jobs */
6073
function upgrade_197_to_198() {
6074
	global $g, $config;
6075

    
6076
	install_cron_job('/etc/rc.periodic daily',   true, "1",  '3', '*', '*', '*', 'root', false);
6077
	install_cron_job('/etc/rc.periodic weekly',  true, "15", '4', '*', '*', '6', 'root', false);
6078
	install_cron_job('/etc/rc.periodic monthly', true, "30", '5', '1', '*', '*', 'root', false);
6079
}
6080

    
6081
/* Update IPsec authentication method names
6082
 * https://redmine.pfsense.org/issues/9903 */
6083
function upgrade_198_to_199() {
6084
	global $config;
6085
	/* "RSA" methods changed to the more generic "cert" since they are not only RSA. */
6086
	$namechanges = array(
6087
		'hybrid_rsa_server' => 'hybrid_cert_server',
6088
		'xauth_rsa_server' => 'xauth_cert_server',
6089
		'rsasig' => 'cert',
6090
	);
6091
	init_config_arr(array('ipsec', 'phase1'));
6092
	foreach ($config['ipsec']['phase1'] as & $ph1ent) {
6093
		/* If the auth method for this P1 is in the list to change, change it */
6094
		if (array_key_exists($ph1ent['authentication_method'], $namechanges)) {
6095
			$ph1ent['authentication_method'] = $namechanges[$ph1ent['authentication_method']];
6096
		}
6097
	}
6098
}
6099

    
6100
/* Superceded. See https://redmine.pfsense.org/issues/11219 and upgrade_212_to_213() */
6101
function upgrade_199_to_200() {
6102
	global $config;
6103
}
6104

    
6105
/* Update LDAP transport values */
6106
function upgrade_200_to_201() {
6107
	global $config;
6108
	/* Normalize/correct names (All are TCP) */
6109
	$namechanges = array(
6110
		'TCP - Standard' => 'Standard TCP',
6111
		'TCP - STARTTLS' => 'STARTTLS Encrypted',
6112
		'SSL - Encrypted' => 'SSL/TLS Encrypted',
6113
	);
6114
	init_config_arr(array('system', 'authserver'));
6115
	foreach ($config['system']['authserver'] as & $authserver) {
6116
		if (array_key_exists($authserver['ldap_urltype'], $namechanges)) {
6117
			$authserver['ldap_urltype'] = $namechanges[$authserver['ldap_urltype']];
6118
		}
6119
	}
6120
}
6121

    
6122
/* #10525: Handle Chinese (HongKong / Taiwan) locale rename */
6123
function upgrade_201_to_202() {
6124
	global $config;
6125

    
6126
	if (!empty($config['system']['language'])) {
6127
		if ($config['system']['language'] == 'zh_HK') {
6128
			$config['system']['language'] = 'zh_Hans_HK';
6129
		} elseif ($config['system']['language'] == 'zh_TW') {
6130
			$config['system']['language'] = 'zh_Hant_TW';
6131
		}
6132
	}
6133
}
6134

    
6135
function upgrade_202_to_203() {
6136
	global $config;
6137
	// Upgrade GREs with IPv6 tunnel networks to new dual stack format
6138
	if (is_array($config['gres']['gre'])) {
6139
		foreach ($config['gres']['gre'] as $idx => &$gre) {
6140
			if (is_ipaddrv6($gre['tunnel-local-addr'])) {
6141
				$gre['tunnel-local-addr6'] = $gre['tunnel-local-addr'];
6142
				$gre['tunnel-remote-addr6'] = $gre['tunnel-remote-addr'];
6143
				$gre['tunnel-remote-net6'] = $gre['tunnel-remote-net'];
6144
				$gre['tunnel-local-addr'] = '';
6145
				$gre['tunnel-remote-addr'] = '';
6146
				$gre['tunnel-remote-net'] = '';
6147
			} else {
6148
				$gre['tunnel-local-addr6'] = '';
6149
				$gre['tunnel-remote-addr6'] = '';
6150
				$gre['tunnel-remote-net6'] = '';
6151
			}
6152
		}
6153
	}
6154
}
6155

    
6156
/*
6157
 * Change IPsec close_action values
6158
 * See https://redmine.pfsense.org/issues/10632
6159
 */
6160

    
6161
function upgrade_203_to_204() {
6162
	global $config;
6163
	init_config_arr(array('ipsec', 'phase1'));
6164
	foreach ($config['ipsec']['phase1'] as & $ph1ent) {
6165
		if (empty($ph1ent)) {
6166
			continue;
6167
		}
6168
		if (isset($ph1ent['closeaction'])) {
6169
			switch ($ph1ent['closeaction']) {
6170
				case 'clear':
6171
					/* swanctl.conf combined "clear" and "none" */
6172
					$ph1ent['closeaction'] = "none";
6173
					break;
6174
				case 'restart':
6175
					/* swanctl.conf uses "start" not "restart" */
6176
					$ph1ent['closeaction'] = "start";
6177
					break;
6178
				case 'hold':
6179
					/* swanctl.conf uses "trap" not "hold" */
6180
					$ph1ent['closeaction'] = "trap";
6181
					break;
6182
				default:
6183
					/* "none" does not need changed. */
6184
			}
6185
		}
6186
	}
6187
}
6188

    
6189
function upgrade_204_to_205() {
6190
	global $config, $g;
6191

    
6192
	if (is_array($config['captiveportal'])) {
6193
		foreach ($config['captiveportal'] as $cpzone => $cp) {
6194
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
6195

    
6196
			if (is_array($config['voucher'][$cpzone])) {
6197
				if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) {
6198
					$config['captiveportal'][$cpzone]['enablebackwardsync'] = '';
6199
					$config['captiveportal'][$cpzone]['backwardsyncip'] = config_get_path("voucher/{$cpzone}/vouchersyncdbip");
6200
					$config['captiveportal'][$cpzone]['backwardsyncuser'] = config_get_path("voucher/{$cpzone}/vouchersyncusername");
6201
					$config['captiveportal'][$cpzone]['backwardsyncpassword'] = config_get_path("voucher/{$cpzone}/vouchersyncpass");
6202
				}
6203
			}
6204
		}
6205
	}
6206
}
6207

    
6208
function upgrade_205_to_206() {
6209
	/*
6210
	 * Trigger a boot loader settings update to make sure the contents will
6211
	 * be updated before the reboot.
6212
	 */
6213
	console_configure();
6214
}
6215

    
6216
function upgrade_206_to_207() {
6217
	/*
6218
	 * Trigger a boot loader settings update to make sure the contents will
6219
	 * be updated before the reboot.
6220
	 */
6221
	console_configure();
6222
}
6223

    
6224
function upgrade_207_to_208() {
6225
	global $config;
6226

    
6227
	$config['system']['hn_altq_enable'] = true;
6228
}
6229

    
6230
/* Update IPsec VTI to new VTIMAP format
6231
 * https://redmine.pfsense.org/issues/9592
6232
 */
6233
function upgrade_208_to_209() {
6234
	require_once("interfaces.inc");
6235
	global $config;
6236

    
6237
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6238

    
6239
	if (!is_array($config['ipsec']['phase1']) ||
6240
	    !is_array($config['ipsec']['phase2'])) {
6241
		return;
6242
	}
6243

    
6244
	foreach ($config['ipsec']['phase1'] as $ph1ent) {
6245
		if (!isset($ph1ent['mobile']) &&
6246
		    ($ph1ent['iketype'] == 'ikev1' ||
6247
		    isset($ph1ent['splitconn']))) {
6248
			$vtisubnet_spec = ipsec_vti($ph1ent, true, false);
6249
			if (empty($vtisubnet_spec)) {
6250
				continue;
6251
			}
6252
			foreach ($vtisubnet_spec as $idx => $vtisub) {
6253
				$config['ipsec']['vtimaps']['item'][] = array(
6254
					"reqid" => $ph1ent['ikeid'],
6255
					"index" => $idx,
6256
					"ifnum" => "{$ph1ent['ikeid']}00{$idx}"
6257
				);
6258
			}
6259
		} else {
6260
			$config['ipsec']['vtimaps']['item'][] = array(
6261
				"reqid" => $ph1ent['ikeid'],
6262
				"index" => "0",
6263
				"ifnum" => "{$ph1ent['ikeid']}000"
6264
			);
6265
		}
6266
	}
6267
}
6268

    
6269
function upgrade_209_to_210() {
6270
	global $config;
6271
	if (isset($config['system']['dnslocalhost'])) {
6272
		$config['system']['dnslocalhost'] = 'remote';
6273
	}
6274
}
6275

    
6276
/* OpenVPN Data Cipher changes
6277
 * https://redmine.pfsense.org/issues/10919 */
6278
function upgrade_210_to_211() {
6279
	global $config;
6280
	init_config_arr(array('openvpn', 'openvpn-server'));
6281
	init_config_arr(array('openvpn', 'openvpn-client'));
6282
	foreach(array('server', 'client') as $mode) {
6283
		foreach ($config['openvpn']["openvpn-{$mode}"] as & $settings) {
6284
			/* Rename ncp-ciphers to data_ciphers */
6285
			if (!empty($settings['ncp-ciphers'])) {
6286
				$settings['data_ciphers'] = $settings['ncp-ciphers'];
6287
			} elseif ($settings['crypto'] == 'none') {
6288
				$settings['data_ciphers'] = 'none';
6289
			} else {
6290
				$settings['data_ciphers'] = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305';
6291
			}
6292
			if (isset($settings['ncp-ciphers'])) {
6293
				unset($settings['ncp-ciphers']);
6294
			}
6295
			/* Add crypto to data_ciphers */
6296
			if (!empty($settings['crypto']) &&
6297
			    ($settings['crypto'] != 'none') &&
6298
			    !in_array($settings['crypto'], explode(',', $settings['data_ciphers']))) {
6299
				$settings['data_ciphers'] .= ',' . $settings['crypto'];
6300
			}
6301
			/* Rename crypto to data_ciphers_fallback */
6302
			if (isset($settings['crypto'])) {
6303
				$settings['data_ciphers_fallback'] = $settings['crypto'];
6304
				unset($settings['crypto']);
6305
			}
6306
			/* Forcefully enable data cipher negotiation since
6307
			 * disabling negotiation is now deprecated */
6308
			$settings['ncp_enable'] = "enabled";
6309
		}
6310
	}
6311
}
6312

    
6313
function upgrade_211_to_212() {
6314
	global $config;
6315
	if (isset($config['unbound']['sslport'])) {
6316
		$config['unbound']['tlsport'] = config_get_path('unbound/sslport');
6317
		config_del_path('unbound/sslport');
6318
	}
6319
}
6320

    
6321
/* IPsec Expiration and Replacement values which need updated for swanctl format
6322
 * https://redmine.pfsense.org/issues/11219
6323
 * https://redmine.pfsense.org/issues/9983
6324
 */
6325
function upgrade_212_to_213() {
6326
	global $config;
6327
	init_config_arr(array('ipsec', 'phase1'));
6328
	foreach ($config['ipsec']['phase1'] as & $ph1ent) {
6329
		if (empty($ph1ent)) {
6330
			continue;
6331
		}
6332

    
6333
		if (isset($ph1ent['reauth_enable'])) {
6334
			/* Disable reauth */
6335
			$ph1ent['reauth_time'] = "0";
6336
		} elseif (!empty($ph1ent['margintime'])) {
6337
			/* If margintime is set, use that to calculte reauth_time */
6338
			$ph1ent['reauth_time'] = ($ph1ent['lifetime'] - $ph1ent['margintime']);
6339
		}
6340
		/* Auto or IKEv2, rekey items */
6341
		if (($ph1ent['iketype'] == 'ikev2') || ($ph1ent['iketype'] == 'auto')) {
6342
			if (isset($ph1ent['rekey_enable'])) {
6343
				/* Disable rekey */
6344
				$ph1ent['rekey_time'] = "0";
6345
				$ph1ent['reauth_time'] = "0";
6346
			} elseif (!empty($ph1ent['margintime'])) {
6347
				/* If margintime is set, use that to calculate rekey_time */
6348
				$ph1ent['rekey_time'] = ($ph1ent['lifetime'] - $ph1ent['margintime']);
6349
			}
6350
		}
6351

    
6352
		if (!empty($ph1ent['margintime'])) {
6353
			$ph1ent['rand_time'] = $ph1ent['margintime'];
6354
		}
6355

    
6356
		/* Older snaps had over_time, now need lifetime back. */
6357
		if (!empty($ph1ent['over_time']) && empty($ph1ent['lifetime'])) {
6358
			$ph1ent['lifetime'] = $ph1ent['over_time'] + max($ph1ent['rekey_time'], $ph1ent['reauth_time']);
6359
		}
6360

    
6361
		if (isset($ph1ent['reauth_enable'])) {
6362
			unset($ph1ent['reauth_enable']);
6363
		}
6364
		if (isset($ph1ent['rekey_enable'])) {
6365
			unset($ph1ent['rekey_enable']);
6366
		}
6367
		if (isset($ph1ent['margintime'])) {
6368
			unset($ph1ent['margintime']);
6369
		}
6370
		if (isset($ph1ent['over_time'])) {
6371
			unset($ph1ent['over_time']);
6372
		}
6373
	}
6374
}
6375

    
6376
/* VXLAN support was removed */
6377
function upgrade_213_to_214() {
6378
	global $config;
6379

    
6380
	if (isset($config['vxlans'])) {
6381
		config_del_path('vxlans');
6382
	}
6383
}
6384

    
6385
/* WireGuard support was removed */
6386
function upgrade_214_to_215() {
6387
	global $config;
6388

    
6389
	if (isset($config['wireguard'])) {
6390
		config_del_path('wireguard');
6391
	}
6392
}
6393

    
6394
/* Fix VTI interface numbers */
6395
function upgrade_215_to_216() {
6396
	if (count(config_get_path('ipsec/vtimaps/item', [])) == 0) {
6397
		return;
6398
	}
6399

    
6400
	/* Deprecated method. */
6401
	function upgrade216_ipsec_create_vtimap($ikeid, $idx) {
6402
		$assigned = array_column(config_get_path('ipsec/vtimaps/item', []), 'ifnum');
6403
		asort($assigned, SORT_NUMERIC);
6404
		$new = 1;
6405
		foreach ($assigned as $ipsecifnum) {
6406
			if ($ipsecifnum != $new) {
6407
				break;
6408
			}
6409
			if ($new++ > 32767) {
6410
				return(NULL);
6411
			}
6412
		}
6413
		return array(
6414
			"reqid" => $ikeid,
6415
			"index" => $idx,
6416
			"ifnum" => $new
6417
		);
6418
	}
6419

    
6420
	$iflist = get_configured_interface_list_by_realif(true);
6421

    
6422
	foreach (config_get_path('ipsec/vtimaps/item', []) as $idx => $vtimap) {
6423
		if ($vtimap['ifnum'] <= 32767) {
6424
			continue;
6425
		}
6426

    
6427
		$new_vtimap = upgrade216_ipsec_create_vtimap($vtimap['reqid'],
6428
		    $vtimap['index']);
6429

    
6430
		/*
6431
		 * NULL means 32767 limit was reached.  It should never hit
6432
		 * this
6433
		 */
6434
		if ($new_vtimap == NULL) {
6435
			break;
6436
		}
6437

    
6438
		$old_if = 'ipsec' . $vtimap['ifnum'];
6439

    
6440
		/* Interface is assigned */
6441
		if (isset($iflist[$old_if])) {
6442
			config_set_path('interfaces/' . $iflist[$old_if] . '/if', 'ipsec' . $new_vtimap['ifnum']);
6443
		}
6444

    
6445
		config_set_path('ipsec/vtimaps/item/' . $idx, $new_vtimap);
6446
	}
6447
}
6448

    
6449
/*
6450
 * Child SA Start Action has replaced the Responder Only option. Update P1
6451
 * to match.
6452
 * https://redmine.pfsense.org/issues/11576
6453
 */
6454
function upgrade_216_to_217() {
6455
	global $config;
6456
	init_config_arr(array('ipsec', 'phase1'));
6457
	foreach ($config['ipsec']['phase1'] as & $ph1ent) {
6458
		if (empty($ph1ent)) {
6459
			continue;
6460
		}
6461
		if (isset($ph1ent['responderonly'])) {
6462
			$ph1ent['startaction'] = 'none';
6463
			unset($ph1ent['responderonly']);
6464
		}
6465
	}
6466
}
6467

    
6468
/*
6469
 * Disable PC/SC Smart Card Daemon if PKCS#11 authentication is not used
6470
 * https://redmine.pfsense.org/issues/11933
6471
 */
6472
function upgrade_217_to_218() {
6473
	global $config;
6474
	init_config_arr(array('ipsec', 'phase1'));
6475
	foreach ($config['ipsec']['phase1'] as $ph1ent) {
6476
		if (empty($ph1ent)) {
6477
			continue;
6478
		}
6479
		if (($ph1ent['authentication_method'] == 'pkcs11') &&
6480
		    !isset($ph1ent['disabled'])) {
6481
			$config['ipsec']['pkcs11support'] = true;
6482
			break;
6483
		}
6484
	}
6485
}
6486

    
6487
/*
6488
 * Convert VTI interface names to new format
6489
 */
6490
function upgrade_218_to_219() {
6491
	global $config;
6492
	init_config_arr(array('ipsec', 'phase1'));
6493
	init_config_arr(array('ipsec', 'phase2'));
6494
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6495

    
6496
	/* Deprecated method.
6497
	 * $ipsecifnum = get_ipsecifnum($ikeid, $idx);
6498
	 * locates and returns an ipsecifnum in the config.
6499
	 */
6500
	function upgrade219_get_ipsecifnum($ikeid, $idx) {
6501
		global $config;
6502
		foreach ($config['ipsec']['vtimaps']['item'] as $vtimap) {
6503
			if (($vtimap['reqid'] == $ikeid) &&
6504
			    ($vtimap['index'] == $idx)) {
6505
				return $vtimap['ifnum'];
6506
			}
6507
		}
6508
		return false;
6509
	}
6510

    
6511
	/* If IPsec is disabled or there are no P1 or P2 entries, there cannot
6512
	 * be any current assignments, so bail early */
6513
	if (!ipsec_enabled() ||
6514
	    empty($config['ipsec']['phase1']) ||
6515
	    empty($config['ipsec']['phase2'])) {
6516
		return false;
6517
	}
6518

    
6519
	/* Make an associative array with old name as key and new name as value for all VTI tunnels */
6520
	$ipsecifs = array();
6521
	foreach ($config['ipsec']['phase1'] as $ph1ent) {
6522
		if (empty($ph1ent) || !is_array($ph1ent)) {
6523
			continue;
6524
		}
6525
		$ifent = array();
6526
		/* If there is data here, then it's a VTI tunnel */
6527
		$vtisubnet_spec = ipsec_vti($ph1ent, true);
6528
		if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
6529
			/* Not VTI, so skip it. */
6530
			continue;
6531
		}
6532
		if (!isset($ph1ent['mobile']) && ($ph1ent['iketype'] == 'ikev1' || isset($ph1ent['splitconn']))) {
6533
			foreach ($vtisubnet_spec as $idx => $vtisub) {
6534
				/* Determine old name */
6535
				$old = "ipsec" . upgrade219_get_ipsecifnum($ph1ent['ikeid'], $idx);
6536
				/* Determine new name */
6537
				$new = ipsec_get_ifname($ph1ent, $vtisub['reqid']);
6538
				$ipsecifs[$old] = $new;
6539
			}
6540
		} else {
6541
			/* For IKEv2, only create one interface with additional addresses as aliases */
6542
			/* Determine old name */
6543
			$old = "ipsec" . upgrade219_get_ipsecifnum($ph1ent['ikeid'], 0);
6544
			/* Determine new name */
6545
			$new = ipsec_get_ifname($ph1ent);
6546
			$ipsecifs[$old] = $new;
6547
		}
6548
	}
6549

    
6550
	/* If there are no VTI interfaces, we have nothing to do */
6551
	if (empty($ipsecifs)) {
6552
		return null;
6553
	}
6554

    
6555
	foreach ($config['interfaces'] as $ifname => &$ifcfg) {
6556
		/* Check current interface assignments and see if any match a value we want */
6557
		if (array_key_exists($ifcfg['if'], $ipsecifs)) {
6558
			/* Update assignment to new name */
6559
			$ifcfg['if'] = $ipsecifs[$ifcfg['if']];
6560
		}
6561
	}
6562
	config_del_path('ipsec/vtimaps');
6563
}
6564

    
6565
/*
6566
 * Ensure the ACB cron job is installed after upgrade if ACB is enabled
6567
 * If the cron job already exists, no harm is done
6568
 */
6569
function upgrade_219_to_220() {
6570
	global $config;
6571

    
6572
	init_config_arr(array('system', 'acb'));
6573

    
6574
	if ($config['system']['acb']['enable'] == "yes" && file_exists("/usr/local/sbin/acbupload.php")) {
6575
		install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/acbupload.php", true, "*");
6576
	}
6577
}
6578

    
6579
/*
6580
 * Add new disk widget to dashboard if user already had the system information
6581
 * wiget configured to show disk usage stats.
6582
 */
6583
function upgrade_220_to_221() {
6584
	global $config;
6585

    
6586
	$widgets = explode(',', $config['widgets']['sequence']);
6587

    
6588
	foreach ($widgets as $idx => $widget) {
6589
		[$name, $col, $state, $index] = explode(':', $widget);
6590

    
6591
		if ($name === 'system_information') {
6592
			$widget_settings_key = "{$name}-{$index}";
6593

    
6594
			$filter = explode(',', $config['widgets'][$widget_settings_key]['filter']);
6595

    
6596
			if (!in_array('disk_usage', $filter)) {
6597
				$disk_widget = implode(':', array_filter(['disks', $col, $state, $index]));
6598

    
6599
				if (!in_array($disk_widget, $widgets)) {
6600
					array_splice($widgets, ($idx + 1), 0, $disk_widget);
6601
				}
6602
			}
6603
		}
6604
	}
6605

    
6606
	$config['widgets']['sequence'] = implode(',', $widgets);
6607
}
6608

    
6609
/* No functional changes. */
6610
function upgrade_221_to_222() {
6611
}
6612

    
6613
function upgrade_222_to_223() {
6614
	global $config;
6615

    
6616
	foreach ($config['system']['user'] as & $user) {
6617
		if ($user['name'] == 'admin') {
6618
			$user_home = "/root";
6619
		} else {
6620
			$user_home = "/home/{$user_name}";
6621
		}
6622
		$fn = "{$user_home}/.keephistory";
6623
		if (file_exists($fn)) {
6624
			$user['keephistory'] = true;
6625
			@unlink($fn);
6626
		}
6627
	}
6628
}
6629

    
6630
function upgrade_223_to_224() {
6631
	global $config;
6632

    
6633
	init_config_arr(array('filter', 'rule'));
6634
	foreach ($config['filter']['rule'] as & $rule) {
6635
		if (isset($rule['floating']) && !isset($rule['interface'])) {
6636
			$rule['interface'] = 'any';
6637
		}
6638
	}
6639
}
6640

    
6641
function upgrade_224_to_225() {
6642
	global $config;
6643

    
6644
	/* DHCP6 now uses single config for all interfaces
6645
	 * see https://redmine.pfsense.org/issues/6880 */
6646
	foreach ($config['interfaces'] as & $inf) {
6647
		if (isset($inf['dhcp6debug'])) {
6648
			$config['system']['dhcp6debug'] = true;
6649
			unset($inf['dhcp6debug']);
6650
		}
6651
		if (isset($inf['dhcp6norelease'])) {
6652
			$config['system']['dhcp6norelease'] = true;
6653
			unset($inf['dhcp6norelease']);
6654
		}
6655
	}
6656
}
6657

    
6658
function upgrade_225_to_226() {
6659
	global $config;
6660

    
6661
	/* Update value of state killing on gateway failure.
6662
	 * https://redmine.pfsense.org/issues/12092
6663
	 */
6664
	if (isset($config['system']['gw_down_kill_states'])) {
6665
		$config['system']['gw_down_kill_states'] = 'all';
6666
	}
6667
}
6668

    
6669
function upgrade_226_to_227() {
6670
	global $config;
6671

    
6672
	/* Convert dnsmasq (forwarder) custom options to base64.
6673
	 * https://redmine.pfsense.org/issues/13105
6674
	 */
6675
	if (is_array($config['dnsmasq']) && !empty($config['dnsmasq']['custom_options'])) {
6676
		$config['dnsmasq']['custom_options'] = base64_encode($config['dnsmasq']['custom_options']);
6677
	}
6678
}
6679

    
6680
function upgrade_227_to_228() {
6681
	global $config;
6682

    
6683
	$any_removed = false;
6684
	/* We no longer support 3des, blowfish, cast128 or md5 and sha1
6685
	 * authentication for IPSec. */
6686
	if (is_array($config['ipsec'])) {
6687
		if (is_array($config['ipsec']['phase1'])) {
6688
			foreach ($config['ipsec']['phase1'] as & $phase1) {
6689
				if (! isset($phase1['encryption']) || !is_array($phase1['encryption']['item']))
6690
					continue;
6691

    
6692
				$bad_count = 0;
6693
				foreach ($phase1['encryption']['item'] as $k => $enc) {
6694
					$bad = false;
6695
					if (isset($enc['encryption-algorithm']['name']) &&
6696
					    in_array($enc['encryption-algorithm']['name'],
6697
					    array("blowfish", "3des", "cast128"))) {
6698
						$bad = true;
6699
					}
6700
					if (isset($enc['hash-algorithm']) && $enc['hash-algorithm'] == "md5") {
6701
						$bad = true;
6702
					}
6703
					if ($bad) {
6704
						/* Remove this item as it contains deprecated encryption or hashing */
6705
						unset($phase1['encryption']['item'][$k]);
6706
						$bad_count++;
6707
					}
6708
				}
6709
				if ($bad_count > 0) {
6710
					$any_removed = true;
6711
					/* Only notify once per P1 */
6712
					if (count($phase1['encryption']['item']) == 0) {
6713
						/* Only disable P1 if there are no valid encryption options left. */
6714
						$phase1['disabled'] = true;
6715
						unset($phase1['encryption']);
6716
						file_notice("IPsec", sprintf(gettext("IPsec Phase 1 '%s' disabled after removing deprecated encryption and hashing algorithms as it has no remaining valid entries."), $phase1['descr']));
6717
					} else {
6718
						/* Let the user know that the P1 was adjusted */
6719
						file_notice("IPsec", sprintf(gettext("Removed deprecated encryption options from IPsec Phase 1 '%s'."), $phase1['descr']));
6720
					}
6721
				}
6722
			}
6723
		}
6724
		if (is_array($config['ipsec']['phase2'])) {
6725
			foreach ($config['ipsec']['phase2'] as & $phase2) {
6726

    
6727
				$bad_count = 0;
6728
				if (is_array($phase2['encryption-algorithm-option'])) {
6729
					foreach ($phase2['encryption-algorithm-option'] as $k => $opt) {
6730
						if (in_array($opt['name'], array("blowfish", "3des", "cast128"))) {
6731
							/* Remove this item as it contains deprecated encryption */
6732
							unset($phase2['encryption-algorithm-option'][$k]);
6733
							$bad_count++;
6734
						}
6735
					}
6736
				}
6737
				if (is_array($phase2['hash-algorithm-option'])) {
6738
					foreach ($phase2['hash-algorithm-option'] as $k => $opt) {
6739
						if ($opt == "hmac_md5") {
6740
							/* Remove this item as it contains deprecated hashing */
6741
							unset($phase2['hash-algorithm-option'][$k]);
6742
							$bad_count++;
6743
						}
6744
					}
6745
				}
6746

    
6747
				if ($bad_count > 0) {
6748
					$any_removed = true;
6749
					/* Only notify once per P2 */
6750
					if ((count($phase2['encryption-algorithm-option']) == 0) ||
6751
					    (count($phase2['hash-algorithm-option']) == 0)) {
6752
						/* Only disable P2 if there are no valid encryption options left. */
6753
						$phase2['disabled'] = true;
6754
						file_notice("IPsec", sprintf(gettext("IPsec Phase 2 '%s' disabled after removing deprecated encryption and hashing algorithms as it has no remaining valid combinations of options."), $phase2['descr']));
6755
					} else {
6756
						/* Let the user know that the P2 was adjusted */
6757
						file_notice("IPsec", sprintf(gettext("Removed deprecated encryption options from IPsec Phase 2 '%s'."), $phase2['descr']));
6758
					}
6759
				}
6760
			}
6761
		}
6762
	}
6763

    
6764
	/* Only list deprecated types once */
6765
	if ($any_removed) {
6766
		file_notice("IPsec", gettext("One or more IPsec entries contained deprecated algorithms. The following are no longer supported: 3DES encryption, Blowfish encryption, CAST128 encryption, MD5 hashing."));
6767
	}
6768
}
6769

    
6770
function upgrade_228_to_229() {
6771
	global $g;
6772
	/* Update System Memory RRD file with new data sources
6773
	 * https://redmine.pfsense.org/issues/14011
6774
	 */
6775
	$rrddbpath = "/var/db/rrd/";
6776
	$database = "system-memory.rrd";
6777
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
6778
	$rrdinterval = 60;
6779
	$valid = $rrdinterval * 2;
6780
	if (platform_booting()) {
6781
		echo "Migrating System Memory RRD file to new format\n";
6782
	}
6783
	mwexec("$rrdtool tune {$rrddbpath}{$database} DS:userwire:GAUGE:{$valid}:0:10000000 2>&1");
6784
	mwexec("$rrdtool tune {$rrddbpath}{$database} DS:laundry:GAUGE:{$valid}:0:10000000 2>&1");
6785
	mwexec("$rrdtool tune {$rrddbpath}{$database} DS:buffers:GAUGE:{$valid}:0:10000000 2>&1");
6786
}
6787

    
6788
function upgrade_229_to_230() {
6789
	/* The "target" GUI for outbound NAT rules now behaves similarly to other pages. */
6790
	$obn_rules = config_get_path('nat/outbound/rule', []);
6791
	foreach ($obn_rules as & $obent) {
6792
		if (empty($obent['target'])) {
6793
			// migrate interface address selection
6794
			$obent['target_type'] = $obent['interface'] . 'ip';
6795
			$obent['target'] = '';
6796
			$obent['target_subnet'] = '';
6797
		} elseif (str_contains($obent['target'], ':') ||
6798
		          str_contains($obent['target'], '.')) {
6799
			// migrate VIPs
6800
			if (get_specialnet($obent['target'])) {
6801
				$obent['target_type'] = $obent['target'];
6802
				$obent['target'] = '';
6803
			} else {
6804
				$obent['target_type'] = '';
6805
			}
6806
			$obent['target_subnet'] = '';
6807
		} elseif ($obent['target'] == 'other-subnet') {
6808
			// migrate custom subnets
6809
			$obent['target_type'] = 'network';
6810
			$obent['target'] = $obent['targetip'];
6811
			$obent['target_subnet'] = $obent['targetip_subnet'];
6812
		} else {
6813
			// migrate aliases
6814
			$obent['target_type'] = 'network';
6815
			$obent['target_subnet'] = '';
6816
		}
6817
		foreach (['targetip', 'targetip_subnet'] as $old) {
6818
			if (array_key_exists($old, $obent)) {
6819
				unset($obent[$old]);
6820
			}
6821
		}
6822
	}
6823
	if (isset($obent)) {
6824
		unset($obent);
6825
	}
6826
	config_set_path('nat/outbound/rule', $obn_rules);
6827
}
6828

    
6829
/*
6830
 * Special function that is called independent of current config version. It's
6831
 * a workaround to have config_upgrade running on older versions after next
6832
 * config version was already taken by newer pfSense.
6833
 *
6834
 * XXX Change the way we handle config version to make it based on product
6835
 *     version
6836
 */
6837
function additional_config_upgrade() {
6838
}
6839

    
6840
?>
(53-53/61)