Project

General

Profile

Download (208 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-2024 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
	$opti = 1;
44
	$ifmap = array('lan' => 'lan', 'wan' => 'wan', 'pptp' => 'pptp');
45
	$if_config = config_get_path('interfaces');
46

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

    
50
		$dmzcfg = &$if_config['dmz'];
51

    
52
		if ($dmzcfg['if']) {
53
			$if_config["opt{$opti}"] = array();
54
			$optcfg = &$if_config["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
		unset($if_config['dmz']);
67
	}
68

    
69
	/* convert WLAN1/2 to optional, if necessary */
70
	for ($i = 1; isset($if_config["wlan{$i}"]); $i++) {
71

    
72
		if (!$if_config["wlan{$i}"]['if']) {
73
			unset($if_config["wlan{$i}"]);
74
			continue;
75
		}
76

    
77
		$wlancfg = &$if_config["wlan{$i}"];
78
		$if_config["opt{$opti}"] = array();
79
		$optcfg = &$if_config["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
		unset($if_config["wlan{$i}"]);
97
		$opti++;
98
	}
99

    
100
	config_set_path('interfaces', $if_config);
101

    
102
	/* convert filter rules */
103
	config_init_path('filter/rule');
104
	$filter_rule_config = config_get_path('filter/rule');
105
	$n = count($filter_rule_config);
106
	for ($i = 0; $i < $n; $i++) {
107

    
108
		$fr = &$filter_rule_config[$i];
109

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

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

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

    
148
	config_set_path('filter/rule', $filter_rule_config);
149

    
150
	/* convert shaper rules */
151
	config_init_path('pfqueueing/rule');
152
	$shaper_rule_config = config_get_path('pfqueueing/rule');
153
	$n = count($shaper_rule_config);
154
	for ($i = 0; $i < $n; $i++) {
155

    
156
		$fr = &$shaper_rule_config[$i];
157

    
158
		/* remap interface */
159
		if (array_key_exists($fr['interface'], $ifmap)) {
160
			$fr['interface'] = $ifmap[$fr['interface']];
161
		} else {
162
			/* remove the rule */
163
			printf(gettext("%sWarning: traffic shaper rule removed " .
164
				"(interface '%s' does not exist anymore)."), "\n", $fr['interface']);
165
			unset($shaper_rule_config[$i]);
166
			continue;
167
		}
168

    
169
		/* remap source network */
170
		if (isset($fr['source']['network'])) {
171
			if (array_key_exists($fr['source']['network'], $ifmap)) {
172
				$fr['source']['network'] = $ifmap[$fr['source']['network']];
173
			} else {
174
				/* remove the rule */
175
				printf(gettext("%sWarning: traffic shaper rule removed " .
176
					"(source network '%s' does not exist anymore)."), "\n", $fr['source']['network']);
177
				unset($shaper_rule_config[$i]);
178
				continue;
179
			}
180
		}
181

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

    
196
	config_set_path('pfqueueing/rule', $shaper_rule_config);
197
}
198

    
199

    
200
function upgrade_011_to_012() {
201
	/* move LAN DHCP server config */
202
	$tmp = config_get_path('dhcpd');
203
	config_init_path('dhcpd/lan');
204
	config_set_path('dhcpd/lan', $tmp);
205

    
206
	/* encrypt password */
207
	config_set_path('system/password', password_hash(config_get_path('system/password'), PASSWORD_BCRYPT));
208
}
209

    
210

    
211
function upgrade_012_to_013() {
212
	/* convert advanced outbound NAT config */
213
	$onat_rule_config = config_get_path('nat/advancedoutbound/rule');
214
	for ($i = 0; isset($onat_rule_config[$i]); $i++) {
215
		$curent = &$onat_rule_config[$i];
216
		$src = $curent['source'];
217
		$curent['source'] = array();
218
		$curent['source']['network'] = $src;
219
		$curent['destination'] = array();
220
		$curent['destination']['any'] = true;
221
	}
222
	config_set_path('nat/advancedoutbound/rule', $onat_rule_config);
223

    
224
	/* add an explicit type="pass" to all filter rules to make things consistent */
225
	$filter_rule_config = config_get_path('filter/rule');
226
	for ($i = 0; isset($filter_rule_config[$i]); $i++) {
227
		$filter_rule_config[$i]['type'] = "pass";
228
	}
229
	config_set_path('nat/advancedoutbound/rule', $filter_rule_config);
230
}
231

    
232

    
233
function upgrade_013_to_014() {
234
	/* convert shaper rules (make pipes) */
235
	$shaper_rule_config = config_get_path('pfqueueing/rule');
236
	if (is_array($shaper_rule_config)) {
237
		config_init_path('pfqueueing/pipe');
238
		$shaper_pipe_config = config_get_path('pfqueueing/pipe');
239

    
240
		for ($i = 0; isset($shaper_rule_config[$i]); $i++) {
241
			$curent = &$shaper_rule_config[$i];
242

    
243
			/* make new pipe and associate with this rule */
244
			$newpipe = array();
245
			$newpipe['descr'] = $curent['descr'];
246
			$newpipe['bandwidth'] = $curent['bandwidth'];
247
			$newpipe['delay'] = $curent['delay'];
248
			$newpipe['mask'] = $curent['mask'];
249
			$shaper_pipe_config[$i] = $newpipe;
250

    
251
			$curent['targetpipe'] = $i;
252

    
253
			unset($curent['bandwidth']);
254
			unset($curent['delay']);
255
			unset($curent['mask']);
256
		}
257

    
258
		config_set_path('pfqueueing/rule', $shaper_rule_config);
259
		config_set_path('pfqueueing/pipe', $shaper_pipe_config);
260
	}
261
}
262

    
263

    
264
function upgrade_014_to_015() {
265
	/* Default route moved */
266
	$default_gateway_config = config_get_path('interfaces/wan/gateway');
267
	if (isset($default_gateway_config)) {
268
		if ($default_gateway_config <> "") {
269
			config_set_path('system/gateway', $default_gateway_config);
270
		}
271
		config_del_path('interfaces/wan/gateway');
272
	}
273

    
274
	/* Queues are no longer interface specific */
275
	config_del_path('interfaces/lan/schedulertype');
276
	config_del_path('interfaces/wan/schedulertype');
277

    
278
	$if_config = config_get_path('interfaces');
279
	for ($i = 1; isset($if_config["opt{$i}"]); $i++) {
280
		config_del_path("interfaces/opt{$i}/schedulertype");
281
	}
282
}
283

    
284

    
285
function upgrade_015_to_016() {
286
	/* Alternate firmware URL moved */
287
	$firmware_url_config = config_get_path('system/firmwareurl');
288
	$firmware_name_config = config_get_path('system/firmwarename');
289
	if (isset($firmware_url_config) && isset($firmware_name_config)) { // Only convert if *both* are defined.
290
		$alt_firmware_config = [
291
			'enabled' => "",
292
			'firmware_base_url' => $firmware_url_config,
293
			'firmware_filename' => $firmware_name_config
294
		];
295
		config_set_path('system/alt_firmware_url', $alt_firmware_config);
296
	}
297
	config_del_path('system/firmwareurl');
298
	config_del_path('system/firmwarename');
299
}
300

    
301

    
302
function upgrade_016_to_017() {
303
	/* wipe previous shaper configuration */
304
	config_del_path('shaper/queue');
305
	config_del_path('shaper/rule');
306
	config_del_path('interfaces/wan/bandwidth');
307
	config_del_path('interfaces/wan/bandwidthtype');
308
	config_del_path('interfaces/lan/bandwidth');
309
	config_del_path('interfaces/lan/bandwidthtype');
310
	config_set_path('shaper/enable', FALSE);
311
}
312

    
313

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

    
365
	/* enable SSH */
366
	if (config_get_path('version') == "1.8") {
367
		config_set_path('system/sshenabled', true);
368
	}
369
}
370

    
371

    
372
function upgrade_018_to_019() {
373
}
374

    
375

    
376
function upgrade_019_to_020() {
377
	$ipsec_config = config_get_path('ipsec/tunnel');
378
	if (is_array($ipsec_config)) {
379
		reset($ipsec_config);
380
		foreach ($ipsec_config as $idnex => $tunnel) {
381
			/* Sanity check on required variables */
382
			/* This fixes bogus <tunnel> entries - remnant of bug #393 */
383
			if (!isset($tunnel['local-subnet']) && !isset($tunnel['remote-subnet'])) {
384
				unset($ipsec_config[$tunnel]);
385
			}
386
		}
387
		config_set_path('ipsec/tunnel', $ipsec_config);
388
	}
389
}
390

    
391
function upgrade_020_to_021() {
392
	/* shaper scheduler moved */
393
	$shaper_config = config_get_path('system/schedulertype');
394
	if (isset($shaper_config)) {
395
		config_set_path('shaper/schedulertype', $shaper_config);
396
		config_del_path('system/schedulertype');
397
	}
398
}
399

    
400

    
401
function upgrade_021_to_022() {
402
	/* move gateway to wan interface */
403
	config_set_path('interfaces/wan/gateway', config_get_path('system/gateway'));
404
}
405

    
406
function upgrade_022_to_023() {
407
	config_del_path('shaper');
408
}
409

    
410

    
411
function upgrade_023_to_024() {
412
}
413

    
414

    
415
function upgrade_024_to_025() {
416
	config_set_path('interfaces/wan/use_rrd_gateway', config_get_path('system/use_rrd_gateway'));
417
	config_del_path('system/use_rrd_gateway');
418
}
419

    
420
function upgrade_025_to_026() {
421
	$cron_config = config_get_path('cron/item');
422

    
423
	$cron_config[] = [
424
		'minute' => '0',
425
		'hour' => '*',
426
		'mday' => '*',
427
		'month' => '*',
428
		'wday' => '*',
429
		'who' => 'root',
430
		'command' => '/usr/bin/nice -n20 newsyslog'
431
	];
432
	$cron_config[] = [
433
		'minute' => '1,31',
434
		'hour' => '0-5',
435
		'mday' => '*',
436
		'month' => '*',
437
		'wday' => '*',
438
		'who' => 'root',
439
		'command' => '/usr/bin/nice -n20 adjkerntz -a'
440
	];
441
	$cron_config[] = [
442
		'minute' => '1',
443
		'hour' => '*',
444
		'mday' => '1',
445
		'month' => '*',
446
		'wday' => '*',
447
		'who' => 'root',
448
		'command' => '/usr/bin/nice -n20 /etc/rc.update_bogons.sh'
449
	];
450
	$cron_config[] = [
451
		'minute' => '*/60',
452
		'hour' => '*',
453
		'mday' => '*',
454
		'month' => '*',
455
		'wday' => '*',
456
		'who' => 'root',
457
		'command' => '/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard'
458
	];
459
	$cron_config[] = [
460
		'minute' => '1',
461
		'hour' => '1',
462
		'mday' => '*',
463
		'month' => '*',
464
		'wday' => '*',
465
		'who' => 'root',
466
		'command' => '/usr/bin/nice -n20 /etc/rc.dyndns.update'
467
	];
468
	$cron_config[] = [
469
		'minute' => '*/60',
470
		'hour' => '*',
471
		'mday' => '*',
472
		'month' => '*',
473
		'wday' => '*',
474
		'who' => 'root',
475
		'command' => '/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 virusprot'
476
	];
477
	$cron_config[] = [
478
		'minute' => '*/60',
479
		'hour' => '*',
480
		'mday' => '*',
481
		'month' => '*',
482
		'wday' => '*',
483
		'who' => 'root',
484
		'command' => '/usr/bin/nice -n20 /usr/local/sbin/expiretable -t 1800 snort2c'
485
	];
486

    
487
	config_set_path('cron/item', $cron_config);
488
}
489

    
490

    
491
function upgrade_026_to_027() {
492
}
493

    
494

    
495
function upgrade_027_to_028() {
496
}
497

    
498

    
499
function upgrade_028_to_029() {
500
	$rule_item = array();
501
	$rule_item['interface'] = "enc0";
502
	$rule_item['type'] = "pass";
503
	$rule_item['source']['any'] = true;
504
	$rule_item['destination']['any'] = true;
505
	$rule_item['descr'] = gettext("Permit IPsec traffic.");
506
	$rule_item['statetype'] = "keep state";
507
	config_set_path('filter/rule/', $rule_item);
508
}
509

    
510

    
511
function upgrade_029_to_030() {
512
	/* enable the rrd config setting by default */
513
	config_set_path('rrd/enable', true);
514
}
515

    
516

    
517
function upgrade_030_to_031() {
518
	/* Insert upgrade code here */
519
}
520

    
521

    
522
function upgrade_031_to_032() {
523
	/* Insert upgrade code here */
524
}
525

    
526

    
527
function upgrade_032_to_033() {
528
	/* Insert upgrade code here */
529
}
530

    
531

    
532
function upgrade_033_to_034() {
533
	/* Insert upgrade code here */
534
}
535

    
536

    
537
function upgrade_034_to_035() {
538
	/* Insert upgrade code here */
539
}
540

    
541

    
542
function upgrade_035_to_036() {
543
	/* Insert upgrade code here */
544
}
545

    
546

    
547
function upgrade_036_to_037() {
548
	/* Insert upgrade code here */
549
}
550

    
551

    
552
function upgrade_037_to_038() {
553
	/* Insert upgrade code here */
554
}
555

    
556

    
557
function upgrade_038_to_039() {
558
	/* Insert upgrade code here */
559
}
560

    
561

    
562
function upgrade_039_to_040() {
563
	global $g;
564
	$webgui_config = config_get_path('system/webgui');
565
	$webgui_config['auth_method'] = "session";
566
	$webgui_config['backing_method'] = "htpasswd";
567
	config_set_path('system/webgui', $webgui_config);
568

    
569
	$username_config = config_get_path('system/username', '');
570
	if (!empty($username_config)) {
571
		/* Ensure that we follow what this new "admin" username should be in the session. */
572
		$_SESSION["Username"] = $username_config;
573

    
574
		$group_config = [[
575
			'name' => 'admins',
576
			'description' => gettext('System Administrators'),
577
			'scope' => 'system',
578
			'priv' => 'page-all',
579
			'home' => 'index.php',
580
			'gid' => '110'
581
		]];
582
		config_set_path('system/group', $group_config);
583

    
584
		$user_config = [[
585
			'name' => $username_config,
586
			'descr' => 'System Administrator',
587
			'scope' => 'system',
588
			'groupname' => 'admins',
589
			'password' => config_get_path('system/password', ''),
590
			'uid' => '0',
591
			'priv' => [
592
				[
593
					'id' => 'lockwc',
594
					'name' => 'Lock webConfigurator',
595
					'descr' => gettext('Indicates whether this user will lock access to the webConfigurator for other users.'),
596
				],
597
				[
598
					'id' => 'lock-ipages',
599
					'name' => 'Lock individual pages',
600
					'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).'),
601
				],
602
				[
603
					'id' => 'hasshell',
604
					'name' => 'Has shell access',
605
					'descr' => gettext('Indicates whether this user is able to login for example via SSH.'),
606
				],
607
				[
608
					'id' => 'copyfiles',
609
					'name' => 'Is allowed to copy files',
610
					'descr' => sprintf(gettext('Indicates whether this user is allowed to copy files onto the %s appliance via SCP/SFTP.'), g_get('product_label')),
611
				],
612
				[
613
					'id' => 'isroot',
614
					'name' => 'Is root user',
615
					'descr' => gettext('This user is associated with the UNIX root user (this privilege should only be associated with one single user).'),	
616
				]
617
			]
618
		]];
619
		config_set_path('system/user', $user_config);
620

    
621
		config_set_path('system/nextuid', '111');
622
		config_set_path('system/nextgid', '111');
623

    
624
		config_del_path('system/username');
625
		config_del_path('system/password');
626
	}
627
}
628

    
629
function upgrade_040_to_041() {
630
	$sysctl_config = config_get_path('sysctl');
631
	if (!$sysctl_config) {
632
		$sysctl_config['item'] = array();
633

    
634
		$sysctl_config['item'][0]['tunable'] = "net.inet.tcp.blackhole";
635
		$sysctl_config['item'][0]['descr'] =    gettext("Drop packets to closed TCP ports without returning a RST");
636
		$sysctl_config['item'][0]['value'] =   "default";
637

    
638
		$sysctl_config['item'][1]['tunable'] = "net.inet.udp.blackhole";
639
		$sysctl_config['item'][1]['descr'] =    gettext("Do not send ICMP port unreachable messages for closed UDP ports");
640
		$sysctl_config['item'][1]['value'] =   "default";
641

    
642
		$sysctl_config['item'][2]['tunable'] = "net.inet.ip.random_id";
643
		$sysctl_config['item'][2]['descr'] =    gettext("Randomize the ID field in IP packets (default is 1: Assign random IP IDs)");
644
		$sysctl_config['item'][2]['value'] =   "default";
645

    
646
		$sysctl_config['item'][3]['tunable'] = "net.inet.tcp.drop_synfin";
647
		$sysctl_config['item'][3]['descr'] =    gettext("Drop SYN-FIN packets (breaks RFC1379, but nobody uses it anyway)");
648
		$sysctl_config['item'][3]['value'] =   "default";
649

    
650
		$sysctl_config['item'][4]['tunable'] = "net.inet.ip.redirect";
651
		$sysctl_config['item'][4]['descr'] =    gettext("Sending of IPv4 ICMP redirects");
652
		$sysctl_config['item'][4]['value'] =   "default";
653

    
654
		$sysctl_config['item'][5]['tunable'] = "net.inet6.ip6.redirect";
655
		$sysctl_config['item'][5]['descr'] =    gettext("Sending of IPv6 ICMP redirects");
656
		$sysctl_config['item'][5]['value'] =   "default";
657

    
658
		$sysctl_config['item'][6]['tunable'] = "net.inet.tcp.syncookies";
659
		$sysctl_config['item'][6]['descr'] =    gettext("Generate SYN cookies for outbound SYN-ACK packets");
660
		$sysctl_config['item'][6]['value'] =   "default";
661

    
662
		$sysctl_config['item'][7]['tunable'] = "net.inet.tcp.recvspace";
663
		$sysctl_config['item'][7]['descr'] =    gettext("Maximum incoming TCP datagram size");
664
		$sysctl_config['item'][7]['value'] =   "default";
665

    
666
		$sysctl_config['item'][8]['tunable'] = "net.inet.tcp.sendspace";
667
		$sysctl_config['item'][8]['descr'] =    gettext("Maximum outgoing TCP datagram size");
668
		$sysctl_config['item'][8]['value'] =   "default";
669

    
670
		$sysctl_config['item'][9]['tunable'] = "net.inet.tcp.delayed_ack";
671
		$sysctl_config['item'][9]['descr'] =    gettext("Do not delay ACK to try and piggyback it onto a data packet");
672
		$sysctl_config['item'][9]['value'] =   "default";
673

    
674
		$sysctl_config['item'][10]['tunable'] = "net.inet.udp.maxdgram";
675
		$sysctl_config['item'][10]['descr'] =    gettext("Maximum outgoing UDP datagram size");
676
		$sysctl_config['item'][10]['value'] =   "default";
677

    
678
		$sysctl_config['item'][11]['tunable'] = "net.link.bridge.pfil_onlyip";
679
		$sysctl_config['item'][11]['descr'] =    gettext("Handling of non-IP packets which are not passed to pfil (see if_bridge(4))");
680
		$sysctl_config['item'][11]['value'] =   "default";
681

    
682
		$sysctl_config['item'][12]['tunable'] = "net.link.tap.user_open";
683
		$sysctl_config['item'][12]['descr'] =    gettext("Allow unprivileged access to tap(4) device nodes");
684
		$sysctl_config['item'][12]['value'] =   "default";
685

    
686
		$sysctl_config['item'][13]['tunable'] = "kern.randompid";
687
		$sysctl_config['item'][13]['descr'] =    gettext("Randomize PID's (see src/sys/kern/kern_fork.c: sysctl_kern_randompid())");
688
		$sysctl_config['item'][13]['value'] =   "default";
689

    
690
		$sysctl_config['item'][14]['tunable'] = "net.inet.tcp.inflight.enable";
691
		$sysctl_config['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. ");
692
		$sysctl_config['item'][14]['value'] =   "default";
693

    
694
		$sysctl_config['item'][15]['tunable'] = "net.inet.icmp.icmplim";
695
		$sysctl_config['item'][15]['descr'] =    gettext("Set ICMP Limits");
696
		$sysctl_config['item'][15]['value'] =   "default";
697

    
698
		$sysctl_config['item'][16]['tunable'] = "net.inet.tcp.tso";
699
		$sysctl_config['item'][16]['descr'] =    gettext("TCP Offload engine");
700
		$sysctl_config['item'][16]['value'] =   "default";
701

    
702
		$sysctl_config['item'][17]['tunable'] = "net.inet.ip.portrange.first";
703
		$sysctl_config['item'][17]['descr'] =    "Set the ephemeral port range starting port";
704
		$sysctl_config['item'][17]['value'] =   "default";
705

    
706
		$sysctl_config['item'][18]['tunable'] = "hw.syscons.kbd_reboot";
707
		$sysctl_config['item'][18]['descr'] =    "Enables ctrl+alt+delete";
708
		$sysctl_config['item'][18]['value'] =   "default";
709

    
710
		$sysctl_config['item'][19]['tunable'] = "kern.ipc.maxsockbuf";
711
		$sysctl_config['item'][19]['descr'] =    "Maximum socket buffer size";
712
		$sysctl_config['item'][19]['value'] =   "default";
713

    
714
		config_set_path('sysctl', $sysctl_config);
715
	}
716
}
717

    
718

    
719
function upgrade_041_to_042() {
720
	config_del_path('shaper');
721
	config_del_path('ezshaper');
722
}
723

    
724

    
725
function upgrade_042_to_043() {
726
	/* migrate old interface gateway to the new gateways config */
727
	$gateways_config = config_get_path('gateways/gateway_item');
728
	$if_config = config_get_path('interfaces');
729
	$filter_rule_config = config_get_path('filter/rule');
730
	$iflist = get_configured_interface_list(true);
731
	$gateways = array();
732
	$i = 0;
733
	foreach ($iflist as $ifname => $interface) {
734
		if (!interface_has_gateway($ifname)) {
735
			continue;
736
		}
737
		$gateways_config[$i] = array();
738
		if (is_ipaddr($if_config[$ifname]['gateway'])) {
739
			$gateways_config[$i]['gateway'] = $if_config[$ifname]['gateway'];
740
			$gateways_config[$i]['descr'] = sprintf(gettext("Interface %s Static Gateway"), $ifname);
741
		} else {
742
			$gateways_config[$i]['gateway'] = "dynamic";
743
			$gateways_config[$i]['descr'] = sprintf(gettext("Interface %s Dynamic Gateway"), $ifname);
744
		}
745
		$gateways_config[$i]['interface'] = $ifname;
746
		$gateways_config[$i]['name'] = "GW_" . strtoupper($ifname);
747
		/* add default gateway bit for wan on upgrade */
748
		if ($ifname == "wan") {
749
			$gateways_config[$i]['defaultgw'] = true;
750
		}
751
		if (is_ipaddr($if_config[$ifname]['use_rrd_gateway'])) {
752
			$gateways_config[$i]['monitor'] = $if_config[$ifname]['use_rrd_gateway'];
753
			array_del_path($if_config, "{$ifname}/use_rrd_gateway");
754
		}
755
		$if_config[$ifname]['gateway'] = $gateways_config[$i]['name'];
756

    
757
		/* Update all filter rules which might reference this gateway */
758
		$j = 0;
759
		foreach ($filter_rule_config as &$rule) {
760
			if (is_ipaddr($rule['gateway'])) {
761
				if ($rule['gateway'] == $gateways_config[$i]['gateway']) {
762
					$rule[$j]['gateway'] = $gateways_config[$i]['name'];
763
				} else if ($rule['gateway'] == $ifname) {
764
					$rule[$j]['gateway'] = $gateways_config[$i]['name'];
765
				}
766
			}
767
			$j++;
768
		}
769

    
770
		/* rename old Quality RRD files in the process */
771
		$rrddbpath = "/var/db/rrd";
772
		$gwname = "GW_" . strtoupper($ifname);
773
		if (is_readable("{$rrddbpath}/{$ifname}-quality.rrd")) {
774
			rename("{$rrddbpath}/{$ifname}-quality.rrd", "{$rrddbpath}/{$gwname}-quality.rrd");
775
		}
776
		$i++;
777
	}
778
	config_set_path('gateways/gateway_item', $gateways_config);
779
	config_set_path('interfaces', $if_config);
780
	config_set_path('filter/rule', $filter_rule_config);
781
}
782

    
783

    
784
function upgrade_043_to_044() {
785
	/* migrate static routes to the new gateways config */
786
	$gateways = get_gateways(GW_CACHE_DISABLED);
787
	$i = 0;
788
	$static_routes_config = config_get_path('staticroutes/route');
789
	if (is_array($static_routes_config)) {
790
		config_init_path('gateways/gateway_item');
791
		$gateways_config = config_get_path('gateways/gateway_item');
792
		$gwmap = array();
793
		foreach ($static_routes_config as $idx => $sroute) {
794
			$found = false;
795
			foreach ($gateways as $gwname => $gw) {
796
				if ($gw['gateway'] == $sroute['gateway']) {
797
					$static_routes_config[$idx]['gateway'] = $gwname;
798
					$found = true;
799
					break;
800
				}
801
			}
802
			if ($gwmap[$sroute['gateway']]) {
803
				/* We already added a gateway name for this IP */
804
				$static_routes_config[$idx]['gateway'] = "{$gwmap[$sroute['gateway']]}";
805
				$found = true;
806
			}
807

    
808
			if ($found == false) {
809
				$gateway = array();
810
				$gateway['name'] = "SROUTE{$i}";
811
				$gwmap[$sroute['gateway']] = $gateway['name'];
812
				$gateway['gateway'] = $sroute['gateway'];
813
				$gateway['interface'] = $sroute['interface'];
814
				$gateway['descr'] = sprintf(gettext("Upgraded static route for %s"), $sroute['network']);
815
				$gateways_config[] = $gateway;
816
				$static_routes_config[$idx]['gateway'] = $gateway['name'];
817
				$i++;
818
			}
819
		}
820
		config_set_path('staticroutes/route', $static_routes_config);
821
		config_set_path('gateways/gateway_item', $gateways_config);
822
	}
823
}
824

    
825

    
826
function upgrade_044_to_045() {
827
	$iflist = get_configured_interface_list(true);
828
	$vlans_config = config_get_path('vlans/vlan');
829
	if (is_array($vlans_config) && count($vlans_config)) {
830
		$if_config = config_get_path('interfaces');
831
		$i = 0;
832
		foreach ($vlans_config as $id => $vlan) {
833
			/* Make sure to update the interfaces section with the right name */
834
			$vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}";
835
			foreach ($iflist as $ifname) {
836
				if ($if_config[$ifname]['if'] == "vlan{$i}") {
837
					$if_config[$ifname]['if'] = $vlan_name;
838
					continue;
839
				}
840
			}
841
			$vlans_config[$i]['vlanif'] = "{$vlan_name}";
842
			$i++;
843
		}
844
		config_set_path('vlans/vlan', $vlans_config);
845
		config_set_path('interfaces', $if_config);
846
	}
847
}
848

    
849

    
850
function upgrade_045_to_046() {
851
	$load_balancer_config = config_get_path('load_balancer');
852
	/* Load up monitors that are in the default config for 2.0 but not in 1.2.3
853
		thus wouldn't be in an upgraded config. */
854
	$load_balancer_config['monitor_type'] = array (
855
		array ('name' => 'ICMP',
856
			'type' => 'icmp',
857
			'descr' => 'ICMP',
858
			'options' => '',
859
		),
860
		array ('name' => 'TCP',
861
			'type' => 'tcp',
862
			'descr' => 'Generic TCP',
863
			'options' => '',
864
		),
865
		array ('name' => 'HTTP',
866
			'type' => 'http',
867
			'descr' => 'Generic HTTP',
868
			'options' =>
869
			array ('path' => '/',
870
				'host' => '',
871
				'code' => '200',
872
			),
873
		),
874
		array ('name' => 'HTTPS',
875
			'type' => 'https',
876
			'descr' => 'Generic HTTPS',
877
			'options' =>
878
			array ('path' => '/',
879
				'host' => '',
880
				'code' => '200',
881
			),
882
		),
883
		array ('name' => 'SMTP',
884
			'type' => 'send',
885
			'descr' => 'Generic SMTP',
886
			'options' =>
887
			array ('send' => '',
888
				'expect' => '220 *',
889
			),
890
		),
891
	);
892
	/* Upgrade load balancer from slb to relayd */
893
	if (is_array($load_balancer_config['virtual_server']) && count($load_balancer_config['virtual_server'])) {
894
		$vs_a = &$load_balancer_config['virtual_server'];
895
		array_init_path($load_balancer_config, 'lbpool');
896
		$pool_a = &$load_balancer_config['lbpool'];
897
		$pools = array();
898
		/* Index pools by name */
899
		if (is_array($pool_a)) {
900
			for ($i = 0; isset($pool_a[$i]); $i++) {
901
				if ($pool_a[$i]['type'] == "server") {
902
					$pools[$pool_a[$i]['name']] = $pool_a[$i];
903
				}
904
			}
905
		}
906
		/* Convert sitedown entries to pools and re-attach */
907
		for ($i = 0; isset($vs_a[$i]); $i++) {
908
			/* Set mode while we're here. */
909
			$vs_a[$i]['mode'] = "redirect_mode";
910
			if (isset($vs_a[$i]['sitedown'])) {
911
				$pool = array();
912
				$pool['type'] = 'server';
913
				$pool['behaviour'] = 'balance';
914
				$pool['name'] = "{$vs_a[$i]['name']}-sitedown";
915
				$pool['descr'] = sprintf(gettext("Sitedown pool for VS: %s"), $vs_a[$i]['name']);
916
				if (is_array($vs_a[$i]['pool'])) {
917
					$vs_a[$i]['pool'] = $vs_a[$i]['pool'][0];
918
				}
919
				$pool['port'] = $pools[$vs_a[$i]['pool']]['port'];
920
				$pool['servers'] = array();
921
				$pool['servers'][] = $vs_a[$i]['sitedown'];
922
				$pool['monitor'] = $pools[$vs_a[$i]['pool']]['monitor'];
923
				$pool_a[] = $pool;
924
				$vs_a[$i]['sitedown'] = $pool['name'];
925
			}
926
		}
927
	}
928
	config_set_path('load_balancer', $load_balancer_config);
929
	if (count(config_get_path('load_balancer', [])) == 0) {
930
		config_del_path('load_balancer');
931
	}
932
}
933

    
934

    
935
function upgrade_046_to_047() {
936
	/* Upgrade IPsec from tunnel to phase1/phase2 */
937

    
938
	$ipsec_config = config_get_path('ipsec/tunnel');
939
	if (is_array($ipsec_config)) {
940

    
941
		$a_phase1 = array();
942
		$a_phase2 = array();
943
		$ikeid = 0;
944

    
945
		$virtualip_config = config_get_path('virtualip/vip');
946
		foreach ($ipsec_config as $tunnel) {
947

    
948
			unset($ph1ent);
949
			unset($ph2ent);
950

    
951
			/*
952
				*  attempt to locate an enabled phase1
953
				*  entry that matches the peer gateway
954
				*/
955

    
956
			if (!isset($tunnel['disabled'])) {
957

    
958
				$remote_gateway = $tunnel['remote-gateway'];
959

    
960
				foreach ($a_phase1 as $ph1tmp) {
961
					if ($ph1tmp['remote-gateway'] == $remote_gateway) {
962
						$ph1ent = $ph1tmp;
963
						break;
964
					}
965
				}
966
			}
967

    
968
			/* none found, create a new one */
969

    
970
			if (!isset($ph1ent)) {
971

    
972
				/* build new phase1 entry */
973

    
974
				$ph1ent = array();
975

    
976
				$ph1ent['ikeid'] = ++$ikeid;
977

    
978
				if (isset($tunnel['disabled'])) {
979
					$ph1ent['disabled'] = $tunnel['disabled'];
980
				}
981

    
982
				/* convert to the new vip[$vhid] name */
983
				if (preg_match("/^carp/", $tunnel['interface'])) {
984
					$carpid = str_replace("carp", "", $tunnel['interface']);
985
					$tunnel['interface'] = "vip{$virtualip_config[$carpid]['vhid']}";
986
				}
987
				$ph1ent['interface'] = $tunnel['interface'];
988
				$ph1ent['remote-gateway'] = $tunnel['remote-gateway'];
989
				$ph1ent['descr'] = $tunnel['descr'];
990

    
991
				$ph1ent['mode'] = $tunnel['p1']['mode'];
992

    
993
				if (isset($tunnel['p1']['myident']['myaddress'])) {
994
					$ph1ent['myid_type'] = "myaddress";
995
				}
996
				if (isset($tunnel['p1']['myident']['address'])) {
997
					$ph1ent['myid_type'] = "address";
998
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['address'];
999
				}
1000
				if (isset($tunnel['p1']['myident']['fqdn'])) {
1001
					$ph1ent['myid_type'] = "fqdn";
1002
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['fqdn'];
1003
				}
1004
				if (isset($tunnel['p1']['myident']['ufqdn'])) {
1005
					$ph1ent['myid_type'] = "user_fqdn";
1006
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['ufqdn'];
1007
				}
1008
				if (isset($tunnel['p1']['myident']['asn1dn'])) {
1009
					$ph1ent['myid_type'] = "asn1dn";
1010
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['asn1dn'];
1011
				}
1012
				if (isset($tunnel['p1']['myident']['dyn_dns'])) {
1013
					$ph1ent['myid_type'] = "dyn_dns";
1014
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['dyn_dns'];
1015
				}
1016

    
1017
				$ph1ent['peerid_type'] = "peeraddress";
1018

    
1019
				switch ($tunnel['p1']['encryption-algorithm']) {
1020
					case "des":
1021
						$ph1alg = array('name' => 'des');
1022
						break;
1023
					case "3des":
1024
						$ph1alg = array('name' => '3des');
1025
						break;
1026
					case "blowfish":
1027
						$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1028
						break;
1029
					case "cast128":
1030
						$ph1alg = array('name' => 'cast128');
1031
						break;
1032
					case "rijndael":
1033
						$ph1alg = array('name' => 'aes', 'keylen' => '128');
1034
						break;
1035
					case "rijndael 256":
1036
					case "aes 256":
1037
						$ph1alg = array('name' => 'aes', 'keylen' => '256');
1038
						break;
1039
				}
1040

    
1041
				$ph1ent['encryption-algorithm'] = $ph1alg;
1042
				$ph1ent['hash-algorithm'] = $tunnel['p1']['hash-algorithm'];
1043
				$ph1ent['dhgroup'] = $tunnel['p1']['dhgroup'];
1044
				$ph1ent['lifetime'] = $tunnel['p1']['lifetime'];
1045
				$ph1ent['authentication_method'] = $tunnel['p1']['authentication_method'];
1046

    
1047
				if (isset($tunnel['p1']['pre-shared-key'])) {
1048
					$ph1ent['pre-shared-key'] = $tunnel['p1']['pre-shared-key'];
1049
				}
1050
				if (isset($tunnel['p1']['cert'])) {
1051
					$ph1ent['cert'] = $tunnel['p1']['cert'];
1052
				}
1053
				if (isset($tunnel['p1']['peercert'])) {
1054
					$ph1ent['peercert'] = $tunnel['p1']['peercert'];
1055
				}
1056
				if (isset($tunnel['p1']['private-key'])) {
1057
					$ph1ent['private-key'] = $tunnel['p1']['private-key'];
1058
				}
1059

    
1060
				$ph1ent['nat_traversal'] = "on";
1061
				$ph1ent['dpd_enable'] = 1;
1062
				$ph1ent['dpd_delay'] = 10;
1063
				$ph1ent['dpd_maxfail'] = 5;
1064

    
1065
				$a_phase1[] = $ph1ent;
1066
			}
1067

    
1068
			/* build new phase2 entry */
1069

    
1070
			$ph2ent = array();
1071

    
1072
			$ph2ent['ikeid'] = $ph1ent['ikeid'];
1073

    
1074
			if (isset($tunnel['disabled'])) {
1075
				$ph1ent['disabled'] = $tunnel['disabled'];
1076
			}
1077

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

    
1080
			$type = "lan";
1081
			if ($tunnel['local-subnet']['network']) {
1082
				$type = $tunnel['local-subnet']['network'];
1083
			}
1084
			if ($tunnel['local-subnet']['address']) {
1085
				list($address, $netbits) = explode("/", $tunnel['local-subnet']['address']);
1086
				if (is_null($netbits)) {
1087
					$type = "address";
1088
				} else {
1089
					$type = "network";
1090
				}
1091
			}
1092

    
1093
			switch ($type) {
1094
				case "address":
1095
					$ph2ent['localid'] = array('type' => $type, 'address' => $address);
1096
					break;
1097
				case "network":
1098
					$ph2ent['localid'] = array('type' => $type, 'address' => $address, 'netbits' => $netbits);
1099
					break;
1100
				default:
1101
					$ph2ent['localid'] = array('type' => $type);
1102
					break;
1103
			}
1104

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

    
1108
			$ph2ent['protocol'] = $tunnel['p2']['protocol'];
1109

    
1110
			$aes_count = 0;
1111
			foreach ($tunnel['p2']['encryption-algorithm-option'] as $tunalg) {
1112
				$aes_found = false;
1113
				switch ($tunalg) {
1114
					case "des":
1115
						$ph2alg = array('name' => 'des');
1116
						break;
1117
					case "3des":
1118
						$ph2alg = array('name' => '3des');
1119
						break;
1120
					case "blowfish":
1121
						$ph2alg = array('name' => 'blowfish', 'keylen' => 'auto');
1122
						break;
1123
					case "cast128":
1124
						$ph2alg = array('name' => 'cast128');
1125
						break;
1126
					case "rijndael":
1127
					case "rijndael 256":
1128
					case "aes 256":
1129
						$ph2alg = array('name' => 'aes', 'keylen' => 'auto');
1130
						$aes_found = true;
1131
						$aes_count++;
1132
						break;
1133
				}
1134

    
1135
				if (!$aes_found || ($aes_count < 2)) {
1136
					$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1137
				}
1138
			}
1139

    
1140
			$ph2ent['hash-algorithm-option'] = $tunnel['p2']['hash-algorithm-option'];
1141
			$ph2ent['pfsgroup'] = $tunnel['p2']['pfsgroup'];
1142
			$ph2ent['lifetime'] = $tunnel['p2']['lifetime'];
1143

    
1144
			if (isset($tunnel['pinghost']['pinghost'])) {
1145
				$ph2ent['pinghost'] = $tunnel['pinghost'];
1146
			}
1147

    
1148
			$a_phase2[] = $ph2ent;
1149
		}
1150

    
1151
		config_del_path('ipsec/tunnel');
1152
		config_set_path('ipsec/phase1', $a_phase1);
1153
		config_set_path('ipsec/phase2', $a_phase2);
1154
	}
1155

    
1156
	/* Upgrade Mobile IPsec */
1157
	$ipsec_mobile_config = config_get_path('ipsec/mobileclients');
1158
	if (isset($ipsec_mobile_config) &&
1159
	    is_array($ipsec_mobile_config) &&
1160
	    is_array($ipsec_mobile_config['p1']) &&
1161
	    is_array($ipsec_mobile_config['p2'])) {
1162

    
1163
		if (config_get_path('ipsec/mobileclients') !== null) {
1164
			$ipsec_client_config = config_get_path('ipsec/client');
1165
			$ipsec_client_config['enable'] = true;
1166
			$ipsec_client_config['user_source'] = 'system';
1167
			$ipsec_client_config['group_source'] = 'system';
1168
			config_set_path('ipsec/client', $ipsec_client_config);
1169
		}
1170

    
1171
		$mobilecfg = $ipsec_mobile_config;
1172

    
1173
		$ph1ent = array();
1174
		$ph1ent['ikeid'] = ++$ikeid;
1175

    
1176
		if (!isset($mobilecfg['enable'])) {
1177
			$ph1ent['disabled'] = true;
1178
		}
1179

    
1180
		/* Assume WAN since mobile tunnels couldn't be on a separate interface on 1.2.x */
1181
		$ph1ent['interface'] = 'wan';
1182
		$ph1ent['descr'] = "Mobile Clients (upgraded)";
1183
		$ph1ent['mode'] = $mobilecfg['p1']['mode'];
1184

    
1185
		if (isset($mobilecfg['p1']['myident']['myaddress'])) {
1186
			$ph1ent['myid_type'] = "myaddress";
1187
		}
1188
		if (isset($mobilecfg['p1']['myident']['address'])) {
1189
			$ph1ent['myid_type'] = "address";
1190
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['address'];
1191
		}
1192
		if (isset($mobilecfg['p1']['myident']['fqdn'])) {
1193
			$ph1ent['myid_type'] = "fqdn";
1194
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['fqdn'];
1195
		}
1196
		if (isset($mobilecfg['p1']['myident']['ufqdn'])) {
1197
			$ph1ent['myid_type'] = "user_fqdn";
1198
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['ufqdn'];
1199
		}
1200
		if (isset($mobilecfg['p1']['myident']['asn1dn'])) {
1201
			$ph1ent['myid_type'] = "asn1dn";
1202
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['asn1dn'];
1203
		}
1204
		if (isset($mobilecfg['p1']['myident']['dyn_dns'])) {
1205
			$ph1ent['myid_type'] = "dyn_dns";
1206
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['dyn_dns'];
1207
		}
1208
		$ph1ent['peerid_type'] = "fqdn";
1209
		$ph1ent['peerid_data'] = "";
1210

    
1211
		switch ($mobilecfg['p1']['encryption-algorithm']) {
1212
			case "des":
1213
				$ph1alg = array('name' => 'des');
1214
				break;
1215
			case "3des":
1216
				$ph1alg = array('name' => '3des');
1217
				break;
1218
			case "blowfish":
1219
				$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1220
				break;
1221
			case "cast128":
1222
				$ph1alg = array('name' => 'cast128');
1223
				break;
1224
			case "rijndael":
1225
				$ph1alg = array('name' => 'aes', 'keylen' => '128');
1226
				break;
1227
			case "rijndael 256":
1228
			case "aes 256":
1229
				$ph1alg = array('name' => 'aes', 'keylen' => '256');
1230
				break;
1231
		}
1232

    
1233
		$ph1ent['encryption-algorithm'] = $ph1alg;
1234
		$ph1ent['hash-algorithm'] = $mobilecfg['p1']['hash-algorithm'];
1235
		$ph1ent['dhgroup'] = $mobilecfg['p1']['dhgroup'];
1236
		$ph1ent['lifetime'] = $mobilecfg['p1']['lifetime'];
1237
		$ph1ent['authentication_method'] = $mobilecfg['p1']['authentication_method'];
1238

    
1239
		if (isset($mobilecfg['p1']['cert'])) {
1240
			$ph1ent['cert'] = $mobilecfg['p1']['cert'];
1241
		}
1242
		if (isset($mobilecfg['p1']['peercert'])) {
1243
			$ph1ent['peercert'] = $mobilecfg['p1']['peercert'];
1244
		}
1245
		if (isset($mobilecfg['p1']['private-key'])) {
1246
			$ph1ent['private-key'] = $mobilecfg['p1']['private-key'];
1247
		}
1248

    
1249
		$ph1ent['nat_traversal'] = "on";
1250
		$ph1ent['dpd_enable'] = 1;
1251
		$ph1ent['dpd_delay'] = 10;
1252
		$ph1ent['dpd_maxfail'] = 5;
1253
		$ph1ent['mobile'] = true;
1254

    
1255
		$ph2ent = array();
1256
		$ph2ent['ikeid'] = $ph1ent['ikeid'];
1257
		$ph2ent['descr'] = "phase2 for ".$mobilecfg['descr'];
1258
		$ph2ent['localid'] = array('type' => 'none');
1259
		$ph2ent['remoteid'] = array('type' => 'mobile');
1260
		$ph2ent['protocol'] = $mobilecfg['p2']['protocol'];
1261

    
1262
		$aes_count = 0;
1263
		foreach ($mobilecfg['p2']['encryption-algorithm-option'] as $tunalg) {
1264
			$aes_found = false;
1265
			switch ($tunalg) {
1266
				case "des":
1267
					$ph2alg = array('name' => 'des');
1268
					break;
1269
				case "3des":
1270
					$ph2alg = array('name' => '3des');
1271
					break;
1272
				case "blowfish":
1273
					$ph2alg = array('name' => 'blowfish', 'keylen' => 'auto');
1274
					break;
1275
				case "cast128":
1276
					$ph2alg = array('name' => 'cast128');
1277
					break;
1278
				case "rijndael":
1279
				case "rijndael 256":
1280
				case "aes 256":
1281
					$ph2alg = array('name' => 'aes', 'keylen' => 'auto');
1282
					$aes_found = true;
1283
					$aes_count++;
1284
					break;
1285
			}
1286

    
1287
			if (!$aes_found || ($aes_count < 2)) {
1288
				$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1289
			}
1290
		}
1291
		$ph2ent['hash-algorithm-option'] = $mobilecfg['p2']['hash-algorithm-option'];
1292
		$ph2ent['pfsgroup'] = $mobilecfg['p2']['pfsgroup'];
1293
		$ph2ent['lifetime'] = $mobilecfg['p2']['lifetime'];
1294
		$ph2ent['mobile'] = true;
1295

    
1296
		config_set_path('ipsec/phase1/', $a_phase1);
1297
		config_set_path('ipsec/phase2/', $a_phase2);
1298
		config_del_path('ipsec/mobileclients');
1299
	}
1300
}
1301

    
1302

    
1303
function upgrade_047_to_048() {
1304
	$dyndns_config = config_get_path('dyndns');
1305
	if (!empty($dyndns_config)) {
1306
		if (isset($dyndns_config[0]['host'])) {
1307
			$tempdyn = array();
1308
			$tempdyn['enable'] = isset($dyndns_config[0]['enable']);
1309
			$tempdyn['type'] = $dyndns_config[0]['type'];
1310
			$tempdyn['wildcard'] = isset($dyndns_config[0]['wildcard']);
1311
			$tempdyn['username'] = $dyndns_config[0]['username'];
1312
			$tempdyn['password'] = $dyndns_config[0]['password'];
1313
			$tempdyn['host'] = $dyndns_config[0]['host'];
1314
			$tempdyn['mx'] = $dyndns_config[0]['mx'];
1315
			$tempdyn['interface'] = "wan";
1316
			$tempdyn['descr'] = sprintf(gettext("Upgraded Dyndns %s"), $tempdyn['type']);
1317
			config_set_path('dyndnses/dyndns', [$tempdyn]);
1318
		}
1319
		config_del_path('dyndns');
1320
	}
1321
	if (!empty(config_get_path('dnsupdate'))) {
1322
		$pconfig = config_get_path('dnsupdate/0');
1323
		if (!$pconfig['ttl']) {
1324
			$pconfig['ttl'] = 60;
1325
		}
1326
		if (!$pconfig['keytype']) {
1327
			$pconfig['keytype'] = "zone";
1328
		}
1329
		$pconfig['interface'] = "wan";
1330
		config_set_path('dnsupdates/dnsupdate/', $pconfig);
1331
		config_del_path('dnsupdate');
1332
	}
1333

    
1334
	$wan_config = config_get_path('interfaces/wan');
1335
	$pppoe_config = config_get_path('pppoe/0');
1336
	if (is_array($pppoe_config)) {
1337
		config_del_path('pppoe');
1338
		$wan_config['pppoe_username'] = $pppoe_config['username'];
1339
		$wan_config['pppoe_password'] = $pppoe_config['password'];
1340
		$wan_config['provider'] = $pppoe_config['provider'];
1341
		$wan_config['ondemand'] = isset($pppoe_config['ondemand']);
1342
		$wan_config['timeout'] = $pppoe_config['timeout'];
1343
	}
1344
	$pptp_config = config_get_path('pptp');
1345
	if (is_array($pptp_config)) {
1346
		config_del_path('pptp');
1347
		$wan_config['pppoe_username'] = $pptp_config['username'];
1348
		$wan_config['pppoe_password'] = $pptp_config['password'];
1349
		$wan_config['provider'] = $pptp_config['provider'];
1350
		$wan_config['ondemand'] = isset($pptp_config['ondemand']);
1351
		$wan_config['timeout'] = $pptp_config['timeout'];
1352
	}
1353
	config_set_path('interfaces/wan', $wan_config);
1354
}
1355

    
1356

    
1357
function upgrade_048_to_049() {
1358
	/* setup new all users group */
1359
	$all = array();
1360
	$all['name'] = "all";
1361
	$all['description'] = gettext("All Users");
1362
	$all['scope'] = "system";
1363
	$all['gid'] = 1998;
1364
	$all['member'] = array();
1365

    
1366
	config_init_path('system/user');
1367
	$user_config = config_get_path('system/user');
1368
	config_init_path('system/group');
1369
	$group_config = config_get_path('system/group');
1370

    
1371
	/* work around broken uid assignments */
1372
	$nextuid = 2000;
1373
	foreach ($user_config  as & $user) {
1374
		if (isset($user['uid']) && !$user['uid']) {
1375
			continue;
1376
		}
1377
		$user['uid'] = $nextuid++;
1378
	}
1379
	config_set_path('system/nextuid', $nextuid);
1380

    
1381
	/* work around broken gid assignments */
1382
	$nextgid = 2000;
1383
	foreach ($group_config as & $group) {
1384
		if ($group['name'] == g_get('admin_group')) {
1385
			$group['gid'] = 1999;
1386
		} else {
1387
			$group['gid'] = $nextgid++;
1388
		}
1389
	}
1390
	config_set_path('system/nextgid', $nextgid);
1391

    
1392
	/* build group membership information */
1393
	foreach ($group_config as & $group) {
1394
		$group['member'] = array();
1395
		foreach ($user_config as & $user) {
1396
			$groupnames = explode(",", $user['groupname']);
1397
			if (in_array($group['name'], $groupnames)) {
1398
				$group['member'][] = $user['uid'];
1399
			}
1400
		}
1401
	}
1402

    
1403
	/* reset user group information */
1404
	foreach ($user_config as & $user) {
1405
		unset($user['groupname']);
1406
		$all['member'][] = $user['uid'];
1407
	}
1408

    
1409
	/* reset group scope information */
1410
	foreach ($user_config as & $group) {
1411
		if ($group['name'] != g_get('admin_group')) {
1412
			$group['scope'] = "user";
1413
		}
1414
	}
1415

    
1416
	/* insert new all group */
1417
	$group_config = array_merge($group_config, [[$all]]);
1418

    
1419
	config_set_path('system/user', $user_config);
1420
	config_set_path('system/group', $group_config);
1421
}
1422

    
1423

    
1424
function upgrade_049_to_050() {
1425
	config_init_path('system/user');
1426
	$user_config = config_get_path('system/user');
1427
	/* update user privileges */
1428
	foreach ($user_config as & $user) {
1429
		$privs = array();
1430
		if (!is_array($user['priv'])) {
1431
			unset($user['priv']);
1432
			continue;
1433
		}
1434
		foreach ($user['priv'] as $priv) {
1435
			switch ($priv['id']) {
1436
				case "hasshell":
1437
					$privs[] = "user-shell-access";
1438
					break;
1439
				case "copyfiles":
1440
					$privs[] = "user-copy-files";
1441
					break;
1442
			}
1443
		}
1444
		$user['priv'] = $privs;
1445
	}
1446

    
1447
	config_init_path('system/group');
1448
	$group_config = config_get_path('system/group');
1449
	/* update group privileges */
1450
	foreach ($group_config as & $group) {
1451
		$privs = array();
1452
		if (!is_array($group['pages'])) {
1453
			unset($group['pages']);
1454
			continue;
1455
		}
1456
		foreach ($group['pages'] as $page) {
1457
			$priv = map_page_privname($page);
1458
			if ($priv) {
1459
				$privs[] = $priv;
1460
			}
1461
		}
1462
		unset($group['pages']);
1463
		$group['priv'] = $privs;
1464
	}
1465

    
1466
	config_set_path('system/user', $user_config);
1467
	config_set_path('system/group', $group_config);
1468

    
1469
	/* sync all local account information */
1470
	local_reset_accounts();
1471
}
1472

    
1473

    
1474
function upgrade_050_to_051() {
1475
	$sysctl_config = config_get_path('sysctl/item');
1476
	$pconfig = array();
1477
	$pconfig['descr'] = "Set to 0 to disable filtering on the incoming and outgoing member interfaces.";
1478
	$pconfig['tunable'] = "net.link.bridge.pfil_member";
1479
	$pconfig['value'] = "1";
1480
	$sysctl_config[] = $pconfig;
1481
	$pconfig = array();
1482
	$pconfig['descr'] = "Set to 1 to enable filtering on the bridge interface";
1483
	$pconfig['tunable'] = "net.link.bridge.pfil_bridge";
1484
	$pconfig['value'] = "0";
1485
	$sysctl_config[] = $pconfig;
1486
	config_set_path('sysctl/item', $sysctl_config);
1487
	config_del_path('bridge');
1488

    
1489
	$convert_bridges = false;
1490
	foreach (config_get_path('interfaces', []) as $intf) {
1491
		if (isset($intf['bridge']) && $intf['bridge'] <> "") {
1492
			config_init_path('bridges/bridged');
1493
			$convert_bridges = true;
1494
			break;
1495
		}
1496
	}
1497
	if ($convert_bridges == true) {
1498
		$bridge_config = config_get_path('bridges/bridged');
1499
		$if_config = config_get_path('interfaces');
1500
		$i = 0;
1501
		foreach ($if_config as $ifr => &$intf) {
1502
			if (isset($intf['bridge']) && $intf['bridge'] <> "") {
1503
				$nbridge = array();
1504
				$nbridge['members'] = "{$ifr},{$intf['bridge']}";
1505
				$nbridge['descr'] = sprintf(gettext("Converted bridged %s"), $ifr);
1506
				$nbridge['bridgeif'] = "bridge{$i}";
1507
				$bridge_config[] = $nbridge;
1508
				unset($intf['bridge']);
1509
				$i++;
1510
			}
1511
		}
1512
		config_set_path('interfaces', $if_config);
1513
		config_set_path('bridges/bridged', $bridge_config);
1514
	}
1515
}
1516

    
1517

    
1518
function upgrade_051_to_052() {
1519
	config_set_path('openvpn', []);
1520
	config_init_path('ca');
1521
	config_init_path('cert');
1522

    
1523
	$vpnid = 1;
1524

    
1525
	/* openvpn server configurations */
1526
	if (is_array(config_get_path('installedpackages/openvpnserver'))) {
1527
		config_set_path('openvpn/openvpn-server', []);
1528
		$index = 1;
1529
		foreach (config_get_path('installedpackages/openvpnserver/config', []) as $server) {
1530

    
1531
			if (!is_array($server)) {
1532
				continue;
1533
			}
1534

    
1535
			if ($server['auth_method'] == "pki") {
1536

    
1537
				/* create ca entry */
1538
				$ca = array();
1539
				$ca['refid'] = uniqid();
1540
				$ca['descr'] = "OpenVPN Server CA #{$index}";
1541
				$ca['crt'] = $server['ca_cert'];
1542
				config_set_path('ca/', $ca);
1543

    
1544
				/* create ca reference */
1545
				unset($server['ca_cert']);
1546
				$server['caref'] = $ca['refid'];
1547

    
1548
				/* create a crl entry if needed */
1549
				if (!empty($server['crl'][0])) {
1550
					$crl = array();
1551
					$crl['refid'] = uniqid();
1552
					$crl['descr'] = "Imported OpenVPN CRL #{$index}";
1553
					$crl['caref'] = $ca['refid'];
1554
					$crl['text'] = $server['crl'][0];
1555
					config_set_path('crl/', $crl);
1556
					$server['crlref'] = $crl['refid'];
1557
				}
1558
				unset($server['crl']);
1559

    
1560
				/* create cert entry */
1561
				$cert = array();
1562
				$cert['refid'] = uniqid();
1563
				$cert['descr'] = "OpenVPN Server Certificate #{$index}";
1564
				$cert['crt'] = $server['server_cert'];
1565
				$cert['prv'] = $server['server_key'];
1566
				config_set_path('cert/', $cert);
1567

    
1568
				/* create cert reference */
1569
				unset($server['server_cert']);
1570
				unset($server['server_key']);
1571
				$server['certref'] = $cert['refid'];
1572

    
1573
				$index++;
1574
			}
1575

    
1576
			/* determine operational mode */
1577
			if ($server['auth_method'] == 'pki') {
1578
				if ($server['nopool']) {
1579
					$server['mode'] = "p2p_tls";
1580
				} else {
1581
					$server['mode'] = "server_tls";
1582
				}
1583
			} else {
1584
				$server['mode'] = "p2p_shared_key";
1585
			}
1586
			unset($server['auth_method']);
1587

    
1588
			/* modify configuration values */
1589
			$server['dh_length'] = 1024;
1590
			unset($server['dh_params']);
1591
			if (!$server['interface']) {
1592
				$server['interface'] = 'any';
1593
			}
1594
			$server['tunnel_network'] = $server['addresspool'];
1595
			unset($server['addresspool']);
1596
			if (isset($server['use_lzo']) && ($server['use_lzo'] == "on")) {
1597
				$server['compression'] = "on";
1598
				unset($server['use_lzo']);
1599
			}
1600
			if ($server['nopool']) {
1601
				$server['pool_enable'] = false;
1602
			} else {
1603
				$server['pool_enable'] = "yes";
1604
			}
1605
			unset($server['nopool']);
1606
			$server['dns_domain'] = $server['dhcp_domainname'];
1607
			unset($server['dhcp_domainname']);
1608

    
1609
			$tmparr = explode(";", $server['dhcp_dns'], 4);
1610
			$d=1;
1611
			foreach ($tmparr as $tmpa) {
1612
				$server["dns_server{$d}"] = $tmpa;
1613
				$d++;
1614
			}
1615
			unset($server['dhcp_dns']);
1616

    
1617
			$tmparr = explode(";", $server['dhcp_ntp'], 2);
1618
			$d=1;
1619
			foreach ($tmparr as $tmpa) {
1620
				$server["ntp_server{$d}"] = $tmpa;
1621
				$d++;
1622
			}
1623
			unset($server['dhcp_ntp']);
1624

    
1625
			if ($server['dhcp_nbtdisable']) {
1626
				$server['netbios_enable'] = false;
1627
			} else {
1628
				$server['netbios_enable'] = "yes";
1629
			}
1630
			unset($server['dhcp_nbtdisable']);
1631
			$server['netbios_ntype'] = $server['dhcp_nbttype'];
1632
			unset($server['dhcp_nbttype']);
1633
			$server['netbios_scope'] = $server['dhcp_nbtscope'];
1634
			unset($server['dhcp_nbtscope']);
1635

    
1636
			$tmparr = explode(";", $server['dhcp_nbdd'], 2);
1637
			$d=1;
1638
			foreach ($tmparr as $tmpa) {
1639
				$server["nbdd_server{$d}"] = $tmpa;
1640
				$d++;
1641
			}
1642
			unset($server['dhcp_nbdd']);
1643

    
1644
			$tmparr = explode(";", $server['dhcp_wins'], 2);
1645
			$d=1;
1646
			foreach ($tmparr as $tmpa) {
1647
				$server["wins_server{$d}"] = $tmpa;
1648
				$d++;
1649
			}
1650
			unset($server['dhcp_wins']);
1651

    
1652
			if (!empty($server['disable'])) {
1653
				$server['disable'] = true;
1654
			} else {
1655
				unset($server['disable']);
1656
			}
1657

    
1658
			/* allocate vpnid */
1659
			$server['vpnid'] = $vpnid++;
1660

    
1661
			if (!empty($server['custom_options'])) {
1662
				$cstmopts = array();
1663
				$tmpcstmopts = explode(";", $server['custom_options']);
1664
				$assigned_if = "";
1665
				$tmpstr = "";
1666
				foreach ($tmpcstmopts as $tmpcstmopt) {
1667
					$tmpstr = str_replace(" ", "", $tmpcstmopt);
1668
					if (substr($tmpstr, 0, 6) == "devtun") {
1669
						$assigned_if = substr($tmpstr, 3);
1670
						continue;
1671
					} else if (substr($tmpstr, 0, 5) == "local") {
1672
						$localip = substr($tmpstr, 5);
1673
						$server['ipaddr'] = str_replace("\n", "", $localip);
1674
					} else {
1675
						$cstmopts[] = $tmpcstmopt;
1676
					}
1677
				}
1678
				$server['custom_options'] = implode(";", $cstmopts);
1679
				if (!empty($assigned_if)) {
1680
					foreach (config_get_path('interfaces', []) as $iface => $cfgif) {
1681
						if ($cfgif['if'] == $assigned_if) {
1682
							config_set_path("interfaces/{$iface}/if", "ovpns{$server['vpnid']}");
1683
							break;
1684
						}
1685
					}
1686
				}
1687
			}
1688

    
1689
			config_set_path('openvpn/openvpn-server/', $server);
1690
		}
1691
		config_del_path('installedpackages/openvpnserver');
1692
	}
1693

    
1694
	/* openvpn client configurations */
1695
	if (is_array(config_get_path('installedpackages/openvpnclient'))) {
1696
		config_set_path('openvpn/openvpn-client', []);
1697

    
1698
		$index = 1;
1699
		foreach (config_get_path('installedpackages/openvpnclient/config', []) as $client) {
1700

    
1701
			if (!is_array($client)) {
1702
				continue;
1703
			}
1704

    
1705
			if ($client['auth_method'] == "pki") {
1706

    
1707
				/* create ca entry */
1708
				$ca = array();
1709
				$ca['refid'] = uniqid();
1710
				$ca['descr'] = "OpenVPN Client CA #{$index}";
1711
				$ca['crt'] = $client['ca_cert'];
1712
				$ca['crl'] = $client['crl'];
1713
				config_set_path('ca/', $ca);
1714

    
1715
				/* create ca reference */
1716
				unset($client['ca_cert']);
1717
				unset($client['crl']);
1718
				$client['caref'] = $ca['refid'];
1719

    
1720
				/* create cert entry */
1721
				$cert = array();
1722
				$cert['refid'] = uniqid();
1723
				$cert['descr'] = "OpenVPN Client Certificate #{$index}";
1724
				$cert['crt'] = $client['client_cert'];
1725
				$cert['prv'] = $client['client_key'];
1726
				config_set_path('cert/', $cert);
1727

    
1728
				/* create cert reference */
1729
				unset($client['client_cert']);
1730
				unset($client['client_key']);
1731
				$client['certref'] = $cert['refid'];
1732

    
1733
				$index++;
1734
			}
1735

    
1736
			/* determine operational mode */
1737
			if ($client['auth_method'] == 'pki') {
1738
				$client['mode'] = "p2p_tls";
1739
			} else {
1740
				$client['mode'] = "p2p_shared_key";
1741
			}
1742
			unset($client['auth_method']);
1743

    
1744
			/* modify configuration values */
1745
			if (!$client['interface']) {
1746
				$client['interface'] = 'wan';
1747
			}
1748
			$client['tunnel_network'] = $client['interface_ip'];
1749
			unset($client['interface_ip']);
1750
			$client['server_addr'] = $client['serveraddr'];
1751
			unset($client['serveraddr']);
1752
			$client['server_port'] = $client['serverport'];
1753
			unset($client['serverport']);
1754
			$client['proxy_addr'] = $client['poxy_hostname'];
1755
			unset($client['proxy_addr']);
1756
			if (isset($client['use_lzo']) && ($client['use_lzo'] == "on")) {
1757
				$client['compression'] = "on";
1758
				unset($client['use_lzo']);
1759
			}
1760
			$client['resolve_retry'] = $client['infiniteresolvretry'];
1761
			unset($client['infiniteresolvretry']);
1762

    
1763
			/* allocate vpnid */
1764
			$client['vpnid'] = $vpnid++;
1765

    
1766
			if (!empty($client['custom_options'])) {
1767
				$cstmopts = array();
1768
				$tmpcstmopts = explode(";", $client['custom_options']);
1769
				$assigned_if = "";
1770
				$tmpstr = "";
1771
				foreach ($tmpcstmopts as $tmpcstmopt) {
1772
					$tmpstr = str_replace(" ", "", $tmpcstmopt);
1773
					if (substr($tmpstr, 0, 6) == "devtun") {
1774
						$assigned_if = substr($tmpstr, 3);
1775
						continue;
1776
					} else if (substr($tmpstr, 0, 5) == "local") {
1777
						$localip = substr($tmpstr, 5);
1778
						$client['ipaddr'] = str_replace("\n", "", $localip);
1779
					} else {
1780
						$cstmopts[] = $tmpcstmopt;
1781
					}
1782
				}
1783
				$client['custom_options'] = implode(";", $cstmopts);
1784
				if (!empty($assigned_if)) {
1785
					foreach (config_get_path('interfaces', []) as $iface => $cfgif) {
1786
						if ($cfgif['if'] == $assigned_if) {
1787
							config_set_path("interfaces/{$iface}/if", "ovpnc{$client['vpnid']}");
1788
							break;
1789
						}
1790
					}
1791
				}
1792
			}
1793

    
1794
			if (!empty($client['disable'])) {
1795
				$client['disable'] = true;
1796
			} else {
1797
				unset($client['disable']);
1798
			}
1799

    
1800
			config_set_path('openvpn/openvpn-client/', $client);
1801
		}
1802

    
1803
		config_del_path('installedpackages/openvpnclient');
1804
	}
1805

    
1806
	/* openvpn client specific configurations */
1807
	if (is_array(config_get_path('installedpackages/openvpncsc'))) {
1808
		config_set_path('openvpn/openvpn-csc', []);
1809

    
1810
		foreach (config_get_path('installedpackages/openvpncsc/config', []) as $csc) {
1811

    
1812
			if (!is_array($csc)) {
1813
				continue;
1814
			}
1815

    
1816
			/* modify configuration values */
1817
			$csc['common_name'] = $csc['commonname'];
1818
			unset($csc['commonname']);
1819
			$csc['tunnel_network'] = $csc['ifconfig_push'];
1820
			unset($csc['ifconfig_push']);
1821
			$csc['dns_domain'] = $csc['dhcp_domainname'];
1822
			unset($csc['dhcp_domainname']);
1823

    
1824
			$tmparr = explode(";", $csc['dhcp_dns'], 4);
1825
			$d=1;
1826
			foreach ($tmparr as $tmpa) {
1827
				$csc["dns_server{$d}"] = $tmpa;
1828
				$d++;
1829
			}
1830
			unset($csc['dhcp_dns']);
1831

    
1832
			$tmparr = explode(";", $csc['dhcp_ntp'], 2);
1833
			$d=1;
1834
			foreach ($tmparr as $tmpa) {
1835
				$csc["ntp_server{$d}"] = $tmpa;
1836
				$d++;
1837
			}
1838
			unset($csc['dhcp_ntp']);
1839

    
1840
			if ($csc['dhcp_nbtdisable']) {
1841
				$csc['netbios_enable'] = false;
1842
			} else {
1843
				$csc['netbios_enable'] = "yes";
1844
			}
1845
			unset($csc['dhcp_nbtdisable']);
1846
			$csc['netbios_ntype'] = $csc['dhcp_nbttype'];
1847
			unset($csc['dhcp_nbttype']);
1848
			$csc['netbios_scope'] = $csc['dhcp_nbtscope'];
1849
			unset($csc['dhcp_nbtscope']);
1850

    
1851
			$tmparr = explode(";", $csc['dhcp_nbdd'], 2);
1852
			$d=1;
1853
			foreach ($tmparr as $tmpa) {
1854
				$csc["nbdd_server{$d}"] = $tmpa;
1855
				$d++;
1856
			}
1857
			unset($csc['dhcp_nbdd']);
1858

    
1859
			$tmparr = explode(";", $csc['dhcp_wins'], 2);
1860
			$d=1;
1861
			foreach ($tmparr as $tmpa) {
1862
				$csc["wins_server{$d}"] = $tmpa;
1863
				$d++;
1864
			}
1865
			unset($csc['dhcp_wins']);
1866

    
1867
			if (!empty($csc['disable'])) {
1868
				$csc['disable'] = true;
1869
			} else {
1870
				unset($csc['disable']);
1871
			}
1872

    
1873
			config_set_path('openvpn/openvpn-csc/', $csc);
1874
		}
1875

    
1876
		config_del_path('installedpackages/openvpncsc');
1877
	}
1878

    
1879
	if (count(config_get_path('openvpn-server', [])) > 0 ||
1880
	    count(config_get_path('openvpn-client', [])) > 0) {
1881
		config_set_path('filter/rule/', [
1882
			'type' => 'pass',
1883
			'interface' => 'openvpn',
1884
			'statetype' => 'keep state',
1885
			'source' => [
1886
				'any' => true
1887
			],
1888
			'destination' => [
1889
				'any' => true
1890
			],
1891
			'descr' => gettext('Auto added OpenVPN rule from config upgrade.')
1892
		]);
1893
	}
1894

    
1895
	/*
1896
		* FIXME: hack to keep things working with no installedpackages
1897
		* or carp array in the configuration data.
1898
		*/
1899
	config_init_path('installedpackages/carp');
1900

    
1901
}
1902

    
1903

    
1904
function upgrade_052_to_053() {
1905
	config_init_path('ca');
1906
	config_init_path('cert');
1907

    
1908
	/* migrate advanced admin page webui ssl to certificate manager */
1909
	$webgui_config = config_get_path('system/webgui');
1910
	if ($webgui_config['certificate'] &&
1911
	    $webgui_config['private-key']) {
1912

    
1913
		/* create cert entry */
1914
		$cert = array();
1915
		$cert['refid'] = uniqid();
1916
		$cert['descr'] = "webConfigurator SSL/TLS Certificate";
1917
		$cert['crt'] = $webgui_config['certificate'];
1918
		$cert['prv'] = $webgui_config['private-key'];
1919
		config_set_path('cert/', $cert);
1920

    
1921
		config_del_path('system/webgui/certificate');
1922
		config_del_path('system/webgui/private-key');
1923
		$webgui_config['ssl-certref'] = $cert['refid'];
1924
	}
1925
	config_set_path('system/webgui', $webgui_config);
1926

    
1927
	/* migrate advanced admin page ssh keys to user manager */
1928
	$authorizedkeys = config_get_path('system/ssh/authorizedkeys');
1929
	if (!empty($authorizedkeys)) {
1930
		$admin_user = getUserEntryByUID(0);
1931
		if (!empty($admin_user['idx'])) {
1932
			config_set_path("system/user/{$admin_user['idx']}/authorizedkeys", $authorizedkeys);
1933
		}
1934
		config_del_path('system/ssh/authorizedkeys');
1935
	}
1936
}
1937

    
1938

    
1939
function upgrade_053_to_054() {
1940
	$loadbalancer_pool_config =  config_get_path('load_balancer/lbpool');
1941
	if (is_array($loadbalancer_pool_config)) {
1942
		$lbpool_arr = $loadbalancer_pool_config;
1943
		$lbpool_srv_arr = array();
1944
		$gateway_group_arr = array();
1945
		$gateways = get_gateways();
1946
		$group_name_changes = array();
1947
		config_init_path('gateways/gateway_item');
1948
		$a_gateways = config_get_path('gateways/gateway_item');
1949
		foreach ($lbpool_arr as $lbpool) {
1950
			if ($lbpool['type'] == "gateway") {
1951
				// Gateway Groups have to have valid names in pf, old lb pools did not. Clean them up.
1952
				$group_name = preg_replace("/[^A-Za-z0-9]/", "", $lbpool['name']);
1953
				// If we made and changes, check for collisions and note the change.
1954
				if ($group_name != $lbpool['name']) {
1955
					// Make sure the name isn't already in use.
1956
					foreach ($gateway_group_arr as $gwg) {
1957
						// If the name is in use, add some random bits to avoid collision.
1958
						if ($gwg['name'] == $group_name) {
1959
							$group_name .= uniqid();
1960
						}
1961
					}
1962
					$group_name_changes[$lbpool['name']] = $group_name;
1963
				}
1964
				$gateway_group['name'] = $group_name;
1965
				$gateway_group['descr'] = $lbpool['descr'];
1966
				$gateway_group['trigger'] = "down";
1967
				$gateway_group['item'] = array();
1968
				$i = 0;
1969
				foreach ($lbpool['servers'] as $member) {
1970
					$split = explode("|", $member);
1971
					$interface = $split[0];
1972
					$monitor = $split[1];
1973
					/* on static upgraded configuration we automatically prepend GW_ */
1974
					$static_name = "GW_" . strtoupper($interface);
1975
					if (is_ipaddr($monitor)) {
1976
						foreach ($a_gateways as & $gw) {
1977
							if ($gw['name'] == $static_name) {
1978
								$gw['monitor'] = $monitor;
1979
							}
1980
						}
1981
					}
1982

    
1983
					/* on failover increment tier. Else always assign 1 */
1984
					if ($lbpool['behaviour'] == "failover") {
1985
						$i++;
1986
					} else {
1987
						$i = 1;
1988
					}
1989
					$gateway_group['item'][] = "$static_name|$i";
1990
				}
1991
				$gateway_group_arr[] = $gateway_group;
1992
			} else {
1993
				$lbpool_srv_arr[] = $lbpool;
1994
			}
1995
		}
1996
		config_set_path('load_balancer/lbpool', $lbpool_srv_arr);
1997
		config_set_path('gateways/gateway_group', $gateway_group_arr);
1998
		config_set_path('gateways/gateway_item', $a_gateways);
1999
	}
2000
	// Unset lbpool if we no longer have any server pools
2001
	if (count($lbpool_srv_arr) == 0) {
2002
		if (empty(config_get_path('load_balancer'))) {
2003
			config_del_path('load_balancer');
2004
		} else {
2005
			config_del_path('load_balancer/lbpool');
2006
		}
2007
	} else {
2008
		config_set_path('load_balancer/lbpool', $lbpool_srv_arr);
2009
	}
2010
	// Only set the gateway group array if we converted any
2011
	if (count($gateway_group_arr) != 0) {
2012
		config_set_path('gateways/gateway_group', $gateway_group_arr);
2013
		// Update any rules that had a gateway change, if any.
2014
		if (count($group_name_changes) > 0) {
2015
			$filter_rule_config =  config_get_path('filter/rule');
2016
			foreach ($filter_rule_config as & $rule) {
2017
				if (!empty($rule["gateway"]) && array_key_exists($rule["gateway"], $group_name_changes)) {
2018
					$rule["gateway"] = $group_name_changes[$rule["gateway"]];
2019
				}
2020
			}
2021
			config_set_path('filter/rule', $filter_rule_config);
2022
		}
2023
	}
2024
}
2025

    
2026

    
2027
function upgrade_054_to_055() {
2028
	global $g;
2029

    
2030
	/* RRD files changed for quality, traffic and packets graphs */
2031
	//ini_set("max_execution_time", "1800");
2032
	/* convert traffic RRD file */
2033
	global $parsedcfg, $listtags;
2034
	$listtags = array("ds", "v", "rra", "row");
2035

    
2036
	$rrddbpath = "/var/db/rrd/";
2037
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2038

    
2039
	$rrdinterval = 60;
2040
	$valid = $rrdinterval * 2;
2041

    
2042
	/* Assume GigE for now */
2043
	$downstream = 125000000;
2044
	$upstream = 125000000;
2045

    
2046
	/* build a list of quality databases */
2047
	/* roundtrip has become delay */
2048
	function divide_delay($delayval) {
2049
		$delayval = floatval($delayval);
2050
		$delayval = ($delayval / 1000);
2051
		$delayval = " ". sprintf("%1.10e", $delayval) ." ";
2052
		return $delayval;
2053
	}
2054
	/* the roundtrip times need to be divided by 1000 to get seconds, really */
2055
	$databases = array();
2056
	if (!file_exists($rrddbpath)) {
2057
		@mkdir($rrddbpath);
2058
	}
2059
	chdir($rrddbpath);
2060
	$databases = glob("*-quality.rrd");
2061
	rsort($databases);
2062
	foreach ($databases as $database) {
2063
		$xmldump = "{$database}.old.xml";
2064
		$xmldumpnew = "{$database}.new.xml";
2065

    
2066
		if (is_platform_booting()) {
2067
			echo "Migrate RRD database {$database} to new format for IPv6 \n";
2068
		}
2069
		mwexec("$rrdtool tune {$rrddbpath}{$database} -r roundtrip:delay 2>&1");
2070

    
2071
		dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}");
2072
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2073
		$rrdold = $rrdold['rrd'];
2074

    
2075
		$i = 0;
2076
		foreach ($rrdold['rra'] as $rra) {
2077
			$l = 0;
2078
			foreach ($rra['database']['row'] as $row) {
2079
				$vnew = divide_delay($row['v'][1]);
2080
				$rrdold['rra'][$i]['database']['row'][$l]['v'][1] = $vnew;
2081
				$l++;
2082
			}
2083
			$i++;
2084
		}
2085

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

    
2089
		unset($rrdold);
2090
		@unlink("{$g['tmp_path']}/{$xmldump}");
2091
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2092
	}
2093

    
2094
	/* build a list of traffic and packets databases */
2095
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
2096
	rsort($databases);
2097
	foreach ($databases as $database) {
2098
		$databasetmp = "{$database}.tmp";
2099
		$xmldump = "{$database}.old.xml";
2100
		$xmldumptmp = "{$database}.tmp.xml";
2101
		$xmldumpnew = "{$database}.new.xml";
2102

    
2103
		if (is_platform_booting()) {
2104
			echo "Migrate RRD database {$database} to new format \n";
2105
		}
2106
		/* rename DS source */
2107
		mwexec("$rrdtool tune {$rrddbpath}/{$database} -r in:inpass 2>&1");
2108
		mwexec("$rrdtool tune {$rrddbpath}/{$database} -r out:outpass 2>71");
2109

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

    
2113
		/* create new rrd database file */
2114
		$rrdcreate = "$rrdtool create {$g['tmp_path']}/{$databasetmp} --step $rrdinterval ";
2115
		$rrdcreate .= "DS:inpass:COUNTER:$valid:0:$downstream ";
2116
		$rrdcreate .= "DS:outpass:COUNTER:$valid:0:$upstream ";
2117
		$rrdcreate .= "DS:inblock:COUNTER:$valid:0:$downstream ";
2118
		$rrdcreate .= "DS:outblock:COUNTER:$valid:0:$upstream ";
2119
		$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
2120
		$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
2121
		$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
2122
		$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
2123

    
2124
		create_new_rrd("$rrdcreate");
2125
		/* create temporary xml from new RRD */
2126
		dump_rrd_to_xml("{$g['tmp_path']}/{$databasetmp}", "{$g['tmp_path']}/{$xmldumptmp}");
2127

    
2128
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2129
		$rrdold = $rrdold['rrd'];
2130

    
2131
		$rrdnew = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldumptmp}"), 1, "tag");
2132
		$rrdnew = $rrdnew['rrd'];
2133

    
2134
		/* remove any MAX RRA's. Not needed for traffic. */
2135
		$i = 0;
2136
		foreach ($rrdold['rra'] as $rra) {
2137
			if (trim($rra['cf']) == "MAX") {
2138
				unset($rrdold['rra'][$i]);
2139
			}
2140
			$i++;
2141
		}
2142

    
2143
		file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", dump_xml_config_raw(migrate_rrd_format($rrdold, $rrdnew), "rrd"));
2144
		mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1");
2145
		/* we now have the rrd with the new fields, adjust the size now. */
2146
		/* RRA 2 is 60 minutes, RRA 3 is 720 minutes */
2147
		mwexec("/bin/sync");
2148
		mwexec("$rrdtool resize {$rrddbpath}/{$database} 2 GROW 2000;/bin/mv resize.rrd {$rrddbpath}/{$database} 2>&1");
2149
		mwexec("/bin/sync");
2150
		mwexec("$rrdtool resize {$rrddbpath}/{$database} 3 GROW 2000;/bin/mv resize.rrd {$rrddbpath}/{$database} 2>&1");
2151
		unset($rrdxmlarray);
2152
		@unlink("{$g['tmp_path']}/{$xmldump}");
2153
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2154
	}
2155
	if (!is_platform_booting()) {
2156
		enable_rrd_graphing();
2157
	}
2158
	/* Let's save the RRD graphs after we run enable RRD graphing */
2159
	/* The function will restore the rrd.tgz so we will save it after */
2160
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
2161
	unlink_if_exists("{$g['vardb_path']}/rrd/*.xml");
2162
	if (is_platform_booting()) {
2163
		echo "Updating configuration...";
2164
	}
2165
}
2166

    
2167

    
2168
function upgrade_055_to_056() {
2169
	config_init_path('ca');
2170
	config_init_path('cert');
2171
	$ca_config = config_get_path('ca');
2172
	$cert_config = config_get_path('cert');
2173
	$ipsec_config = config_get_path('ipsec');
2174

    
2175
	/* migrate ipsec ca's to cert manager */
2176
	if (is_array($ipsec_config['cacert'])) {
2177
		foreach ($ipsec_config['cacert'] as & $cacert) {
2178
			$ca = array();
2179
			$ca['refid'] = uniqid();
2180
			if (is_array($cacert['cert'])) {
2181
				$ca['crt'] = $cacert['cert'][0];
2182
			} else {
2183
				$ca['crt'] = $cacert['cert'];
2184
			}
2185
			$ca['descr'] = $cacert['ident'];
2186
			$ca_config[] = $ca;
2187
		}
2188
		unset($ipsec_config['cacert']);
2189
	}
2190

    
2191
	/* migrate phase1 certificates to cert manager */
2192
	if (is_array($ipsec_config['phase1'])) {
2193
		foreach ($ipsec_config['phase1'] as & $ph1ent) {
2194
			$cert = array();
2195
			$cert['refid'] = uniqid();
2196
			$cert['descr'] = "IPsec Peer {$ph1ent['remote-gateway']} Certificate";
2197
			if (is_array($ph1ent['cert'])) {
2198
				$cert['crt'] = $ph1ent['cert'][0];
2199
			} else {
2200
				$cert['crt'] = $ph1ent['cert'];
2201
			}
2202
			$cert['prv'] = $ph1ent['private-key'];
2203
			$cert_config[] = $cert;
2204
			$ph1ent['certref'] = $cert['refid'];
2205
			if ($ph1ent['cert']) {
2206
				unset($ph1ent['cert']);
2207
			}
2208
			if ($ph1ent['private-key']) {
2209
				unset($ph1ent['private-key']);
2210
			}
2211
			if ($ph1ent['peercert']) {
2212
				unset($ph1ent['peercert']);
2213
			}
2214
		}
2215
	}
2216

    
2217
	config_set_path('ca', $ca_config);
2218
	config_set_path('cert', $cert_config);
2219
	config_set_path('ipsec', $ipsec_config);
2220
}
2221

    
2222

    
2223
function upgrade_056_to_057() {
2224
	config_init_path('system/user');
2225
	$user_config = config_get_path('system/user');
2226

    
2227
	/* migrate captivate portal to user manager */
2228
	if (is_array(config_get_path('captiveportal/user'))) {
2229
		$nextuid = config_get_path('system/nextuid');
2230
		foreach (config_get_path('captiveportal/user', []) as $user) {
2231
			// avoid user conflicts
2232
			$found = false;
2233
			foreach ($user_config as $userent) {
2234
				if ($userent['name'] == $user['name']) {
2235
					$found = true;
2236
					break;
2237
				}
2238
			}
2239
			if ($found) {
2240
				continue;
2241
			}
2242
			$user['scope'] = "user";
2243
			if (isset($user['expirationdate'])) {
2244
				$user['expires'] = $user['expirationdate'];
2245
				unset($user['expirationdate']);
2246
			}
2247
			if (isset($user['password'])) {
2248
				$user['md5-hash'] = $user['password'];
2249
				unset($user['password']);
2250
			}
2251
			$user['uid'] = $nextuid++;
2252
			$user_config[] = $user;
2253
		}
2254
		config_del_path('captiveportal/user');
2255
		config_set_path('system/nextuid', $nextuid);
2256
		config_set_path('system/user', $user_config);
2257
	}
2258
}
2259

    
2260
function upgrade_057_to_058() {
2261
	/* set all phase2 entries to tunnel mode */
2262
	$ipsec_phase2_config = config_get_path('ipsec/phase2');
2263
	if (is_array($ipsec_phase2_config)) {
2264
		foreach ($ipsec_phase2_config as & $ph2ent) {
2265
			$ph2ent['mode'] = 'tunnel';
2266
		}
2267
		config_set_path('ipsec/phase2', $ipsec_phase2_config);
2268
	}
2269
}
2270

    
2271
function upgrade_058_to_059() {
2272
	$schedule_config = config_get_path('schedules/schedule');
2273
	if (is_array($schedule_config)) {
2274
		foreach ($schedule_config as & $schedl) {
2275
			$schedl['schedlabel'] = uniqid();
2276
		}
2277
		config_set_path('schedules/schedule', $schedule_config);
2278
	}
2279
}
2280

    
2281
function upgrade_059_to_060() {
2282
	require_once("/etc/inc/certs.inc");
2283
	config_init_path('ca');
2284
	config_init_path('cert');
2285
	$ca_config = config_get_path('ca');
2286
	$cert_config = config_get_path('cert');
2287
	if (is_array($ca_config)) {
2288
		/* Locate issuer for all CAs */
2289
		foreach ($ca_config as & $ca) {
2290
			$subject = cert_get_subject($ca['crt']);
2291
			$issuer = cert_get_issuer($ca['crt']);
2292
			if ($issuer <> $subject) {
2293
				$issuer_crt = lookup_ca_by_subject($issuer);
2294
				$issuer_crt = $issuer_crt['item'];
2295
				if ($issuer_crt) {
2296
					$ca['caref'] = $issuer_crt['refid'];
2297
				}
2298
			}
2299
		}
2300

    
2301
		/* Locate issuer for all certificates */
2302
		if (is_array($cert_config)) {
2303
			foreach ($cert_config as & $cert) {
2304
				$subject = cert_get_subject($cert['crt']);
2305
				$issuer = cert_get_issuer($cert['crt']);
2306
				if ($issuer <> $subject) {
2307
					$issuer_crt = lookup_ca_by_subject($issuer);
2308
					$issuer_crt = $issuer_crt['item'];
2309
					if ($issuer_crt) {
2310
						$cert['caref'] = $issuer_crt['refid'];
2311
					}
2312
				}
2313
			}
2314
		}
2315

    
2316
		config_set_path('ca', $ca_config);
2317
		config_set_path('cert', $cert_config);
2318
	}
2319
}
2320

    
2321
function upgrade_060_to_061() {
2322
	$if_config = config_get_path('interfaces');
2323

    
2324
	if (is_array($if_config['wan'])) {
2325
		config_set_path('interfaces/wan/enable', true);
2326
	}
2327
	if (is_array($if_config['lan'])) {
2328
		config_set_path('interfaces/lan/enable', true);
2329
	}
2330

    
2331
	/* On 1.2.3 the "mtu" field adjusted MSS.
2332
	   On 2.x the "mtu" field is actually the MTU. Rename accordingly.
2333
	   See redmine ticket #1886
2334
	*/
2335
	foreach ($if_config as $ifr => &$intf) {
2336
		if (isset($intf['mtu']) && is_numeric($intf['mtu'])) {
2337
			$intf['mss'] = $intf['mtu'];
2338
			unset($intf['mtu']);
2339
		}
2340
	}
2341
	config_set_path('interfaces', $if_config);
2342
}
2343

    
2344
function upgrade_061_to_062() {
2345
	$nat_rule_config = config_get_path('nat/rule');
2346

    
2347
	/* Convert NAT port forwarding rules */
2348
	if (is_array($nat_rule_config)) {
2349
		$a_nat = &$nat_rule_config;
2350

    
2351
		foreach ($a_nat as &$natent) {
2352
			$natent['disabled'] = false;
2353
			$natent['nordr']    = false;
2354

    
2355
			$natent['source'] = array(
2356
				"not"     => false,
2357
				"any"     => true,
2358
				"port"    => ""
2359
			);
2360

    
2361
			$natent['destination'] = array(
2362
				"not"     => false,
2363
				"address" => $natent['external-address'],
2364
				"port"    => $natent['external-port']
2365
			);
2366

    
2367
			if (empty($natent['destination']['address'])) {
2368
				unset($natent['destination']['address']);
2369
				$natent['destination']['network'] = $natent['interface'] . 'ip';
2370
			} else if ($natent['destination']['address'] == 'any') {
2371
				unset($natent['destination']['address']);
2372
				$natent['destination']['any'] = true;
2373
			}
2374

    
2375
			unset($natent['external-address']);
2376
			unset($natent['external-port']);
2377
		}
2378

    
2379
		unset($natent);
2380
		config_set_path('nat/rule', $nat_rule_config);
2381
	}
2382
}
2383

    
2384
function upgrade_062_to_063() {
2385
	/* Upgrade legacy Themes to the new pfsense_ng */
2386
	// Not supported in 2.3+
2387

    
2388
}
2389

    
2390
function upgrade_063_to_064() {
2391
	$j = 0;
2392
	config_init_path('ppps/ppp');
2393
	config_init_path('interfaces');
2394
	$ppp_config = config_get_path('ppps/ppp');
2395
	$ifcfg = config_get_path('interfaces');
2396
	$cron_config = config_get_path('cron/item');
2397

    
2398
	if (count($ppp_config)) {
2399
		foreach ($ppp_config as $pppid => &$ppp) {
2400
			$ppp['if'] = "ppp".$j;
2401
			$ppp['ptpid'] = $j;
2402
			$j++;
2403
			if (isset($ppp['port'])) {
2404
				$ppp['ports'] = $ppp['port'];
2405
				unset($ppp['port']);
2406
			}
2407
			if (!isset($ppp['type'])) {
2408
				$ppp['type'] = "ppp";
2409
			}
2410
			if (isset($ppp['defaultgw'])) {
2411
				unset($ppp['defaultgw']);
2412
			}
2413
		}
2414
	}
2415

    
2416
	$a_ppps = &$ppp_config;
2417

    
2418
	foreach ($ifcfg as $ifname => $ifinfo) {
2419
		$ppp = array();
2420
		// For pppoe conversion
2421
		if ($ifinfo['ipaddr'] == "pppoe" || $ifinfo['ipaddr'] == "pptp") {
2422
			if (isset($ifinfo['ptpid'])) {
2423
				continue;
2424
			}
2425
			$ppp['ptpid'] = $j;
2426
			$ppp['type'] = $ifinfo['ipaddr'];
2427
			$ppp['if'] = $ifinfo['ipaddr'].$j;
2428
			$ppp['ports'] = $ifinfo['if'];
2429
			if ($ifinfo['ipaddr'] == "pppoe") {
2430
				$ppp['username'] = $ifinfo['pppoe_username'];
2431
				$ppp['password'] = base64_encode($ifinfo['pppoe_password']);
2432
			}
2433
			if ($ifinfo['ipaddr'] == "pptp") {
2434
				$ppp['username'] = $ifinfo['pptp_username'];
2435
				$ppp['password'] = base64_encode($ifinfo['pptp_password']);
2436
			}
2437

    
2438
			if (isset($ifinfo['provider'])) {
2439
				$ppp['provider'] = $ifinfo['provider'];
2440
			}
2441
			if (isset($ifinfo['ondemand'])) {
2442
				$ppp['ondemand'] = true;
2443
			}
2444
			if (isset($ifinfo['timeout'])) {
2445
				$ppp['idletimeout'] = $ifinfo['timeout'];
2446
			}
2447
			if (isset($ifinfo['pppoe']['pppoe-reset-type'])) {
2448
				$ppp['pppoe-reset-type'] = $ifinfo['pppoe']['pppoe-reset-type'];
2449
				if (is_array($cron_config)) {
2450
					for ($i = 0; $i < count($cron_config); $i++) {
2451
						$item = $cron_config[$i];
2452
						if (strpos($item['command'], "/conf/pppoe{$ifname}restart") !== false) {
2453
							$cron_config[$i]['command'] = "/var/etc/pppoe_restart_" . $ppp['if'];
2454
						}
2455
					}
2456
				}
2457
			}
2458
			if (isset($ifinfo['local'])) {
2459
				$ppp['localip'] = $ifinfo['local'];
2460
			}
2461
			if (isset($ifinfo['subnet'])) {
2462
				$ppp['subnet'] = $ifinfo['subnet'];
2463
			}
2464
			if (isset($ifinfo['remote'])) {
2465
				$ppp['gateway'] = $ifinfo['remote'];
2466
			}
2467

    
2468
			$ifcfg[$ifname]['if'] = $ifinfo['ipaddr'].$j;
2469
			$j++;
2470

    
2471
			unset($ifcfg[$ifname]['pppoe_username']);
2472
			unset($ifcfg[$ifname]['pppoe_password']);
2473
			unset($ifcfg[$ifname]['provider']);
2474
			unset($ifcfg[$ifname]['ondemand']);
2475
			unset($ifcfg[$ifname]['timeout']);
2476
			unset($ifcfg[$ifname]['pppoe_reset']);
2477
			unset($ifcfg[$ifname]['pppoe_preset']);
2478
			unset($ifcfg[$ifname]['pppoe']);
2479
			unset($ifcfg[$ifname]['pptp_username']);
2480
			unset($ifcfg[$ifname]['pptp_password']);
2481
			unset($ifcfg[$ifname]['local']);
2482
			unset($ifcfg[$ifname]['subnet']);
2483
			unset($ifcfg[$ifname]['remote']);
2484

    
2485
			$a_ppps[] = $ppp;
2486

    
2487
		}
2488
	}
2489

    
2490
	if ($ppp_config !== null) {
2491
		config_set_path('ppps/ppp', $ppp_config);
2492
	}
2493
	if ($ifcfg !== null) {
2494
		config_set_path('interfaces', $ifcfg);
2495
	}
2496
	if ($cron_config !== null) {
2497
		config_set_path('cron/item', $cron_config);
2498
	}
2499
}
2500

    
2501
function upgrade_064_to_065() {
2502
	/* Disable TSO and LRO in upgraded configs */
2503
	config_set_path('system/disablesegmentationoffloading', true);
2504
	config_set_path('system/disablelargereceiveoffloading', true);
2505
}
2506

    
2507
function upgrade_065_to_066() {
2508
	config_init_path('dhcrelay');
2509
	$dhcrelaycfg = config_get_path('dhcrelay');
2510

    
2511
	if (is_array($dhcrelaycfg)) {
2512
		$dhcrelayifs = array();
2513
		$foundifs = false;
2514
		/* DHCPRelay enabled on any interfaces? */
2515
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
2516
			if (isset($dhcrelayifconf['enable'])) {
2517
				$dhcrelayifs[] = $dhcrelayif;
2518
				unset($dhcrelaycfg['dhcrelayif']);
2519
				$foundifs = true;
2520
			}
2521
		}
2522
		if ($foundifs == true) {
2523
			$dhcrelaycfg['interface'] = implode(",", $dhcrelayifs);
2524
		}
2525
		config_set_path('dhcrelay', $dhcrelaycfg);
2526
	}
2527
}
2528

    
2529
function upgrade_066_to_067() {
2530
	if (config_get_path('system/ca') !== null) {
2531
		config_set_path('ca', config_get_path('system/ca'));
2532
		config_del_path('system/ca');
2533
	}
2534
	if (config_get_path('system/cert') !== null) {
2535
		config_set_path('cert', config_get_path('system/cert'));
2536
		config_del_path('system/cert');
2537
	}
2538
}
2539

    
2540
function upgrade_067_to_068() {
2541
	$pppoe_config = config_get_path('pppoe');
2542
	if (!empty($pppoe_config)) {
2543
		config_set_path('pppoes/pppoe/0', $pppoe_config[0]);
2544

    
2545
		if (is_array($pppoe_config['user'])) {
2546
			$username = array();
2547
			foreach ($pppoe_config['user'] as $user) {
2548
				$usr = $user['name'] . ":" . base64_encode($user['password']);
2549
				if ($user['ip']) {
2550
					$usr .= ":{$user['ip']}";
2551
				}
2552
				$username[] = $usr;
2553
			}
2554
			config_set_path('pppoes/pppoe/0/username', implode(" ", $username));
2555
		}
2556
		config_del_path('pppoe');
2557
	}
2558
}
2559

    
2560
function upgrade_068_to_069() {
2561
	$user_config = config_get_path('system/user');
2562
	if (!is_array($user_config)) {
2563
		return;
2564
	}
2565

    
2566
	foreach ($user_config as & $user) {
2567
		if (!is_array($user['cert'])) {
2568
			continue;
2569
		}
2570
		$rids = array();
2571
		foreach ($user['cert'] as $id => $cert) {
2572
			if (!isset($cert['descr'])) {
2573
				continue;
2574
			}
2575
			$tcert = $cert;
2576
			// Make sure each cert gets a refid
2577
			if (!isset($tcert['refid'])) {
2578
				$tcert['refid'] = uniqid();
2579
			}
2580
			// Keep the cert references for this user
2581
			$rids[] = $tcert['refid'];
2582
			config_set_path('cert/', $tcert);
2583
		}
2584
		// Replace user certs with cert references instead.
2585
		if (count($rids) > 0) {
2586
			$user['cert'] = $rids;
2587
		}
2588
	}
2589
	config_set_path('system/user', $user_config);
2590
}
2591

    
2592
function upgrade_069_to_070() {
2593
	$binat_config = config_get_path('nat/onetoone');
2594
	/* Convert NAT 1:1 rules */
2595
	if (is_array($binat_config)) {
2596
		foreach ($binat_config as $nidx => &$natent) {
2597
			if ($natent['subnet'] == 32) {
2598
				$natent[$nidx]['source'] = array("address" => $natent['internal']);
2599
			} else {
2600
				$natent[$nidx]['source'] = array("address" => $natent['internal'] . "/" . $natent['subnet']);
2601
			}
2602

    
2603
			$natent[$nidx]['destination'] = array("any" => true);
2604

    
2605
			unset($natent[$nidx]['internal']);
2606
			unset($natent[$nidx]['subnet']);
2607
		}
2608

    
2609
		unset($natent);
2610
		config_set_path('nat/onetoone', $binat_config);
2611
	}
2612
}
2613

    
2614
function upgrade_070_to_071() {
2615
	$cron_config = config_get_path('cron/item');
2616

    
2617
	if (is_array($cron_config)) {
2618
		foreach ($cron_config as $idx => $cronitem) {
2619
			if (stristr($cronitem['command'], "checkreload.sh")) {
2620
				config_del_path("cron/item/{$idx}");
2621
				break;
2622
			}
2623
		}
2624
	}
2625
}
2626

    
2627
function rename_field(& $section, $oldname, $newname) {
2628
	if (is_array($section)) {
2629
		foreach ($section as & $item) {
2630
			if (is_array($item) && !empty($item[$oldname])) {
2631
				$item[$newname] = $item[$oldname];
2632
			}
2633
			if (is_array($item) && isset($item[$oldname])) {
2634
				unset($item[$oldname]);
2635
			}
2636
		}
2637
	}
2638
}
2639

    
2640
function upgrade_071_to_072() {
2641
	$sysctl_config = config_get_path('sysctl/item');
2642
	if (is_array($sysctl_config)) {
2643
		rename_field($sysctl_config, 'desc', 'descr');
2644
		config_set_path('sysctl/item', $sysctl_config);
2645
	}
2646
}
2647

    
2648
function upgrade_072_to_073() {
2649
	$loadbalancer_config = config_get_path('load_balancer');
2650
	if (!is_array($loadbalancer_config)) {
2651
		return;
2652
	}
2653
	if (is_array($loadbalancer_config['monitor_type'])) {
2654
		rename_field($loadbalancer_config['monitor_type'], 'desc', 'descr');
2655
	}
2656
	if (is_array($loadbalancer_config['lbpool'])) {
2657
		rename_field($loadbalancer_config['lbpool'], 'desc', 'descr');
2658
	}
2659
	if (is_array($loadbalancer_config['lbaction'])) {
2660
		rename_field($loadbalancer_config['lbaction'], 'desc', 'descr');
2661
	}
2662
	if (is_array($loadbalancer_config['lbprotocol'])) {
2663
		rename_field($loadbalancer_config['lbprotocol'], 'desc', 'descr');
2664
	}
2665
	if (is_array($loadbalancer_config['virtual_server'])) {
2666
		rename_field($loadbalancer_config['virtual_server'], 'desc', 'descr');
2667
	}
2668
	config_set_path('load_balancer', $loadbalancer_config);
2669
}
2670

    
2671
function upgrade_073_to_074() {
2672
	$user_config = config_get_path('system/user');
2673
	rename_field($user_config, 'fullname', 'descr');
2674
	config_set_path('system/user', $user_config);
2675
}
2676

    
2677
function upgrade_074_to_075() {
2678
	$ca_config = config_get_path('ca');
2679
	$cert_config = config_get_path('cert');
2680
	$crl_config = config_get_path('crl');
2681
	if (is_array($ca_config)) {
2682
		rename_field($ca_config, 'name', 'descr');
2683
		config_set_path('ca', $ca_config);
2684
	}
2685
	if (is_array($cert_config)) {
2686
		rename_field($cert_config, 'name', 'descr');
2687
		config_set_path('cert', $cert_config);
2688
	}
2689
	if (is_array($crl_config)) {
2690
		rename_field($crl_config, 'name', 'descr');
2691
		config_set_path('crl', $crl_config);
2692
	}
2693
}
2694

    
2695
function upgrade_075_to_076() {
2696
	$cron_config = config_get_path('cron/item');
2697
	$cron_config[] = [
2698
		'minute' => '30',
2699
		'hour' => '12',
2700
		'mday' => '*',
2701
		'month' => '*',
2702
		'wday' => '*',
2703
		'who' => 'root',
2704
		'command' => '/usr/bin/nice -n20 /etc/rc.update_urltables'
2705
	];
2706
	config_set_path('cron/item', $cron_config);
2707
}
2708

    
2709
function upgrade_076_to_077() {
2710
	$filter_rule_config = config_get_path('filter/rule');
2711
	foreach ($filter_rule_config as & $rule) {
2712
		if (isset($rule['protocol']) && !empty($rule['protocol'])) {
2713
			$rule['protocol'] = strtolower($rule['protocol']);
2714
		}
2715
	}
2716
	config_set_path('filter/rule', $filter_rule_config);
2717
}
2718

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

    
2748
function upgrade_079_to_080() {
2749
	$username_config = config_get_path('system/username');
2750
	$carp_pkg_config = config_get_path('installedpackages/carpsettings/config');
2751
	/* Upgrade config in 1.2.3 specifying a username other than admin for syncing. */
2752
	if (!empty($username_config) && is_array($carp_pkg_config)) {
2753
		$carp_pkg_config[0]['username'] = $username_config;
2754
		config_del_path('system/username');
2755
		config_set_path('installedpackages/carpsettings/config', $carp_pkg_config);
2756
	}
2757
}
2758

    
2759
function upgrade_080_to_081() {
2760
	global $g;
2761
	/* Welcome to the 2.1 migration path */
2762

    
2763
	/* tag all the existing gateways as being IPv4 */
2764
	$gateways_config = config_get_path('gateways/gateway_item');
2765
	if (is_array($gateways_config)) {
2766
		foreach ($gateways_config as &$gw) {
2767
			$gw['ipprotocol'] = "inet";
2768
		}
2769
		config_set_path('gateways/gateway_item', $gateways_config);
2770
	}
2771

    
2772
	/* RRD files changed for quality, traffic and packets graphs */
2773
	/* convert traffic RRD file */
2774
	global $parsedcfg, $listtags;
2775
	$listtags = array("ds", "v", "rra", "row");
2776

    
2777
	$rrddbpath = "/var/db/rrd/";
2778
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2779

    
2780
	$rrdinterval = 60;
2781
	$valid = $rrdinterval * 2;
2782

    
2783
	/* Assume GigE for now */
2784
	$downstream = 125000000;
2785
	$upstream = 125000000;
2786

    
2787
	/* build a list of traffic and packets databases */
2788
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
2789
	rsort($databases);
2790
	foreach ($databases as $database) {
2791
		$xmldump = "{$database}.old.xml";
2792
		$xmldumpnew = "{$database}.new.xml";
2793

    
2794
		if (is_platform_booting()) {
2795
			echo "Migrate RRD database {$database} to new format for IPv6.\n";
2796
		}
2797

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

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

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

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

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

    
2850
				<!-- PDP Status -->
2851
				<last_ds> 0 </last_ds>
2852
				<value> NaN </value>
2853
				<unknown_sec> 3 </unknown_sec>
2854
			</ds>
2855
			";
2856

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

    
2889
		$value_search = "<\/row>";
2890
		$value_replace = "</row>";
2891
		$value = "<v> NaN </v>";
2892

    
2893
		$xml = file_get_contents("{$g['tmp_path']}/{$xmldump}");
2894
		foreach ($ds_arr as $ds) {
2895
			$xml = preg_replace("/{$ds_search}/s", "$ds{$ds_search}", $xml);
2896
		}
2897
		foreach ($cdp_arr as $cdp) {
2898
			$xml = preg_replace("/{$cdp_search}/s", "$cdp{$cdp_replace}", $xml);
2899
		}
2900
		foreach ($ds_arr as $ds) {
2901
			$xml = preg_replace("/{$value_search}/s", "$value{$value_replace}", $xml);
2902
		}
2903

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

    
2930
function upgrade_081_to_082() {
2931
	/* don't enable the allow IPv6 toggle */
2932
}
2933

    
2934
function upgrade_082_to_083() {
2935
	/* Upgrade captiveportal config */
2936
	$cp_config = config_get_path('captiveportal');
2937
	if (!empty($cp_config)) {
2938
		$cp_config['cpzone'] = $cp_config;
2939
		$cp_config['cpzone']['zoneid'] = 8000;
2940
		$cp_config['cpzone']['zone'] = "cpzone";
2941
		if ($cp_config['cpzone']['auth_method'] == "radius") {
2942
			$cp_config['cpzone']['radius_protocol'] = "PAP";
2943
		}
2944
		config_set_path('captiveportal', $cp_config);
2945
	}
2946
	$voucher_config = config_get_path('voucher');
2947
	if (!empty($voucher_config)) {
2948
		$voucher_config['cpzone'] = $voucher_config;
2949
		config_set_path('voucher', $voucher_config);
2950
	}
2951
}
2952

    
2953
function upgrade_083_to_084() {
2954
	if (config_get_path('hasync') === null) {
2955
		if (!empty(config_get_path('installedpackages/carpsettings/config'))) {
2956
			config_set_path('hasync', config_get_path('installedpackages/carpsettings/config/0'));
2957
			config_del_path('installedpackages/carpsettings');
2958
		}
2959
		if (empty(config_get_path('installedpackages/carpsettings')) && (config_get_path('installedpackages/carpsettings') !== null)) {
2960
			config_del_path('installedpackages/carpsettings');
2961
		}
2962
		if (empty(config_get_path('installedpackages')) && (config_get_path('installedpackages') !== null)) {
2963
			config_del_path('installedpackages');
2964
		}
2965
	}
2966
}
2967

    
2968
function upgrade_084_to_085() {
2969
	$gateway_group_arr = array();
2970
	$gateways = get_gateways();
2971
	$oldnames = array();
2972
	/* setup translation array */
2973
	foreach ($gateways as $name => $gw) {
2974
		if (isset($gw['dynamic'])) {
2975
			$oldname = strtoupper(config_get_path("interfaces/{$gw['friendlyiface']}/descr"));
2976
			$oldnames[$oldname] = $name;
2977
		} else {
2978
			$oldnames[$name] = $name;
2979
		}
2980
	}
2981

    
2982
	/* process the old array */
2983
	if (is_array(config_get_path('gateways/gateway_group'))) {
2984
		$group_array_new = array();
2985
		foreach (config_get_path('gateways/gateway_group', []) as $name => $group) {
2986
			if (is_array($group['item'])) {
2987
				$newlist = array();
2988
				foreach ($group['item'] as $entry) {
2989
					$elements = explode("|", $entry);
2990
					if ($oldnames[$elements[0]] <> "") {
2991
						$newlist[] = "{$oldnames[$elements[0]]}|{$elements[1]}";
2992
					} else {
2993
						$newlist[] = "{$elements[0]}|{$elements[1]}";
2994
					}
2995
				}
2996
				$group['item'] = $newlist;
2997
				$group_array_new[$name] = $group;
2998
			}
2999
		}
3000
		config_set_path('gateways/gateway_group', $group_array_new);
3001
	}
3002
	/* rename old Quality RRD files in the process */
3003
	$rrddbpath = "/var/db/rrd";
3004
	foreach ($oldnames as $old => $new) {
3005
		if (is_readable("{$rrddbpath}/{$old}-quality.rrd")) {
3006
			@rename("{$rrddbpath}/{$old}-quality.rrd", "{$rrddbpath}/{$new}-quality.rrd");
3007
		}
3008
	}
3009
	unset($gateways, $oldnames, $gateway_group_arr);
3010
}
3011

    
3012
function upgrade_085_to_086() {
3013
	$temp_config = config_get_path('');
3014

    
3015
	/* XXX: Gross hacks in sight */
3016
	if (is_array($temp_config['virtualip']['vip'])) {
3017
		$vipchg = array();
3018
		foreach ($temp_config['virtualip']['vip'] as $vip) {
3019
			if ($vip['mode'] != "carp") {
3020
				continue;
3021
			}
3022
			$temp_config = array_replace_values_recursive(
3023
				$temp_config,
3024
				'^vip' . $vip['vhid'] . '$',
3025
				"{$vip['interface']}_vip{$vip['vhid']}"
3026
			);
3027
		}
3028
		config_set_path('', $temp_config);
3029
	}
3030
}
3031

    
3032
function upgrade_086_to_087() {
3033
	global $dummynet_pipe_list;
3034

    
3035
	$shaper_config = config_get_path('dnshaper/queue');
3036
	if (!is_array($shaper_config)) {
3037
		return;
3038
	}
3039

    
3040
	$dnqueue_number = 1;
3041
	$dnpipe_number = 1;
3042

    
3043
	foreach ($shaper_config as &$dnpipe) {
3044
		$dnpipe['number'] = $dnpipe_number;
3045
		$dnpipe_number++;
3046
		if (is_array($dnpipe['queue'])) {
3047
			foreach ($dnpipe['queue'] as &$dnqueue) {
3048
				$dnqueue['number'] = $dnqueue_number;
3049
				$dnqueue_number++;
3050
			}
3051
		}
3052
	}
3053

    
3054
	unset($dnqueue_number, $dnpipe_number, $dnpipe, $dnqueue);
3055
	config_set_path('dnshaper/queue', $shaper_config);
3056

    
3057
	$filter_rule_config = config_get_path('filter/rule');
3058
	if (!is_array($filter_rule_config)) {
3059
		return;
3060
	}
3061

    
3062
	require_once("shaper.inc");
3063
	read_dummynet_config();
3064

    
3065
	$dn_list = array();
3066
	if (is_array($dummynet_pipe_list)) {
3067
		foreach ($dummynet_pipe_list as $dn) {
3068
			$tmplist =& $dn->get_queue_list();
3069
			foreach ($tmplist as $qname => $link) {
3070
				$dn_list[$link] = $qname;
3071
			}
3072
		}
3073
		unset($dummynet_pipe_list);
3074
	}
3075

    
3076
	foreach ($filter_rule_config as &$rule) {
3077
		if (!empty($rule['dnpipe'])) {
3078
			if (!empty($dn_list[$rule['dnpipe']])) {
3079
				$rule['dnpipe'] = $dn_list[$rule['dnpipe']];
3080
			}
3081
		}
3082
		if (!empty($rule['pdnpipe'])) {
3083
			if (!empty($dn_list[$rule['pdnpipe']])) {
3084
				$rule['pdnpipe'] = $dn_list[$rule['pdnpipe']];
3085
			}
3086
		}
3087
	}
3088
	config_set_path('filter/rule', $filter_rule_config);
3089
}
3090
function upgrade_087_to_088() {
3091
	if (config_path_enabled('system', 'glxsb_enable')) {
3092
		config_del_path('system/glxsb_enable');
3093
		config_set_path('system/crypto_hardware', 'glxsb');
3094
	}
3095
}
3096

    
3097
function upgrade_088_to_089() {
3098
	config_init_path('ca');
3099
	config_init_path('cert');
3100
	$ca_config = config_get_path('ca');
3101
	$cert_config = config_get_path('cert');
3102
	$cp_config = config_get_path('captiveportal');
3103

    
3104
	/* migrate captive portal ssl to certificate manager */
3105
	if (is_array($cp_config)) {
3106
		foreach ($cp_config as &$setting) {
3107
			if (isset($setting['httpslogin'])) {
3108
				/* create cert entry */
3109
				$cert = array();
3110
				$cert['refid'] = uniqid();
3111
				$cert['descr'] = "Captive Portal Cert - {$setting['zone']}";
3112
				$cert['crt'] = $setting['certificate'];
3113
				$cert['prv'] = $setting['private-key'];
3114

    
3115
				if (!empty($setting['cacertificate'])) {
3116
					/* create ca entry */
3117
					$ca = array();
3118
					$ca['refid'] = uniqid();
3119
					$ca['descr'] = "Captive Portal CA - {$setting['zone']}";
3120
					$ca['crt'] = $setting['cacertificate'];
3121
					$ca_config[] = $ca;
3122

    
3123
					/* add ca reference to certificate */
3124
					$cert['caref'] = $ca['refid'];
3125
				}
3126

    
3127
				$cert_config[] = $cert;
3128

    
3129
				/* create cert reference */
3130
				$setting['certref'] = $cert['refid'];
3131

    
3132
				unset($setting['certificate']);
3133
				unset($setting['private-key']);
3134
				unset($setting['cacertificate']);
3135

    
3136
			}
3137
		}
3138
		config_set_path('ca', $ca_config);
3139
		config_set_path('cert', $cert_config);
3140
		config_set_path('captiveportal', $cp_config);
3141
	}
3142
}
3143

    
3144
function upgrade_089_to_090() {
3145
	$loadbalancer_config = config_get_path('load_balancer/virtual_server');
3146
	if (is_array($loadbalancer_config) && count($loadbalancer_config)) {
3147
		$vs_a = &$loadbalancer_config;
3148
		for ($i = 0; isset($vs_a[$i]); $i++) {
3149
			if (is_array($vs_a[$i]['pool'])) {
3150
				$vs_a[$i]['poolname'] = $vs_a[$i]['pool'][0];
3151
				unset($vs_a[$i]['pool']);
3152
			} elseif (!empty($vs_a[$i]['pool'])) {
3153
				$vs_a[$i]['poolname'] = $vs_a[$i]['pool'];
3154
				unset($vs_a[$i]['pool']);
3155
			}
3156
		}
3157
		config_set_path('load_balancer/virtual_server', $loadbalancer_config);
3158
	}
3159
}
3160

    
3161
function upgrade_090_to_091() {
3162
	$shaper_config = config_get_path('dnshaper/queue');
3163

    
3164
	if (is_array($shaper_config)) {
3165
		foreach ($shaper_config as &$dnqueue) {
3166
			if (!empty($dnqueue['bandwidth'])) {
3167
				$bw = array();
3168
				$bw['bw'] = $dnqueue['bandwidth'];
3169
				$bw['bwscale'] = $dnqueue['bandwidthtype'];
3170
				$bw['bwsched'] = "none";
3171
				$dnqueue['bandwidth']['item'] = [$bw];
3172
			}
3173
		}
3174
		config_set_path('dnshaper/queue', $shaper_config);
3175
	}
3176
}
3177

    
3178
function upgrade_091_to_092() {
3179
	$nat_rule_config = config_get_path('nat/advancedoutbound/rule');
3180

    
3181
	if (is_array($nat_rule_config)) {
3182
		$nat_rules = &$nat_rule_config;
3183
		for ($i = 0; isset($nat_rules[$i]); $i++) {
3184
			if (empty($nat_rules[$i]['interface'])) {
3185
				$nat_rules[$i]['interface'] = 'wan';
3186
			}
3187
		}
3188
		config_set_path('nat/advancedoutbound/rule', $nat_rule_config);
3189
	}
3190
}
3191

    
3192
function upgrade_092_to_093() {
3193
	global $g;
3194

    
3195
	$suffixes = array("concurrent", "loggedin");
3196

    
3197
	foreach ($suffixes as $suffix) {
3198
		if (file_exists("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd")) {
3199
			rename("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd",
3200
				"{$g['vardb_path']}/rrd/captiveportal-cpZone-{$suffix}.rrd");
3201
		}
3202
	}
3203

    
3204
	if (!is_platform_booting()) {
3205
		enable_rrd_graphing();
3206
	}
3207
}
3208

    
3209
function upgrade_093_to_094() {
3210
	if (config_get_path('system/powerd_mode') !== null) {
3211
		config_set_path('system/powerd_ac_mode', config_get_path('system/powerd_mode'));
3212
		config_set_path('system/powerd_battery_mode', config_get_path('system/powerd_mode'));
3213
		config_del_path('system/powerd_mode');
3214
	}
3215
}
3216

    
3217
function upgrade_094_to_095() {
3218
	$if_config = config_get_path('interfaces');
3219
	if (!is_array($if_config)) {
3220
		return;
3221
	}
3222

    
3223
	foreach ($if_config as &$cfg) {
3224
		if (isset($cfg['ipaddrv6']) && ($cfg['ipaddrv6'] == "track6")) {
3225
			if (!isset($cfg['track6-prefix-id']) || ($cfg['track6-prefix-id'] == "")) {
3226
				$cfg['track6-prefix-id'] = 0;
3227
			}
3228
		}
3229
	}
3230
	config_set_path('interfaces', $if_config);
3231
}
3232

    
3233
function upgrade_095_to_096() {
3234
	global $g;
3235

    
3236
	$names = array("inpass", "outpass", "inblock", "outblock",
3237
		"inpass6", "outpass6", "inblock6", "outblock6");
3238
	$rrddbpath = "/var/db/rrd";
3239
	$rrdtool = "/usr/local/bin/rrdtool";
3240

    
3241
	/* Assume 2*10GigE for now */
3242
	$stream = 2500000000;
3243

    
3244
	/* build a list of traffic and packets databases */
3245
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
3246
	rsort($databases);
3247
	foreach ($databases as $database) {
3248
		if (is_platform_booting()) {
3249
			echo "Update RRD database {$database}.\n";
3250
		}
3251

    
3252
		$cmd = "{$rrdtool} tune {$rrddbpath}/{$database}";
3253
		foreach ($names as $name) {
3254
			$cmd .= " -a {$name}:{$stream}";
3255
		}
3256
		mwexec("{$cmd} 2>&1");
3257

    
3258
	}
3259
	if (!is_platform_booting()) {
3260
		enable_rrd_graphing();
3261
	}
3262
	/* Let's save the RRD graphs after we run enable RRD graphing */
3263
	/* The function will restore the rrd.tgz so we will save it after */
3264
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
3265
}
3266

    
3267
function upgrade_096_to_097() {
3268
	global $g;
3269
	/* If the user had disabled default block rule logging before, then bogon/private network logging was already off, so respect their choice. */
3270
	if (config_path_enabled('syslog', 'nologdefaultblock')) {
3271
		config_set_path('syslog/nologbogons', true);
3272
		config_set_path('syslog/nologprivatenets', true);
3273
	}
3274
}
3275

    
3276
function upgrade_097_to_098() {
3277
	// no longer used (used to set kill_states)
3278
	return;
3279
}
3280

    
3281
function upgrade_098_to_099() {
3282
	$dhcpd_config = config_get_path('dhcpd');
3283

    
3284
	if (!is_array($dhcpd_config)) {
3285
		return;
3286
	}
3287

    
3288
	foreach ($dhcpd_config as & $dhcpifconf) {
3289
		if (isset($dhcpifconf['next-server'])) {
3290
			$dhcpifconf['nextserver'] = $dhcpifconf['next-server'];
3291
			unset($dhcpifconf['next-server']);
3292
		}
3293
	}
3294
	config_set_path('dhcpd', $dhcpd_config);
3295
}
3296

    
3297
function upgrade_099_to_100() {
3298
	require_once("/etc/inc/services.inc");
3299
	/* See #7146 for detail on why the extra parameters are needed for the time being. */
3300
	install_cron_job("/usr/bin/nice -n20 newsyslog", false, null, null, null, null, null, null, false);
3301
}
3302

    
3303
function upgrade_100_to_101() {
3304
	global $g;
3305

    
3306
	$voucher_config = config_get_path('voucher');
3307

    
3308
	if (!is_array($voucher_config)) {
3309
		return;
3310
	}
3311

    
3312
	foreach ($voucher_config as &$cp) {
3313
		if (!is_array($cp['roll'])) {
3314
			continue;
3315
		}
3316
		foreach ($cp['roll'] as &$rcfg) {
3317
			if (!empty($rcfg['comment'])) {
3318
				$rcfg['descr'] = $rcfg['comment'];
3319
			}
3320
		}
3321
	}
3322
	config_set_path('voucher', $voucher_config);
3323
}
3324

    
3325
function upgrade_101_to_102() {
3326
	global $g;
3327

    
3328
	$cp_config = config_get_path('captiveportal');
3329
	if (is_array($cp_config)) {
3330
		foreach ($cp_config as &$cp) {
3331
			if (!is_array($cp['passthrumac'])) {
3332
				continue;
3333
			}
3334

    
3335
			foreach ($cp['passthrumac'] as &$passthrumac) {
3336
				$passthrumac['action'] = 'pass';
3337
			}
3338
		}
3339
		config_set_path('captiveportal', $cp_config);
3340
	}
3341

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

    
3364
function upgrade_102_to_103() {
3365
	if (config_get_path('nat/advancedoutbound') !== null) {
3366
		config_set_path('nat/advancedoutbound/mode', "advanced");
3367
		config_del_path('nat/advancedoutbound/enable');
3368
	} else {
3369
		config_set_path('nat/advancedoutbound/mode', "automatic");
3370
	}
3371

    
3372
	config_set_path('nat/outbound', config_get_path('nat/advancedoutbound'));
3373
	config_del_path('nat/ipsecpassthru');
3374
	config_del_path('nat/advancedoutbound');
3375
}
3376

    
3377
function upgrade_103_to_104() {
3378
	$changed_privs = array(
3379
		"page-diag-system-activity" => "page-diagnostics-system-activity",
3380
		"page-interfacess-groups" => "page-interfaces-groups",
3381
		"page-interfacess-lagg" => "page-interfaces-lagg",
3382
		"page-interfacess-qinq" => "page-interfaces-qinq"
3383
	);
3384

    
3385
	$user_config = config_get_path('system/user', []);
3386
	$group_config = config_get_path('system/group', []);
3387

    
3388
	/* update user privileges */
3389
	foreach ($user_config as & $user) {
3390
		if (!is_array($user['priv'])) {
3391
			continue;
3392
		}
3393
		foreach ($user['priv'] as & $priv) {
3394
			if (array_key_exists($priv, $changed_privs)) {
3395
				$priv = $changed_privs[$priv];
3396
			}
3397
		}
3398
	}
3399

    
3400
	/* update group privileges */
3401
	foreach ($group_config as & $group) {
3402
		if (!is_array($group['priv'])) {
3403
			continue;
3404
		}
3405
		foreach ($group['priv'] as & $priv) {
3406
			if (array_key_exists($priv, $changed_privs)) {
3407
				$priv = $changed_privs[$priv];
3408
			}
3409
		}
3410
	}
3411

    
3412

    
3413
	config_set_path('system/user', $user_config);
3414
	config_set_path('system/group', $group_config);
3415

    
3416
	/* sync all local account information */
3417
	local_reset_accounts();
3418
}
3419

    
3420
function upgrade_104_to_105() {
3421
	$cp_config = config_get_path('captiveportal');
3422

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

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

    
3443
function upgrade_106_to_107() {
3444
	$filter_rule_config = config_get_path('filter/rule');
3445

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

    
3471
function upgrade_107_to_108() {
3472
	if (config_path_enabled('system/webgui', 'noautocomplete')) {
3473
		config_del_path('system/webgui/noautocomplete');
3474
	} else {
3475
		config_set_path('system/webgui/loginautocomplete', true);
3476
	}
3477
}
3478

    
3479
function upgrade_108_to_109() {
3480
	$filter_rule_config = config_get_path('filter/rule');
3481

    
3482
	if (!is_array($filter_rule_config)) {
3483
		return;
3484
	}
3485

    
3486
	foreach ($filter_rule_config 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
	config_set_path('filter/rule', $filter_rule_config);
3498
}
3499

    
3500
function upgrade_109_to_110() {
3501
	$ipsec_phase2_config = config_get_path('ipsec/phase2');
3502

    
3503
	if (!is_array($ipsec_phase2_config)) {
3504
		return;
3505
	}
3506

    
3507
	foreach ($ipsec_phase2_config as &$rule) {
3508
		if (!empty($rule['uniqid'])) {
3509
			continue;
3510
		}
3511

    
3512
		$rule['uniqid'] = uniqid();
3513
	}
3514
	config_set_path('ipsec/phase2', $ipsec_phase2_config);
3515
}
3516

    
3517
function upgrade_110_to_111() {
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
	$menu_pkg_config = config_get_path('installedpackages/menu');
3533
	if (is_array($menu_pkg_config)) {
3534
		foreach ($menu_pkg_config as $idx => $menu) {
3535
			if ($menu['name'] != 'Unbound DNS') {
3536
				continue;
3537
			}
3538

    
3539
			unset($menu_pkg_config[$idx]);
3540
			break;
3541
		}
3542
		config_set_path('installedpackages/menu', $menu_pkg_config);
3543
	}
3544

    
3545
	$service_pkg_config = config_get_path('installedpackages/service');
3546
	if (is_array($service_pkg_config)) {
3547
		foreach ($service_pkg_config as $idx => $service) {
3548
			if ($service['name'] != 'unbound') {
3549
				continue;
3550
			}
3551
			unset($service_pkg_config[$idx]);
3552
			break;
3553
		}
3554
		config_set_path('installedpackages/service', $service_pkg_config);
3555
	}
3556

    
3557
	$pkg = config_get_path('installedpackages/unbound/config/0');
3558
	if (!isset($pkg)) {
3559
		return;
3560
	}
3561

    
3562
	$pkg = array_merge($pkg, config_get_path('installedpackages/unboundadvanced/config/0', []));
3563

    
3564
	$new = array();
3565

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

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

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

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

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

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

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

    
3641
	config_set_path('unbound', $new);
3642
	config_del_path('installedpackages/unbound');
3643
	config_del_path('installedpackages/unboundadvanced');
3644
	config_del_path('installedpackages/unboundacls');
3645

    
3646
	unset($pkg, $new);
3647
}
3648

    
3649
function upgrade_111_to_112() {
3650
	$cron_config = config_get_path('cron/item');
3651

    
3652
	$cron_config[] = array(
3653
		'minute' => '*/60',
3654
		'hour' => '*',
3655
		'mday' => '*',
3656
		'month' => '*',
3657
		'wday' => '*',
3658
		'who' => 'root',
3659
		'command' => '/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 webConfiguratorlockout'
3660
	);
3661
}
3662

    
3663
function upgrade_112_to_113() {
3664
	if (config_path_enabled('notifications/smtp', 'ssl')) {
3665
		if (config_get_path('notifications/smtp/ssl') == "checked") {
3666
			config_set_path('notifications/smtp/ssl', true);
3667
		} else {
3668
			config_del_path('notifications/smtp/ssl');
3669
		}
3670
	}
3671

    
3672
	if (config_path_enabled('notifications/smtp', 'tls')) {
3673
		if (config_get_path('notifications/smtp/tls') == "checked") {
3674
			config_set_path('notifications/smtp/tls', true);
3675
		} else {
3676
			config_del_path('notifications/smtp/tls');
3677
		}
3678
	}
3679
}
3680

    
3681
function upgrade_113_to_114() {
3682
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
3683

    
3684
	if (!is_array($ipsec_phase1_config)) {
3685
		return;
3686
	}
3687

    
3688
	foreach ($ipsec_phase1_config as &$ph1ent) {
3689
		if (!isset($ph1ent['iketype'])) {
3690
			$ph1ent['iketype'] = 'ikev1';
3691
		}
3692
	}
3693
	config_set_path('ipsec/phase1', $ipsec_phase1_config);
3694
}
3695

    
3696
function upgrade_114_to_115() {
3697
	if (config_get_path('unbound/custom_options') !== null) {
3698
		config_set_path('unbound/custom_options', base64_encode(config_get_path('unbound/custom_options')));
3699
	}
3700
}
3701

    
3702
function upgrade_115_to_116() {
3703
	$ipsec_phase2_config = config_get_path('ipsec/phase2');
3704

    
3705
	if (!is_array($ipsec_phase2_config)) {
3706
		return;
3707
	}
3708

    
3709
	$keyid = 1;
3710
	foreach ($ipsec_phase2_config as &$ph2) {
3711
		$ph2['reqid'] = $keyid;
3712
		$keyid++;
3713
	}
3714
	config_set_path('ipsec/phase2', $ipsec_phase2_config);
3715
}
3716

    
3717
function upgrade_116_to_117() {
3718
	if (empty(config_get_path('ipsec/client/dns_split'))) {
3719
		return;
3720
	}
3721

    
3722
	config_set_path('ipsec/client/dns_split',
3723
		preg_replace('/\s*,\s*/', ' ', trim(config_get_path('ipsec/client/dns_split'))));
3724

    
3725
}
3726

    
3727
function upgrade_117_to_118() {
3728
	// 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.
3729
	config_del_path('system/ca');
3730
	config_del_path('system/cert');
3731

    
3732
	config_init_path('ipsec/phase1');
3733
	$a_phase1 = config_get_path('ipsec/phase1');
3734

    
3735
	foreach ($a_phase1 as &$ph1_entry) {
3736
		// update asn1dn strings from racoon's format to strongswan's
3737
		if (isset($ph1_entry['myid_type']) && $ph1_entry['myid_type'] == 'asn1dn') {
3738
			$ph1_entry['myid_data'] =
3739
			    preg_replace('/\/\s*emailAddress\s*=\s*/', ', E=', $ph1_entry['myid_data']);
3740
		}
3741
		if (isset($ph1_entry['peerid_type']) && $ph1_entry['peerid_type'] == 'asn1dn') {
3742
			$ph1_entry['peerid_data'] =
3743
			    preg_replace('/\/\s*emailAddress\s*=\s*/', ', E=', $ph1_entry['peerid_data']);
3744
		}
3745
	}
3746
	config_set_path('ipsec/phase1', $a_phase1);
3747
}
3748

    
3749
function upgrade_118_to_119() {
3750
	if (config_get_path('ipsec/phase1') === null) {
3751
		return;
3752
	}
3753

    
3754
	// change peerid_type to 'any' for EAP types to retain previous behavior of omitting rightid
3755
	config_init_path('ipsec/phase1');
3756
	$a_phase1 = config_get_path('ipsec/phase1');
3757

    
3758
	foreach ($a_phase1 as &$ph1_entry) {
3759
		if (strstr($ph1_entry['authentication_method'], 'eap')) {
3760
			$ph1_entry['peerid_type'] = "any";
3761
		}
3762
	}
3763
	config_set_path('ipsec/phase1', $a_phase1);
3764
}
3765

    
3766
function upgrade_119_to_120() {
3767
	require_once("ipsec.inc");
3768
	global $ipsec_log_cats;
3769

    
3770
	$ipsec_config = config_get_path('ipsec');
3771
	if (!is_array($ipsec_config)) {
3772
		return;
3773
	}
3774

    
3775
	// add 1 to configured log levels as part of redmine #5340
3776
	foreach ($ipsec_log_cats as $lkey => $ldescr) {
3777
		if (isset($ipsec_config["ipsec_{$lkey}"])) {
3778
			$ipsec_config["ipsec_{$lkey}"] = $ipsec_config["ipsec_{$lkey}"] + 1;
3779
		}
3780
	}
3781
	config_set_path('ipsec', $ipsec_config);
3782
}
3783

    
3784

    
3785
function upgrade_120_to_121() {
3786
	$miniupnpd = config_get_path('installedpackages/miniupnpd/config/0');
3787
	if (!isset($miniupnpd)) {
3788
		return;
3789
	}
3790

    
3791
	$miniupnpd['row'] = array();
3792

    
3793
	for ($i = 1; $i <= 4; $i++) {
3794
		if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) {
3795
			$miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]);
3796
		}
3797
		unset($miniupnpd["permuser{$i}"]);
3798
	}
3799
	config_set_path('installedpackages/miniupnpd/config/0', $miniupnpd);
3800
}
3801

    
3802
function upgrade_121_to_122() {
3803
	$user_config = config_get_path('system/user', []);
3804
	foreach ($user_config as &$user) {
3805
		if (isset($user['nt-hash'])) {
3806
			unset($user['nt-hash']);
3807
		}
3808
	}
3809
	config_set_path('system/user', $user_config);
3810
}
3811

    
3812
function upgrade_122_to_123() {
3813
	// PPTP server was removed
3814
	config_del_path('pptpd');
3815

    
3816
	$filter_rules_config = config_get_path('filter/rule');
3817
	// Cleanup firewall rules
3818
	if (is_array($filter_rules_config)) {
3819
		$rules = &$filter_rules_config;
3820
		$last_rule = count($rules) - 1;
3821
		// Process in reverse order to be able to unset items
3822
		for ($i = $last_rule; $i >= 0; $i--) {
3823
			if (isset($rules[$i]['interface']) && $rules[$i]['interface'] == 'pptp') {
3824
				unset($rules[$i]);
3825
				continue;
3826
			}
3827
			if (isset($rules[$i]['source']['network']) && $rules[$i]['source']['network'] == 'pptp') {
3828
				unset($rules[$i]);
3829
				continue;
3830
			}
3831
			if (isset($rules[$i]['destination']['network']) && $rules[$i]['destination']['network'] == 'pptp') {
3832
				unset($rules[$i]);
3833
				continue;
3834
			}
3835
		}
3836
		config_set_path('filter/rule', $filter_rules_config);
3837
	}
3838

    
3839
	$binat_config = config_get_path('nat/onetoone');
3840
	// Cleanup 1:1 NAT rules
3841
	if (is_array($binat_config)) {
3842
		$onetoone = &$binat_config;
3843
		$last_rule = count($onetoone) - 1;
3844
		// Process in reverse order to be able to unset items
3845
		for ($i = $last_rule; $i >= 0; $i--) {
3846
			if (isset($onetoone[$i]['interface']) && $onetoone[$i]['interface'] == 'pptp') {
3847
				unset($onetoone[$i]);
3848
				continue;
3849
			}
3850
			if (isset($onetoone[$i]['source']['network']) && $onetoone[$i]['source']['network'] == 'pptp') {
3851
				unset($onetoone[$i]);
3852
				continue;
3853
			}
3854
			if (isset($onetoone[$i]['destination']['network']) && $onetoone[$i]['destination']['network'] == 'pptp') {
3855
				unset($onetoone[$i]);
3856
				continue;
3857
			}
3858
		}
3859
		config_set_path('nat/onetoone', $binat_config);
3860
	}
3861

    
3862
	$npt_config = config_get_path('nat/npt');
3863
	// Cleanup npt NAT rules
3864
	if (is_array($npt_config)) {
3865
		$npt = &$npt_config;
3866
		$last_rule = count($npt) - 1;
3867
		// Process in reverse order to be able to unset items
3868
		for ($i = $last_rule; $i >= 0; $i--) {
3869
			if (isset($npt[$i]['interface']) && $npt[$i]['interface'] == 'pptp') {
3870
				unset($npt_config[$i]);
3871
				continue;
3872
			}
3873
		}
3874
		config_set_path('nat/npt', $npt_config);
3875
	}
3876

    
3877
	$nat_rule_config = config_get_path('nat/rule');
3878
	// Cleanup Port-forward NAT rules
3879
	if (is_array($nat_rule_config)) {
3880
		$nat_rules = &$nat_rule_config;
3881
		$last_rule = count($nat_rules) - 1;
3882
		// Process in reverse order to be able to unset items
3883
		for ($i = $last_rule; $i >= 0; $i--) {
3884
			if (isset($nat_rules[$i]['interface']) && $nat_rules[$i]['interface'] == 'pptp') {
3885
				unset($nat_rules[$i]);
3886
				continue;
3887
			}
3888
			if (isset($nat_rules[$i]['source']['network']) && $nat_rules[$i]['source']['network'] == 'pptp') {
3889
				unset($nat_rules[$i]);
3890
				continue;
3891
			}
3892
			if (isset($nat_rules[$i]['destination']['network']) && $nat_rules[$i]['destination']['network'] == 'pptp') {
3893
				unset($nat_rules[$i]);
3894
				continue;
3895
			}
3896
		}
3897
		config_set_path('nat/rule', $nat_rule_config);
3898
	}
3899

    
3900
	$onat_rule_config = config_get_path('nat/outbound/rule');
3901
	// Cleanup Port-forward NAT rules
3902
	if (is_array($onat_rule_config)) {
3903
		$out_rules = &$onat_rule_config;
3904
		$last_rule = count($out_rules) - 1;
3905
		// Process in reverse order to be able to unset items
3906
		for ($i = $last_rule; $i >= 0; $i--) {
3907
			if (isset($out_rules[$i]['interface']) && $out_rules[$i]['interface'] == 'pptp') {
3908
				unset($out_rules[$i]);
3909
				continue;
3910
			}
3911
		}
3912
		config_set_path('nat/rule', $onat_rule_config);
3913
	}
3914
}
3915

    
3916
function upgrade_123_to_124() {
3917
	config_del_path('system/altpkgrepo');
3918
	config_del_path('theme');
3919
}
3920

    
3921
function upgrade_124_to_125() {
3922
	/* Find interfaces with WEP configured. */
3923
	foreach (config_get_path('interfaces', []) as $ifname => $intf) {
3924
		if (!is_array($intf['wireless'])) {
3925
			continue;
3926
		}
3927

    
3928
		/* Generate a notice, disable interface, remove WEP settings */
3929
		if (isset($intf['wireless']['wep']['enable'])) {
3930
			if (!function_exists("file_notice")) {
3931
				require_once("notices.inc");
3932
			}
3933
			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));
3934
			config_del_path("interfaces/{$ifname}/wireless/wep");
3935
			if (isset($intf['enable'])) {
3936
				config_del_path("interfaces/{$ifname}/enable");
3937
			}
3938
		}
3939
	}
3940
}
3941

    
3942
function upgrade_125_to_126() {
3943
	require_once("ipsec.inc");
3944
	global $ipsec_log_cats, $ipsec_log_sevs;
3945

    
3946
	$ipsec_config = config_get_path('ipsec');
3947
	$def_loglevel = 1;
3948
	if (!is_array(config_get_path('ipsec'))) {
3949
		return;
3950
	}
3951

    
3952
	config_init_path('ipsec/logging');
3953

    
3954
	/* subtract 2 from ipsec log levels. the value stored in the config.xml
3955
	 * will now match the strongswan level exactly.
3956
	 */
3957
	foreach (array_keys($ipsec_log_cats) as $cat) {
3958
		if (!isset($ipsec_config["ipsec_{$cat}"])) {
3959
			$new_level = $def_loglevel;
3960
		} else {
3961
			$new_level = intval($ipsec_config["ipsec_{$cat}"]) - 2;
3962
		}
3963

    
3964
		if (in_array($new_level, array_keys($ipsec_log_sevs))) {
3965
			$ipsec_config['logging'][$cat] = $new_level;
3966
		} else {
3967
			$ipsec_config['logging'][$cat] = $def_loglevel;
3968
		}
3969
		unset($ipsec_config["ipsec_{$cat}"]);
3970
	}
3971
	config_set_path('ipsec', $ipsec_config);
3972
}
3973

    
3974
// prior to v2.3 <widgets><sequence> contains a list of widgets with display types:
3975
//		none, close, hide, & show
3976
// v2.3 & later uses:
3977
//		close & open
3978
// widgets not in use are simply not in the list
3979
function upgrade_126_to_127() {
3980
	$widgets_config = config_get_path('widgets/sequence');
3981

    
3982
	if (!isset($widgets_config)) {
3983
		return;
3984
	}
3985

    
3986
	$cur_widgets = explode(',', trim($widgets_config));
3987
	$new_widgets = array();
3988

    
3989
	foreach ($cur_widgets as $widget) {
3990
		list($file, $col, $display) = explode(':', $widget);
3991

    
3992
		switch ($display) {
3993
			case 'hide':
3994
				$display = 'close';
3995
				break;
3996
			case 'show':
3997
				$display = 'open';
3998
				break;
3999
			case 'open':
4000
				break;
4001
			default:
4002
				continue 2;
4003
		}
4004

    
4005
		/* Remove '-container' from widget name */
4006
		$file = preg_replace('/-container$/', '', $file);
4007

    
4008
		$new_widgets[] = "{$file}:{$col}:{$display}";
4009
	}
4010

    
4011
	$widgets_config = implode(',', $new_widgets);
4012
	config_set_path('widgets/sequence', $widgets_config);
4013

    
4014
}
4015

    
4016
function upgrade_127_to_128() {
4017
	// If bindip is not already specified then migrate the old SNMP bindlan flag to a bindip setting
4018
	if (config_get_path('snmpd/bindlan') !== null) {
4019
		if (config_get_path('snmpd/bindip') === null) {
4020
			config_set_path('snmpd/bindip', 'lan');
4021
		}
4022
		config_del_path('snmpd/bindlan');
4023
	}
4024
}
4025

    
4026
function upgrade_128_to_129() {
4027
	/* net.inet.ip.fastforwarding does not exist in 2.3. */
4028
	if (!is_array(config_get_path('sysctl/item'))) {
4029
		return;
4030
	}
4031

    
4032
	foreach (config_get_path('sysctl/item', []) as $idx => $sysctl) {
4033
		if ($sysctl['tunable'] == "net.inet.ip.fastforwarding") {
4034
			config_del_path("sysctl/item/{$idx}");
4035
		}
4036
		if ($sysctl['tunable'] == "net.inet.ipsec.debug") {
4037
			config_set_path("sysctl/item/{$idx}value", "0");
4038
		}
4039
	}
4040

    
4041
	/* IPSEC is always on in 2.3. */
4042
	if (config_path_enabled('ipsec')) {
4043
		config_del_path('ipsec/enable');
4044
	} else if (is_array(config_get_path('ipsec/phase1'))) {
4045
		/*
4046
		 * If IPsec was globally disabled, disable all
4047
		 * phase1 entries
4048
		 */
4049
		foreach (config_get_path('ipsec/phase1', []) as $idx => $p1) {
4050
			config_set_path("ipsec/phase1/{$idx}/disabled", true);
4051
		}
4052
	}
4053
}
4054

    
4055
function upgrade_129_to_130() {
4056
	$openvpn_config = config_get_path('openvpn/openvpn-server');
4057
	/* Change OpenVPN topology_subnet checkbox into topology multi-select #5526 */
4058
	if (is_array($openvpn_config)) {
4059
		foreach ($openvpn_config as & $serversettings) {
4060
			if (strtolower($serversettings['topology_subnet']) == "yes") {
4061
				unset($serversettings['topology_subnet']);
4062
				$serversettings['topology'] = "subnet";
4063
			} else {
4064
				$serversettings['topology'] = "net30";
4065
			}
4066
		}
4067
	}
4068
	config_set_path('openvpn/openvpn-server', $openvpn_config);
4069
}
4070

    
4071
function upgrade_130_to_131() {
4072
	// Default dpinger parameters at time of this upgrade (2.3)
4073
	$default_interval = 500;
4074
	$default_alert_interval = 1000;
4075
	$default_loss_interval = 2000;
4076
	$default_time_period = 60000;
4077

    
4078
	if (config_get_path('syslog/apinger') !== null) {
4079
		config_set_path('syslog/dpinger', true);
4080
		config_del_path('syslog/apinger');
4081
	}
4082
	config_del_path('system/apinger_debug');
4083

    
4084
	$gateways_config = config_get_path('gateways/gateway_item');
4085
	if (!is_array($gateways_config)) {
4086
		return;
4087
	}
4088

    
4089
	if (is_array($gateways_config)) {
4090
		foreach ($gateways_config as &$gw) {
4091
			// dpinger uses milliseconds
4092
			if (isset($gw['interval']) &&
4093
				is_numeric($gw['interval'])) {
4094
				$gw['interval'] = $gw['interval'] * 1000;
4095
			}
4096

    
4097
			if (!empty($gw['interval'])) {
4098
				$effective_interval = $gw['interval'];
4099
			} else {
4100
				$effective_interval = $default_interval;
4101
			}
4102

    
4103
			if (isset($gw['down']) &&
4104
				is_numeric($gw['down'])) {
4105
				$gw['time_period'] = $gw['down'] * 1000;
4106
				unset($gw['down']);
4107
			}
4108

    
4109
			if (!empty($gw['time_period'])) {
4110
				$effective_time_period = $gw['time_period'];
4111
			} else {
4112
				$effective_time_period = $default_time_period;
4113
			}
4114

    
4115
			if (isset($gw['latencyhigh'])) {
4116
				// Default loss_interval is 2000, but must be set
4117
				// higher if latencyhigh is higher.
4118
				if ($gw['latencyhigh'] > $default_loss_interval) {
4119
					$gw['loss_interval'] = $gw['latencyhigh'];
4120
				}
4121
			}
4122

    
4123
			if (!empty($gw['loss_interval'])) {
4124
				$effective_loss_interval = $gw['loss_interval'];
4125
			} else {
4126
				$effective_loss_interval = $default_loss_interval;
4127
			}
4128

    
4129
			if (isset($gw['interval'])) {
4130
				// Default alert_interval is 1000, but must be set
4131
				// higher if interval is higher.
4132
				if ($gw['interval'] > $default_alert_interval) {
4133
					$gw['alert_interval'] = $gw['interval'];
4134
				}
4135
			}
4136

    
4137
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4138
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4139
			}
4140

    
4141
			if (isset($gw['avg_delay_samples'])) {
4142
				unset($gw['avg_delay_samples']);
4143
			}
4144
			if (isset($gw['avg_delay_samples_calculated'])) {
4145
				unset($gw['avg_delay_samples_calculated']);
4146
			}
4147
			if (isset($gw['avg_loss_samples'])) {
4148
				unset($gw['avg_loss_samples']);
4149
			}
4150
			if (isset($gw['avg_loss_samples_calculated'])) {
4151
				unset($gw['avg_loss_samples_calculated']);
4152
			}
4153
			if (isset($gw['avg_loss_delay_samples'])) {
4154
				unset($gw['avg_loss_delay_samples']);
4155
			}
4156
			if (isset($gw['avg_loss_delay_samples_calculated'])) {
4157
				unset($gw['avg_loss_delay_samples_calculated']);
4158
			}
4159
		}
4160
		config_set_path('gateways/gateway_item', $gateways_config);
4161
	}
4162
}
4163

    
4164
function upgrade_131_to_132() {
4165
	if (config_path_enabled('system', 'usefifolog')) {
4166
		config_del_path('system/usefifolog');
4167
		clear_all_log_files(false);
4168
	}
4169
}
4170

    
4171
function upgrade_132_to_133() {
4172
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
4173
	if (is_array($ipsec_phase1_config)) {
4174
		foreach ($ipsec_phase1_config as &$p1) {
4175
			if (isset($p1['encryption-algorithm']['name']) &&
4176
			    $p1['encryption-algorithm']['name'] == 'des') {
4177
				$p1['disabled'] = true;
4178
				file_notice("IPsec",
4179
				    sprintf(gettext("DES is no longer supported, IPsec phase 1 item '%s' is being disabled."), $p1['descr']));
4180
			}
4181
		}
4182
		config_set_path('ipsec/phase1', $ipsec_phase1_config);
4183
	}
4184

    
4185
	$ipsec_phase2_config = config_get_path('ipsec/phase2');
4186
	if (is_array($ipsec_phase2_config)) {
4187
		foreach ($ipsec_phase2_config as &$p2) {
4188
			if (!isset($p2['encryption-algorithm-option']) ||
4189
			    !is_array($p2['encryption-algorithm-option'])) {
4190
				continue;
4191
			}
4192

    
4193
			foreach ($p2['encryption-algorithm-option'] as $ealgo) {
4194
				if ($ealgo['name'] == 'des') {
4195
					$p2['disabled'] = true;
4196
					file_notice("IPsec",
4197
					    sprintf(gettext("DES is no longer supported, IPsec phase 2 item '%s' is being disabled."), $p2['descr']));
4198
				}
4199
			}
4200
		}
4201
		config_set_path('ipsec/phase2', $ipsec_phase2_config);
4202
	}
4203
}
4204

    
4205
// Determine the highest column number in use and set dashboardcolumns accordingly
4206
function upgrade_133_to_134() {
4207
	if (!config_path_enabled('widgets', 'sequence') || config_path_enabled('system/webgui', 'dashboardcolumns')) {
4208
		return;
4209
	}
4210

    
4211
	$cur_widgets = explode(',', trim(config_get_path('widgets/sequence')));
4212
	$maxcols = 2;
4213

    
4214
	foreach ($cur_widgets as $widget) {
4215
		list($file, $col, $display) = explode(':', $widget);
4216

    
4217
		if (($display != 'none') && ($display != 'hide')) {
4218
			preg_match('#[0-9]+$#', $col, $column);
4219
			if ($column[0] > $maxcols) {
4220
				$maxcols = $column[0];
4221
			}
4222
		}
4223
	}
4224

    
4225
	config_set_path('system/webgui/dashboardcolumns', ($maxcols % 10));
4226
}
4227

    
4228
function upgrade_134_to_135() {
4229
	if (config_path_enabled('syslog', 'nologlighttpd')) {
4230
		config_del_path('syslog/nologlighttpd');
4231
		config_set_path('syslog/nolognginx', true);
4232
	}
4233
}
4234

    
4235
function upgrade_135_to_136() {
4236
	$l7_active = false;
4237
	if (config_get_path('l7shaper') !== null) {
4238
		config_del_path('l7shaper');
4239
		$filter_rule_config = config_get_path('filter/rule');
4240
		if (is_array($filter_rule_config)) {
4241
			foreach ($filter_rule_config as &$rule) {
4242
				if (isset($rule['l7container'])) {
4243
					unset($rule['l7container']);
4244
					$l7_active = true;
4245
				}
4246
			}
4247
			config_set_path('filter/rule', $filter_rule_config);
4248
		}
4249
		if ($l7_active) {
4250
			file_notice("L7shaper", gettext("Layer 7 shaping is no longer supported. Its configuration has been removed."));
4251
		}
4252
	}
4253
}
4254

    
4255
function upgrade_136_to_137() {
4256
	$dhcpd_config = config_get_path('dhcpd');
4257
	if (is_array($dhcpd_config)) {
4258
		foreach ($dhcpd_config as &$dhcpd) {
4259
			if (!is_array($dhcpd['numberoptions']['item'])) {
4260
				continue;
4261
			}
4262

    
4263
			foreach ($dhcpd['numberoptions']['item'] as &$item) {
4264
				$item['value'] = base64_encode($item['value']);
4265
			}
4266
		}
4267
		config_set_path('dhcpd', $dhcpd_config);
4268
	}
4269

    
4270
	$dhcpdv6_config = config_get_path('dhcpdv6');
4271
	if (is_array($dhcpdv6_config)) {
4272
		foreach ($dhcpdv6_config as &$dhcpdv6) {
4273
			if (!is_array($dhcpdv6['numberoptions']['item'])) {
4274
				continue;
4275
			}
4276

    
4277
			foreach ($dhcpdv6['numberoptions']['item'] as &$item) {
4278
				$item['value'] = base64_encode($item['value']);
4279
			}
4280
		}
4281
		config_set_path('dhcpdv6', $dhcpdv6_config);
4282
	}
4283
}
4284

    
4285
function upgrade_137_to_138() {
4286
	// the presence of unityplugin tag used to disable loading of unity plugin
4287
	// it's now disabled by default, and config tag is to enable. Unset accordingly.
4288
	config_del_path('ipsec/unityplugin');
4289
}
4290

    
4291
function upgrade_138_to_139() {
4292
	// clean up state killing on gateway failure. having kill_states set used to mean it was disabled
4293
	// now set gw_down_kill_states if enabled.
4294
	if (!config_path_enabled('system', 'kill_states')) {
4295
		config_set_path('system/gw_down_kill_states', true);
4296
	} else {
4297
		config_del_path('system/kill_states');
4298
	}
4299
}
4300

    
4301
function upgrade_139_to_140() {
4302
	$virtualip_config = config_get_path('virtualip/vip');
4303
	if (is_array($virtualip_config)) {
4304
		foreach ($virtualip_config as &$vip) {
4305
			if ($vip['mode'] == "carp") {
4306
				if (!isset($vip['uniqid'])) {
4307
					$vip['uniqid'] = uniqid();
4308
				}
4309
			}
4310
		}
4311
		config_set_path('virtualip/vip', $virtualip_config);
4312
	}
4313
}
4314

    
4315
function upgrade_140_to_141() {
4316
	$openvpn_config = config_get_path('openvpn/openvpn-client');
4317
	// retain OpenVPN's net30 default topology for upgraded client configs so they still work
4318
	// This is for 2.3 ALPHA to a later 2.3, not 2.2.x upgrades, which had no topology setting on clients
4319
	if (is_array($openvpn_config)) {
4320
		foreach ($openvpn_config as &$ovpnclient) {
4321
			if (!isset($ovpnclient['topology'])) {
4322
				$ovpnclient['topology'] = "net30";
4323
			}
4324
		}
4325
		config_set_path('openvpn/openvpn-client', $openvpn_config);
4326
	}
4327

    
4328
	$filter_rule_config = config_get_path('filter/rule');
4329
	// repeat addition of filter tracker IDs from 106_to_107 where missing since associated filter rules were missing them
4330
	if (is_array($filter_rule_config)) {
4331
		$tracker = (int)microtime(true);
4332
		foreach ($filter_rule_config as &$rule) {
4333
			if (empty($rule['tracker'])) {
4334
				$rule['tracker'] = $tracker;
4335
				$tracker++;
4336
			}
4337
		}
4338
		unset($tracker, $rule);
4339
		config_set_path('filter/rule', $filter_rule_config);
4340
	}
4341

    
4342
}
4343

    
4344
function upgrade_141_to_142() {
4345
	/* Convert Namecheap type DynDNS entries to the new split hostname and domain format */
4346

    
4347
	config_init_path('dyndnses/dyndns');
4348
	$a_dyndns = config_get_path('dyndnses/dyndns');
4349

    
4350
	foreach ($a_dyndns as &$dyndns) {
4351
		if ($dyndns['type'] == "namecheap") {
4352
			/* Use the old style logic to split the host and domain one last time. */
4353
			$dparts = explode(".", trim($dyndns['host']));
4354
			$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
4355
			$domain_offset = count($dparts) - $domain_part_count;
4356
			$dyndns['host'] = implode(".", array_slice($dparts, 0, $domain_offset));
4357
			$dyndns['domainname'] = implode(".", array_slice($dparts, $domain_offset));
4358
		}
4359
	}
4360
	config_set_path('dyndnses/dyndns', $a_dyndns);
4361

    
4362
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
4363
	$cron_config = config_get_path('cron/item');
4364
	if (is_array($cron_config)) {
4365
		foreach ($cron_config as $idx => $cronitem) {
4366
			if ($cronitem['command'] == "/etc/pppoerestart") {
4367
				unset($cron_config[$idx]);
4368
			}
4369
		}
4370
		config_set_path('cron/item', $cron_config);
4371
	}
4372
}
4373

    
4374
// Updated to check for empty separator definitions via is_array()
4375
function upgrade_142_to_143() {
4376
	$filter_config = config_get_path('filter');
4377

    
4378
	/* Re-index firewall rule separators per interface */
4379
	if (is_array($filter_config['separator'])) {
4380
		foreach ($filter_config['separator'] as &$separators) {
4381

    
4382
			if (is_array($separators)) {
4383
				foreach ($separators as $sepn => &$separator) {
4384

    
4385
					$seprow = substr($separator['row']['0'], 2);
4386
					$sepif  = $separator['if'];
4387

    
4388
					// Determine position of separator within the interface rules.
4389
					$i = -1; $j = 0;
4390
					foreach ($filter_config['rule'] as &$filterent) {
4391

    
4392
						if ($i == $seprow) {
4393
							// Set separator row to it's position within the interface rules.
4394
							$filter_config['separator'][$sepif][$sepn]['row'] = 'fr' . $j;
4395
							continue 2;	// Advance to next separator
4396
						}
4397

    
4398
						// Position within the interface rules.
4399
						if (($filterent['interface'] == $sepif && !isset($filterent['floating'])) || (isset($filterent['floating']) && "floatingrules" == $sepif)) {
4400
							$j++;
4401
						}
4402
						$i++;
4403
					}
4404
				}
4405
			}
4406
		}
4407
		unset($separators, $separator, $filterent);
4408
		config_set_path('filter', $filter_config);
4409
	}
4410

    
4411
	$nat_separator_config = config_get_path('nat/separator');
4412
	/* Re-index nat rule separators */
4413
	if (is_array($nat_separator_config)) {
4414
		foreach ($nat_separator_config as &$separator) {
4415
			if (is_array($separator)) {
4416
				$seprow = substr($separator['row']['0'], 2);
4417
				$separator['row'] = 'fr' . ($seprow + 1);
4418
			}
4419
		}
4420
		config_set_path('nat/separator', $nat_separator_config);
4421
	}
4422
}
4423

    
4424
function get_vip_from_ip_alias($ipalias) {
4425
	foreach (config_get_path('virtualip/vip', []) as $idx => $vip) {
4426
		if ($vip['mode'] != "ipalias") {
4427
			continue;
4428
		}
4429
		if ($ipalias == $vip['subnet']) {
4430
			return ("_vip{$vip['uniqid']}");
4431
		}
4432
	}
4433

    
4434
	return ($ipalias);
4435
}
4436

    
4437
function get_vip_from_oldcarp($carp) {
4438
	foreach (config_get_path('virtualip/vip', []) as $idx => $vip) {
4439
		if ($vip['mode'] != "carp") {
4440
			continue;
4441
		}
4442
		if ($carp == "{$vip['interface']}_vip{$vip['vhid']}") {
4443
			return ("_vip{$vip['uniqid']}");
4444
		}
4445
	}
4446

    
4447
	return ($carp);
4448
}
4449

    
4450
function upgrade_143_to_144() {
4451
	$virtualip_config = config_get_path('virtualip/vip');
4452
	if (is_array($virtualip_config)) {
4453
		foreach ($virtualip_config as &$vip) {
4454
			if ($vip['mode'] == "ipalias") {
4455
				if (!isset($vip['uniqid'])) {
4456
					$vip['uniqid'] = uniqid();
4457
				}
4458
			}
4459
		}
4460
		unset($vip);
4461
		config_set_path('virtualip/vip', $virtualip_config);
4462
	}
4463

    
4464
	/* Convert IPsec phase 1 entries. */
4465
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
4466
	if (is_array($ipsec_phase1_config)) {
4467
		foreach ($ipsec_phase1_config as &$ph1ent) {
4468
			if (is_ipaddr($ph1ent['interface']) || is_ipaddrv6($ph1ent['interface'])) {
4469
				$ph1ent['interface'] = get_vip_from_ip_alias($ph1ent['interface']);
4470
			} else if (strpos($ph1ent['interface'], "_vip")) {
4471
				$ph1ent['interface'] = get_vip_from_oldcarp($ph1ent['interface']);
4472
			}
4473
		}
4474
		unset($ph1ent);
4475
		config_set_path('ipsec/phase1', $ipsec_phase1_config);
4476
	}
4477

    
4478
	/* Convert openvpn. */
4479
	$openvpn_server_config = config_get_path('openvpn/openvpn-server');
4480
	if (is_array($openvpn_server_config)) {
4481
		foreach ($openvpn_server_config as &$ovpn) {
4482
			if (empty($ovpn['interface'])) {
4483
				continue;
4484
			}
4485
			if (is_ipaddr($ovpn['interface']) || is_ipaddrv6($ovpn['interface'])) {
4486
				$ovpn['interface'] = get_vip_from_ip_alias($ovpn['interface']);
4487
			} else if (strpos($ovpn['interface'], "_vip")) {
4488
				$ovpn['interface'] = get_vip_from_oldcarp($ovpn['interface']);
4489
			}
4490
		}
4491
		unset($ovpn);
4492
		config_set_path('openvpn/openvpn-server', $openvpn_server_config);
4493
	}
4494
	$openvpn_client_config = config_get_path('openvpn/openvpn-client');
4495
	if (is_array($openvpn_client_config)) {
4496
		foreach ($openvpn_client_config as &$ovpn) {
4497
			if (empty($ovpn['interface'])) {
4498
				continue;
4499
			}
4500
			if (is_ipaddr($ovpn['interface']) || is_ipaddrv6($ovpn['interface'])) {
4501
				$ovpn['interface'] = get_vip_from_ip_alias($ovpn['interface']);
4502
			} else if (strpos($ovpn['interface'], "_vip")) {
4503
				$ovpn['interface'] = get_vip_from_oldcarp($ovpn['interface']);
4504
			}
4505
		}
4506
		unset($ovpn);
4507
		config_set_path('openvpn/openvpn-client', $openvpn_client_config);
4508
	}
4509

    
4510
	/* Convert unbound. */
4511
	$unbound_if_config = config_get_path('unbound/active_interface');
4512
	if (!empty($unbound_if_config)) {
4513
		$active_ifs = explode(",", $unbound_if_config);
4514
		$ifs = array();
4515
		foreach ($active_ifs as $if) {
4516
			if (is_ipaddr($if) || is_ipaddrv6($if)) {
4517
				$ifs[] = get_vip_from_ip_alias($if);
4518
			} else if (strpos($if, "_vip")) {
4519
				$ifs[] = get_vip_from_oldcarp($if);
4520
			} else {
4521
				$ifs[] = $if;
4522
			}
4523
		}
4524
		$unbound_if_config = implode(",", $ifs);
4525
		config_set_path('unbound/active_interface', $unbound_if_config);
4526
	}
4527

    
4528
	/* Convert dnsmasq. */
4529
	$dnsmasq_if_config = config_get_path('dnsmasq/interface');
4530
	if (!empty($dnsmasq_if_config)) {
4531
		$active_ifs = explode(",", $dnsmasq_if_config);
4532
		$ifs = array();
4533
		foreach ($active_ifs as $if) {
4534
			if (is_ipaddr($if) || is_ipaddrv6($if)) {
4535
				$ifs[] = get_vip_from_ip_alias($if);
4536
			} else if (strpos($if, "_vip")) {
4537
				$ifs[] = get_vip_from_oldcarp($if);
4538
			} else {
4539
				$ifs[] = $if;
4540
			}
4541
		}
4542
		$dnsmasq_if_config = implode(",", $ifs);
4543
		config_set_path('dnsmasq/interface', $dnsmasq_if_config);
4544
	}
4545
}
4546

    
4547
function upgrade_144_to_145() {
4548
	$if_config = config_get_path('interfaces');
4549
	$dhcpdv6_config = config_get_path('dhcpdv6');
4550

    
4551
	// Enable DHCPv6 server and radvd config for track6 interfaces,
4552
	// matching what used to be automatically enabled with no user
4553
	// configurability.
4554
	if (is_array($if_config)) {
4555
		foreach ($if_config as $ifname => $ifcfg) {
4556
			if (isset($ifcfg['enable'])) {
4557
				if ($ifcfg['ipaddrv6'] == "track6") {
4558
					$dhcpdv6_config[$ifname]['enable'] = true;
4559
					$dhcpdv6_config[$ifname]['range']['from'] = "::1000";
4560
					$dhcpdv6_config[$ifname]['range']['to'] = "::2000";
4561
					$dhcpdv6_config[$ifname]['ramode'] = "assist";
4562
					$dhcpdv6_config[$ifname]['rapriority'] = "medium";
4563
				}
4564
			}
4565
		}
4566
	}
4567

    
4568
	if ($dhcpdv6_config !== null) {
4569
		config_set_path('dhcpdv6', $dhcpdv6_config);
4570
	}
4571
}
4572

    
4573
function upgrade_145_to_146() {
4574
	// Add standard deviation to the quality rrds
4575
	global $g;
4576

    
4577
	$rrddbpath = "/var/db/rrd";
4578
	$rrdtool = "/usr/local/bin/rrdtool";
4579

    
4580
	$awkcmd = "/usr/bin/awk '";
4581
	$awkcmd .= "{\n";
4582
	$awkcmd .= "    if (sub(/<\\/v><\\/row>/, \"</v><v>NaN</v></row>\") == 0)\n";
4583
	$awkcmd .= "    {\n";
4584
	$awkcmd .= "        if (/<\\/cdp_prep>/)\n";
4585
	$awkcmd .= "        {\n";
4586
	$awkcmd .= "            print \"			<ds>\"\n";
4587
	$awkcmd .= "            print \"			<primary_value> 0.0000000000e+00 </primary_value>\"\n";
4588
	$awkcmd .= "            print \"			<secondary_value> 0.0000000000e+00 </secondary_value>\"\n";
4589
	$awkcmd .= "            print \"			<value> NaN </value>\"\n";
4590
	$awkcmd .= "            print \"			<unknown_datapoints> 0 </unknown_datapoints>\"\n";
4591
	$awkcmd .= "            print \"			</ds>\"\n";
4592
	$awkcmd .= "        }\n";
4593
	$awkcmd .= "        else if (/<!-- Round Robin Archives -->/)\n";
4594
	$awkcmd .= "        {\n";
4595
	$awkcmd .= "            print \"	<ds>\"\n";
4596
	$awkcmd .= "            print \"		<name> stddev </name>\"\n";
4597
	$awkcmd .= "            print \"		<type> GAUGE </type>\"\n";
4598
	$awkcmd .= "            print \"		<minimal_heartbeat> 120 </minimal_heartbeat>\"\n";
4599
	$awkcmd .= "            print \"		<min> 0.0000000000e+00 </min>\"\n";
4600
	$awkcmd .= "            print \"		<max> 1.0000000000e+05 </max>\\n\"\n";
4601
	$awkcmd .= "            print \"		<!-- PDP Status -->\"\n";
4602
	$awkcmd .= "            print \"		<last_ds> 0 </last_ds>\"\n";
4603
	$awkcmd .= "            print \"		<value> 0.0000000000e+00 </value>\"\n";
4604
	$awkcmd .= "            print \"		<unknown_sec> 0 </unknown_sec>\"\n";
4605
	$awkcmd .= "            print \"	</ds>\\n\"\n";
4606
	$awkcmd .= "        }\n";
4607
	$awkcmd .= "    }\n";
4608
	$awkcmd .= "    print;\n";
4609
	$awkcmd .= "}'";
4610

    
4611
	$databases = return_dir_as_array($rrddbpath, '/-quality\.rrd$/');
4612
	foreach ($databases as $database) {
4613
		$xmldump = "{$g['tmp_path']}/{$database}.xml";
4614

    
4615
		if (is_platform_booting()) {
4616
			echo "Update RRD database {$database}.\n";
4617
		}
4618

    
4619
		exec("$rrdtool dump {$rrddbpath}/{$database} | {$awkcmd} > {$xmldump}");
4620
		exec("$rrdtool restore -f {$xmldump} {$rrddbpath}/{$database}");
4621
		@unlink("{$xmldump}");
4622
	}
4623

    
4624
	if (!is_platform_booting()) {
4625
		enable_rrd_graphing();
4626
	}
4627
	/* Let's save the RRD graphs after we run enable RRD graphing */
4628
	/* The function will restore the rrd.tgz so we will save it after */
4629
	exec("cd /; LANG=C RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
4630
}
4631

    
4632
function upgrade_bgpd_146_to_147() {
4633
	$openbgpd_conf = config_get_path('installedpackages/openbgpd/config/0');
4634

    
4635
	if (!is_array($openbgpd_conf)) {
4636
		return;
4637
	}
4638
	if (!isset($openbgpd_conf['carpstatusip']) &&
4639
	    !is_ipaddr($openbgpd_conf['carpstatusip'])) {
4640
		return;
4641
	}
4642

    
4643
	if (!is_array(config_get_path('virtualip/vip')))
4644
		return;
4645
	foreach (config_get_path('virtualip/vip', []) as $idx => $vip) {
4646
		if ($vip['subnet'] == $openbgpd_conf['carpstatusip']) {
4647
			$openbgpd_conf['carpstatusvid'] = "_vip{$vip['uniqid']}";
4648
			unset($openbgpd_conf['carpstatusip']);
4649
			config_set_path('installedpackages/openbgpd/config/0', $openbgpd_conf);
4650
			return;
4651
		}
4652
	}
4653
}
4654

    
4655
function upgrade_quagga_146_to_147() {
4656
	$ospfd_conf = config_get_path('installedpackages/quaggaospfd/config/0');
4657

    
4658
	if (!is_array($ospfd_conf)) {
4659
		return;
4660
	}
4661
	if (!isset($ospfd_conf['carpstatusip']) &&
4662
	    !is_ipaddr($ospfd_conf['carpstatusip'])) {
4663
		return;
4664
	}
4665

    
4666
	if (!is_array(config_get_path('virtualip/vip')))
4667
		return;
4668
	foreach (config_get_path('virtualip/vip', []) as $idx => $vip) {
4669
		if ($vip['subnet'] == $ospfd_conf['carpstatusip']) {
4670
			$ospfd_conf['carpstatusvid'] = "_vip{$vip['uniqid']}";
4671
			unset($ospfd_conf['carpstatusip']);
4672
			config_set_path('installedpackages/quaggaospfd/config/0', $ospfd_conf);
4673
			return;
4674
		}
4675
	}
4676
}
4677

    
4678
function upgrade_146_to_147() {
4679

    
4680
	upgrade_bgpd_146_to_147();
4681
	upgrade_quagga_146_to_147();
4682
}
4683

    
4684
function upgrade_147_to_148() {
4685
	$group_config = config_get_path('system/group');
4686

    
4687
	// Ensure there are no spaces in group names by
4688
	// replacing spaces with underscores
4689
	if (is_array($group_config)) {
4690
		$cleargroups = false;
4691
		foreach ($group_config as &$grp) {
4692
			if (strstr($grp['name'], " ")) {
4693
				$cleargroups = true;
4694
				$grp['scope'] = "remote";
4695
			}
4696
		}
4697
		config_set_path('system/group', $group_config);
4698

    
4699
		// if there was a space in a group name, there may be multiple
4700
		// groups with the same name in the group file. To prevent pw
4701
		// from getting into a neverending loop, delete all user-defined
4702
		// groups here. local_reset_accounts will run shortly after this
4703
		// and add them back. redmine #6012
4704
		if ($cleargroups) {
4705
			foreach ($group_config as $grp) {
4706
				mwexec("/usr/sbin/pw groupdel -g {$grp['gid']}");
4707
			}
4708
		}
4709
	}
4710
}
4711

    
4712
function upgrade_148_to_149() {
4713
	global $altq_list_queues;
4714

    
4715
        if (!is_array(config_get_path('shaper/queue')))
4716
                return;
4717

    
4718
	read_altq_config();
4719

    
4720
	/* Set root queue bandwidth. */
4721
	foreach ($altq_list_queues as $altq) {
4722
		$sum = $altq->GetTotalBw();
4723
		while ($sum > get_queue_bandwidth($altq)) {
4724
			if (intval(($sum / 1000) * 1.2) < (1024 * 1024)) {
4725
				/* 1Gb where possible. */
4726
				$bw = 1024 * 1024;
4727
			} else {
4728
				/* Increase by 20% until it fits. */
4729
				$bw = intval(($sum / 1000) * 1.2);
4730
			}
4731
			$altq->SetBandwidth($bw);
4732
			$altq->SetBwscale("Kb");
4733
			$altq->wconfig();
4734
			$sum = $altq->GetTotalBw();
4735
		}
4736
	}
4737
}
4738

    
4739
function upgrade_149_to_150() {
4740
	$dhcpdv6_config = config_get_path('dhcpdv6');
4741

    
4742
	if (is_array($dhcpdv6_config)) {
4743
        foreach ($dhcpdv6_config as &$dhcpdv6) {
4744
			if (isset($dhcpdv6['rainterface'])) {
4745
				if (strstr($dhcpdv6['rainterface'], "_vip")) {
4746
					$dhcpdv6['rainterface'] = get_vip_from_oldcarp($dhcpdv6['rainterface']);
4747
				}
4748
			}
4749
		}
4750
		config_set_path('dhcpdv6', $dhcpdv6_config);
4751
	}
4752
}
4753

    
4754
function upgrade_150_to_151() {
4755
	// Default dpinger parameters at time of this upgrade (2.3.1)
4756
	$default_interval = 500;
4757
	$default_alert_interval = 1000;
4758
	$default_loss_interval = 2000;
4759
	$default_time_period = 60000;
4760
	$default_latencyhigh = 500;
4761

    
4762
	$gateways_config = config_get_path('gateways/gateway_item');
4763
	// Check advanced gateway parameter relationships in case they are incorrect
4764
	if (is_array($gateways_config)) {
4765
		foreach ($gateways_config as &$gw) {
4766
			if (isset($gw['interval'])) {
4767
				$effective_interval = $gw['interval'];
4768
			} else {
4769
				$effective_interval = $default_interval;
4770
			}
4771

    
4772
			if (isset($gw['alert_interval'])) {
4773
				$effective_alert_interval = $gw['alert_interval'];
4774
			} else {
4775
				$effective_alert_interval = $default_alert_interval;
4776
			}
4777

    
4778
			if (isset($gw['loss_interval'])) {
4779
				$effective_loss_interval = $gw['loss_interval'];
4780
			} else {
4781
				$effective_loss_interval = $default_loss_interval;
4782
			}
4783

    
4784
			if (isset($gw['time_period'])) {
4785
				$effective_time_period = $gw['time_period'];
4786
			} else {
4787
				$effective_time_period = $default_time_period;
4788
			}
4789

    
4790
			if (isset($gw['latencyhigh'])) {
4791
				$effective_latencyhigh = $gw['latencyhigh'];
4792
			} else {
4793
				$effective_latencyhigh = $default_latencyhigh;
4794
			}
4795

    
4796
			// Loss interval has to be at least as big as high latency.
4797
			if ($effective_latencyhigh > $effective_loss_interval) {
4798
				$effective_loss_interval = $gw['loss_interval'] = $effective_latencyhigh;
4799
			}
4800

    
4801
			// Alert interval has to be at least as big as probe interval.
4802
			if ($effective_interval > $effective_alert_interval) {
4803
				$gw['alert_interval'] = $effective_interval;
4804
			}
4805

    
4806
			// The time period for averaging has to be more than 2 probes plus the loss interval.
4807
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4808
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4809
			}
4810
		}
4811
		config_set_path('gateways/gateway_item', $gateways_config);
4812
	}
4813
}
4814

    
4815
function upgrade_151_to_152() {
4816
	require_once("/etc/inc/services.inc");
4817

    
4818
	// Remove these cron jobs on full install if not using ramdisk.
4819
	if (!config_path_enabled('system', 'use_mfs_tmpvar')) {
4820
		/* See #7146 for detail on why the extra parameters are needed for the time being. */
4821
		install_cron_job("/etc/rc.backup_rrd.sh", false, null, null, null, null, null, null, false);
4822
		install_cron_job("/etc/rc.backup_dhcpleases.sh", false, null, null, null, null, null, null, false);
4823
	}
4824
}
4825

    
4826
function upgrade_152_to_153() {
4827
	if (is_array(config_get_path('virtualip/vip'))) {
4828
		foreach (config_get_path('virtualip/vip', []) as $idx => $vip) {
4829
			if (substr($vip['interface'], 0, 4) == "_vip") {
4830
				// using new VIP format
4831
				continue;
4832
			} else if (strstr($vip['interface'], "_vip")) {
4833
				// using old VIP format, update
4834
				config_set_path("virtualip/vip/{$idx}/interface", get_vip_from_oldcarp($vip['interface']));
4835
			}
4836
		}
4837
	}
4838

    
4839
	// upgrade GIFs using VIP to new format
4840
	if (is_array(config_get_path('gifs/gif'))) {
4841
		foreach (config_get_path('gifs/gif', []) as $idx => $gif) {
4842
			if (substr($gif['if'], 0, 4) == "_vip") {
4843
				// using new VIP format
4844
				continue;
4845
			} else if (strstr($gif['if'], "_vip")) {
4846
				// using old VIP format, update
4847
				config_set_path("gifs/gif/{$idx}/if", get_vip_from_oldcarp($gif['if']));
4848
			}
4849
		}
4850
	}
4851

    
4852
	// upgrade GREs using VIP to new format
4853
	if (is_array(config_get_path('gres/gre'))) {
4854
		foreach (config_get_path('gres/gre', []) as $idx => $gre) {
4855
			if (substr($gre['if'], 0, 4) == "_vip") {
4856
				// using new VIP format
4857
				continue;
4858
			} else if (strstr($gre['if'], "_vip")) {
4859
				// using old VIP format, update
4860
				config_set_path("gres/gre/{$idx}/if", get_vip_from_oldcarp($gre['if']));
4861
			}
4862
		}
4863
	}
4864

    
4865
	// upgrade gateway groups using VIPs
4866
	if (is_array(config_get_path('gateways/gateway_group'))) {
4867
		foreach (config_get_path('gateways/gateway_group', []) as $idx => $gw) {
4868
			if (is_array($gw['item'])) {
4869
				$newitems = array();
4870
				$gwvipchange = false;
4871
				foreach ($gw['item'] as $item) {
4872
					if (strstr($item, "|_vip")) {
4873
						// using new VIP format
4874
						$newitems[] = $item;
4875
						continue;
4876
					} else if (strstr($item, "_vip")) {
4877
						// using old VIP format, update
4878
						$gwitemarr = explode("|", $item);
4879
						$gwitemarr[2] = get_vip_from_oldcarp($gwitemarr[2]);
4880
						$newitems[] = implode("|", $gwitemarr);
4881
						$gwvipchange = true;
4882
					} else {
4883
						$newitems[] = $item;
4884
					}
4885
				}
4886
				if ($gwvipchange) {
4887
					config_set_path("gateways/gateway_group/{$idx}/item", $newitems);
4888
				}
4889
			}
4890
		}
4891
	}
4892
}
4893

    
4894
function upgrade_153_to_154() {
4895
	/* NOTE: This upgrade code was reverted. See redmine ticket #6118 and
4896
	   https://github.com/pfsense/pfsense/commit/538a3c04a6b6671151e913b06b2f340b6f8ee222 */
4897
}
4898

    
4899
/* Clean up old GRE/GIF options. See Redmine tickets #6586 and #6587 */
4900
function upgrade_154_to_155() {
4901
	foreach (config_get_path('gifs/gif', []) as $idx => $gif) {
4902
		config_del_path("gifs/gif/{$idx}/link0");
4903
	}
4904

    
4905
	foreach (config_get_path('gres/gre', []) as $idx => $gre) {
4906
		config_del_path("gres/gre/{$idx}/link0");
4907
		config_del_path("gres/gre/{$idx}/link2");
4908
	}
4909
}
4910

    
4911
function upgrade_155_to_156() {
4912
	// Unused
4913
}
4914

    
4915
function upgrade_156_to_157() {
4916
	/* Convert Cloudflare and GratisDNS type DynDNS entries to the new split hostname and domain format */
4917

    
4918
	config_init_path('dyndnses/dyndns');
4919
	$a_dyndns = config_get_path('dyndnses/dyndns');
4920

    
4921
	foreach ($a_dyndns as &$dyndns) {
4922
		if (($dyndns['type'] == "cloudflare") || ($dyndns['type'] == "cloudflare-v6") || ($dyndns['type'] == "gratisdns")) {
4923
			/* Use the old style logic to split the host and domain one last time. */
4924
			$dparts = explode(".", trim($dyndns['host']));
4925
			$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
4926
			$domain_offset = count($dparts) - $domain_part_count;
4927
			$dyndns['host'] = implode(".", array_slice($dparts, 0, $domain_offset));
4928
			$dyndns['domainname'] = implode(".", array_slice($dparts, $domain_offset));
4929
		}
4930
	}
4931
	config_set_path('dyndnses/dyndns', $a_dyndns);
4932

    
4933
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
4934
	if (is_array(config_get_path('cron/item'))) {
4935
		foreach (config_get_path('cron/item', []) as $idx => $cronitem) {
4936
			if ($cronitem['command'] == "/etc/pppoerestart") {
4937
				config_del_path("cron/item/{$idx}");
4938
			}
4939
		}
4940
	}
4941
}
4942

    
4943
function upgrade_157_to_158() {
4944
	/* Convert Dynamic DNS passwords to base64 encoding. Redmine #6688 */
4945

    
4946
	config_init_path('dyndnses/dyndns');
4947
	$a_dyndns = config_get_path('dyndnses/dyndns');
4948

    
4949
	foreach ($a_dyndns as &$dyndns) {
4950
		$dyndns['password'] = base64_encode($dyndns['password']);
4951
	}
4952
	config_set_path('dyndnses/dyndns', $a_dyndns);
4953
}
4954

    
4955
/* Unset references to glxsb in the config. See #6755 */
4956
function upgrade_158_to_159() {
4957
	if (config_get_path('system/crypto_hardware') == "glxsb") {
4958
		config_del_path('system/crypto_hardware');
4959
	}
4960
}
4961

    
4962
/* Convert OpenVPN "protocol" to new style for OpenVPN 2.4, old udp/tcp was
4963
 * IPv4 only, now is dual stack, so change it to udp4/tcp4
4964
 */
4965
function upgrade_159_to_160() {
4966
	$openvpn_server_config = config_get_path('openvpn/openvpn-server', []);
4967
	foreach ($openvpn_server_config as &$vpn) {
4968
		if ($vpn['protocol'] == "UDP") {
4969
			$vpn['protocol'] = "UDP4";
4970
		}
4971
		if ($vpn['protocol'] == "TCP") {
4972
			$vpn['protocol'] = "TCP4";
4973
		}
4974
	}
4975
	unset($vpn);
4976
	config_set_path('openvpn/openvpn-server', $openvpn_server_config);
4977

    
4978
	$openvpn_client_config = config_get_path('openvpn/openvpn-client', []);
4979
	foreach ($openvpn_client_config as &$vpn) {
4980
		if ($vpn['protocol'] == "UDP") {
4981
			$vpn['protocol'] = "UDP4";
4982
		}
4983
		if ($vpn['protocol'] == "TCP") {
4984
			$vpn['protocol'] = "TCP4";
4985
		}
4986
	}
4987
	config_set_path('openvpn/openvpn-client', $openvpn_client_config);
4988
}
4989

    
4990
/* RAM Disk Management */
4991
function upgrade_160_to_161() {
4992
	global $g;
4993

    
4994
	if (!config_path_enabled('system', 'use_mfs_tmpvar')) {
4995
		return;
4996
	}
4997

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

    
5004
		$rrdrestore = "";
5005
		$rrdreturn = "";
5006
		unlink_if_exists("{$rrddbpath}/*.xml");
5007

    
5008
		unset($rrdrestore);
5009
		$_gb = exec("LANG=C /usr/bin/tar -tf {$g['cf_conf_path']}/rrd.tgz", $rrdrestore, $rrdreturn);
5010
		if ($rrdreturn != 0) {
5011
			log_error(sprintf(gettext('RRD restore failed exited with %1$s, the error is: %2$s'), $rrdreturn, $rrdrestore));
5012
		} else {
5013
			foreach ($rrdrestore as $xml_file) {
5014
				$rrd_file = '/' . substr($xml_file, 0, -4) . '.rrd';
5015
				unlink_if_exists("{$rrd_file}");
5016

    
5017
				file_put_contents("{$g['tmp_path']}/rrd_restore", $xml_file);
5018
				$_gb = exec("LANG=C /usr/bin/tar -xf {$g['cf_conf_path']}/rrd.tgz -C / -T {$g['tmp_path']}/rrd_restore");
5019
				if (!file_exists("/{$xml_file}")) {
5020
					log_error(sprintf(gettext("Could not extract %s RRD xml file from archive!"), $xml_file));
5021
					continue;
5022
				}
5023
				$_gb = exec("$rrdtool restore -f '/{$xml_file}' '{$rrd_file}'", $output, $status);
5024
				if ($status) {
5025
					log_error(sprintf(gettext("rrdtool restore -f '%1\$s' '%2\$s' failed returning %3\$s."), $xml_file, $rrd_file, $status));
5026
					continue;
5027
				}
5028
				unset($output);
5029
				@unlink("/{$xml_file}");
5030
			}
5031
			unset($rrdrestore);
5032
			@unlink("{$g['tmp_path']}/rrd_restore");
5033

    
5034
			// Create a new RRD backup to the RAM Disk Store (without RRD XML dump).
5035
			exec("/etc/rc.backup_rrd.sh");
5036
			$ramds_updated = true;
5037

    
5038
			// Rename previous RRD backup so it will not restore again.  Don't delete in case needed for recovery.
5039
			rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/rrd.tgz.old");
5040
		}
5041
	}
5042

    
5043
	// Move existing DHCP leases backup to the RAM Disk Store if it don't already exist there.
5044
	if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz") && ! file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/dhcpleases.tgz")) {
5045
		rename("{$g['cf_conf_path']}/dhcpleases.tgz", "{$g['cf_conf_path']}/RAM_Disk_Store/dhcpleases.tgz");
5046
		$ramds_updated = true;
5047
	}
5048

    
5049
	// Move existing alias table backups to the RAM Disk Store if they don't already exist there.
5050
	$dbpath = "{$g['vardb_path']}/aliastables/";
5051
	$files = glob("{$g['cf_conf_path']}/RAM_Disk_Store{$dbpath}*.tgz");
5052
	if (count($files)) {
5053
		foreach ($files as $file) {
5054
			if (! file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/".basename($file))) {
5055
				rename($file, "{$g['cf_conf_path']}/RAM_Disk_Store/".basename($file));
5056
				$ramds_updated = true;
5057
			}
5058
		}
5059
		// Remove existing alias table backups directory if empty.
5060
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/db/aliastables");
5061
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/db/");
5062
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/");
5063
	}
5064

    
5065
	// Restore RAM Disk Store if updated.
5066
	if ($ramds_updated) {
5067
		exec("/etc/rc.restore_ramdisk_store");
5068
	}
5069
}
5070

    
5071
/* Previous versions of pfSense had cryptodev built into the kernel.
5072
 * To retain the expected behavior on upgrade, load the cryptodev
5073
 * module for users that did not choose a module.
5074
 */
5075
function upgrade_161_to_162() {
5076
	if (empty(config_get_path('system/crypto_hardware'))) {
5077
		config_set_path('system/crypto_hardware', "cryptodev");
5078
	}
5079
}
5080

    
5081
/* Traffic graphs widget settings are now stored in a layout similar
5082
 * to other widgets. Migrate any old settings.
5083
 */
5084
function upgrade_162_to_163() {
5085
	require_once("ipsec.inc");
5086
	foreach (array('refreshinterval', 'invert', 'size', 'backgroundupdate') as $setting) {
5087
		if (config_get_path("widgets/trafficgraphs/{$setting}") !== null) {
5088
			config_set_path("widgets/traffic_graphs/{$setting}", config_get_path("widgets/trafficgraphs/{$setting}"));
5089
			config_del_path("widgets/trafficgraphs/{$setting}");
5090
		}
5091
	}
5092

    
5093
	if (config_get_path('widgets/trafficgraphs/shown') !== null) {
5094
		if (is_array(config_get_path('widgets/trafficgraphs/shown/item'))) {
5095
			$ifdescrs = get_configured_interface_with_descr();
5096

    
5097
			if (ipsec_enabled()) {
5098
				$ifdescrs['enc0'] = "IPsec";
5099
			}
5100

    
5101
			$validNames = array();
5102

    
5103
			foreach ($ifdescrs as $ifdescr => $ifname) {
5104
				array_push($validNames, $ifdescr);
5105
			}
5106

    
5107
			config_set_path('widgets/traffic_graphs/filter', implode(',', array_diff($validNames, config_get_path('widgets/trafficgraphs/shown/item'))));
5108
		}
5109

    
5110
		config_del_path('widgets/trafficgraphs/shown');
5111
	}
5112
}
5113

    
5114
/* Dashboard widget settings config format has changed to support having possibly multiple
5115
 * of a widget on the dashboard. Migrate any old settings.
5116
 */
5117
function convert_widget_164($oldname, $newname, $settings_keys) {
5118
	$user_config = config_get_path('system/user');
5119

    
5120
	if ($newname == '') {
5121
		$newname = $oldname . '-0';
5122
	}
5123

    
5124
	if ($oldname == '') {
5125
		// These settings were stored directly in $config['widgets']
5126
		// Move them down under their new key.
5127
		// e.g. $config['widgets']['filterlogentries']
5128
		// becomes $config['widgets']['log-0']['filterlogentries']
5129
		foreach ($settings_keys as $oldkey => $newkey) {
5130
			if ($newkey == '') {
5131
				$newkey = $oldkey;
5132
			}
5133

    
5134
			// Modify the system-wide entry
5135
			if (config_get_path("widgets/{$oldkey}") !== null) {
5136
				config_set_path("widgets/{$newname}/{$newkey}", config_get_path("widgets/{$oldkey}"));
5137
				config_del_path("widgets/{$oldkey}");
5138
			}
5139

    
5140
			// Modify any user-specific entries
5141
			foreach ($user_config as & $user) {
5142
				if (isset($user['widgets'][$oldkey])) {
5143
					$user['widgets'][$newname][$newkey] = $user['widgets'][$oldkey];
5144
					unset($user['widgets'][$oldkey]);
5145
				}
5146
			}
5147
		}
5148
	} else {
5149
		// These settings were stored in some key under 'widgets',
5150
		// e.g. $config['widgets']['gateways_widget']['display_type']
5151
		// becomes $config['widgets']['gateways-0']['display_type']
5152
		foreach ($settings_keys as $oldkey => $newkey) {
5153
			if ($newkey == '') {
5154
				$newkey = $oldkey;
5155
			}
5156

    
5157
			// Modify the system-wide entry
5158
			if (config_get_path("widgets/{$oldname}/{$oldkey}") !== null) {
5159
				config_set_path("widgets/{$newname}/{$newkey}", config_get_path("widgets/{$oldname}/{$oldkey}"));
5160
				config_del_path("widgets/{$oldname}/{$oldkey}");
5161
			}
5162

    
5163
			// Modify any user-specific entries
5164
			foreach ($user_config as & $user) {
5165
				if (isset($user['widgets'][$oldname][$oldkey])) {
5166
					$user['widgets'][$newname][$newkey] = $user['widgets'][$oldname][$oldkey];
5167
					unset($user['widgets'][$oldname][$oldkey]);
5168
				}
5169

    
5170
				if (isset($user['widgets'][$oldname])) {
5171
					unset($user['widgets'][$oldname]);
5172
				}
5173
			}
5174
		}
5175
		config_del_path("widgets/{$oldname}");
5176
	}
5177
	config_set_path('system/user', $user_config);
5178
}
5179

    
5180
function upgrade_163_to_164() {
5181
	convert_widget_164('dyn_dns_status', '', array('filter' => ''));
5182
	convert_widget_164('gateways_widget', 'gateways-0', array('display_type' => '', 'gatewaysfilter' => ''));
5183
	convert_widget_164('interface_statistics', '', array('iffilter' => ''));
5184
	convert_widget_164('interfaces', '', array('iffilter' => ''));
5185
	convert_widget_164('', 'log-0',
5186
		array(
5187
			'filterlogentries' => '',
5188
			'filterlogentriesacts' => '',
5189
			'filterlogentriesinterfaces' => '',
5190
			'filterlogentriesinterval' => ''));
5191
	convert_widget_164('openvpn', '', array('filter' => ''));
5192
	convert_widget_164('', 'picture-0', array('picturewidget' => '', 'picturewidget_filename' => ''));
5193
	convert_widget_164('', 'rss-0', array('rssfeed' => '', 'rssmaxitems' => '', 'rsswidgetheight' => '', 'rsswidgettextlength' => ''));
5194
	convert_widget_164('', 'services_status-0', array('servicestatusfilter' => 'filter'));
5195
	convert_widget_164('smart_status', '', array('filter' => ''));
5196
	convert_widget_164('system_information', '', array('filter' => ''));
5197
	convert_widget_164('thermal_sensors_widget', 'thermal_sensors-0',
5198
		array(
5199
			'thermal_sensors_widget_zone_warning_threshold' => '',
5200
			'thermal_sensors_widget_zone_critical_threshold' => '',
5201
			'thermal_sensors_widget_core_warning_threshold' => '',
5202
			'thermal_sensors_widget_core_critical_threshold' => '',
5203
			'thermal_sensors_widget_show_raw_output' => '',
5204
			'thermal_sensors_widget_show_full_sensor_name' => '',
5205
			'thermal_sensors_widget_pulsate_warning' => '',
5206
			'thermal_sensors_widget_pulsate_critical' => ''
5207
		));
5208
	convert_widget_164('wol', 'wake_on_lan-0', array('filter' => ''));
5209
}
5210

    
5211
/* Work around broken wizard rules. See https://redmine.pfsense.org/issues/7434 */
5212
function upgrade_164_to_165() {
5213
	$filter_rule_config = config_get_path('filter/rule');
5214
	foreach ($filter_rule_config as & $rule) {
5215
		if ($rule['destination']['port'] == "137-139-137-139") {
5216
			$rule['destination']['port'] = "137-139";
5217
		}
5218
	}
5219
	config_set_path('filter/rule', $filter_rule_config);
5220
}
5221

    
5222
/* Fixup digest algorithm selection for OpenVPN clients and servers so they do not use aliased names. */
5223
function upgrade_165_to_166() {
5224
	require_once('openvpn.inc');
5225
	$openvpn_config = config_get_path('openvpn');
5226
	if (is_array($openvpn_config)) {
5227
		if (is_array($openvpn_config['openvpn-server'])) {
5228
			foreach ($openvpn_config['openvpn-server'] as &$vpn) {
5229
				$vpn['digest'] = openvpn_remap_digest($vpn['digest']);
5230
			}
5231
			unset($vpn);
5232
		}
5233
		if (is_array($openvpn_config['openvpn-client'])) {
5234
			foreach ($openvpn_config['openvpn-client'] as &$vpn) {
5235
				$vpn['digest'] = openvpn_remap_digest($vpn['digest']);
5236
			}
5237
		}
5238
		config_set_path('openvpn', $openvpn_config);
5239
	}
5240
}
5241

    
5242
/* Force the Netgate Services and Support widget to be active on upgrade.
5243
   New widget is added at the top of column 2 */
5244
function upgrade_166_to_167() {
5245
	if (strpos(config_get_path('widgets/sequence'),
5246
	    'netgate_services_and_support') === false) {
5247
		$widgets = explode(",", config_get_path('widgets/sequence'));
5248
		$cnt = count($widgets);
5249
		$col2 = $cnt;
5250
		$newsequence = array();
5251

    
5252
		// Locate the firt column 2 widget
5253
		for ($idx=0;$idx<$cnt;$idx++) {
5254
			if (strpos($widgets[$idx], 'col2') !== false) {
5255
				$col2 = $idx;
5256
				break;
5257
			}
5258
		}
5259

    
5260
		/*
5261
		 * Loop through the widgets inserting the new widget before
5262
		 * the first col2 widget
5263
		 */
5264
		for ($old=0,$new=0;$old<$cnt;$old++,$new++) {
5265
			$newsequence[$new] = $widgets[$old];
5266

    
5267
			if ($old != ($col2 - 1)) {
5268
				continue;
5269
			}
5270
			$new++;
5271
			$newsequence[$new] =
5272
			    "netgate_services_and_support:col2:open:0";
5273
		}
5274

    
5275
		config_set_path('widgets/sequence', implode(",", $newsequence));
5276
	}
5277
}
5278

    
5279
function upgrade_167_to_168() {
5280
	upgrade_166_to_167();
5281
}
5282

    
5283
function upgrade_168_to_169() {
5284
	config_del_path('cron/rc_update_pkg_metadata');
5285

    
5286
	$command = '/usr/bin/nice -n20 /etc/rc.update_pkg_metadata';
5287
	config_init_path('cron/item');
5288
	$cron_config = config_get_path('cron/item');
5289
	if (is_array($cron_config)) {
5290
		foreach ($cron_config as $entry) {
5291
			if ($entry['command'] == $command) {
5292
				return;
5293
			}
5294
		}
5295
	}
5296

    
5297
	$cron_config[] = array(
5298
		'minute' => '1',
5299
		'hour' => '0',
5300
		'mday' => '*',
5301
		'month' => '*',
5302
		'wday' => '*',
5303
		'who' => 'root',
5304
		'command' => $command
5305
	);
5306
	config_set_path('cron/item', $cron_config);
5307
}
5308

    
5309
/* Upgrade wireless interfaces to the format required for 2.4
5310
 * Each wireless interface now needs to be a cloned instance, the card itself
5311
 * Can no longer be assigned. https://redmine.pfsense.org/issues/6770 */
5312
function upgrade_169_to_170() {
5313
	foreach (config_get_path('interfaces', []) as $friendly => & $iface) {
5314
		if (is_array($iface['wireless']) && !empty($iface['wireless']['mode'])) {
5315
			/* This test can only be true for one instance per card, so it is safe. */
5316
			if (stristr($iface['if'], '_wlan') === false) {
5317
				$wlan = array();
5318
				$wlan['if'] = $iface['if'];
5319
				$wlan['mode'] = $iface['wireless']['mode'];
5320
				$wlan['descr'] = "Wireless interface {$friendly}";
5321
				/* It was not possible to create clones of _wlan0 before, so this is safe. */
5322
				$wlan['cloneif'] = "{$iface['if']}_wlan0";
5323
				/* Make sure this entry is placed in the list of wireless interface clones. */
5324
				config_init_path('wireless/clone');
5325
				config_set_path('wireless/clone/', $wlan);
5326
				/* The interface assignment must now be the cloned interface name. */
5327
				$iface['if'] = $wlan['cloneif'];
5328
			}
5329
		}
5330
	}
5331
}
5332

    
5333
/* Upgrade the VLAN interface names to use $if.$tag instead of $if_vlan$tag.
5334
 * This helps keep the interface names smaller than the limit.
5335
 */
5336
function upgrade_170_to_171() {
5337
	$vlan_config = config_get_path('vlans/vlan');
5338
	$if_config = config_get_path('interfaces');
5339

    
5340
	if (!is_array($vlan_config) || count($vlan_config) == 0) {
5341
		return;
5342
	}
5343
	$iflist = get_configured_interface_list(true);
5344
	foreach ($vlan_config as $id => $vlan) {
5345
		/* Make sure to update the interfaces section with the new name. */
5346
		$vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}";
5347
		foreach ($iflist as $ifname) {
5348
			if ($if_config[$ifname]['if'] == $vlan_name) {
5349
				$if_config[$ifname]['if'] = vlan_interface($vlan);
5350
			}
5351
		}
5352
		$vlan_config[$id]['vlanif'] = vlan_interface($vlan);
5353
	}
5354
	config_set_path('vlans/vlan', $vlan_config);
5355
	config_set_path('interfaces', $if_config);
5356
}
5357

    
5358
/* Upgrade the QinQ interface names to use $if.$tag instead of $if_$tag.
5359
 * This helps keep the interface names smaller than the limit (but they are still
5360
 * big with the QinQ subtag).
5361
 */
5362
function upgrade_171_to_172() {
5363
	$qinq_config = config_get_path('qinqs/qinqentry');
5364
	$if_config = config_get_path('interfaces');
5365

    
5366
	if (!is_array($qinq_config) || count($qinq_config) == 0) {
5367
		return;
5368
	}
5369
	$iflist = get_configured_interface_list(true);
5370
	foreach ($qinq_config as &$qinq) {
5371
		$qinq['vlanif'] = vlan_interface($qinq);
5372

    
5373
		if (!isset($qinq['members'])) {
5374
			continue;
5375
		}
5376
		foreach (explode(" ", $qinq['members']) as $tag) {
5377
			/* Make sure to update the interfaces section with the new name. */
5378
			$vlan_name = "{$qinq['if']}_{$qinq['tag']}_{$tag}";
5379
			foreach ($iflist as $ifname) {
5380
				if ($if_config[$ifname]['if'] == $vlan_name) {
5381
					$if_config[$ifname]['if'] = qinq_interface($qinq, $tag);
5382
				}
5383
			}
5384
		}
5385
	}
5386
	config_set_path('qinqs/qinqentry', $qinq_config);
5387
	config_set_path('interfaces', $if_config);
5388
}
5389

    
5390
/*
5391
 * Upgrade the VLAN interface names to use $if.$tag on PPP items
5392
 */
5393
function upgrade_172_to_173() {
5394
	$ppp_config = config_get_path('ppps/ppp');
5395

    
5396
	if (!is_array($ppp_config) ||
5397
	    count($ppp_config) == 0) {
5398
		return;
5399
	}
5400
	$iflist = get_configured_interface_list(true);
5401
	foreach ($ppp_config as &$ppp) {
5402
		if (empty($ppp['ports']) ||
5403
		    strpos($ppp['ports'], "_vlan") == false) {
5404
			continue;
5405
		}
5406

    
5407
		$ppp['ports'] = str_replace('_vlan', '.',
5408
		    $ppp['ports']);
5409
	}
5410
	config_set_path('ppps/ppp', $ppp_config);
5411
}
5412

    
5413
/*
5414
 * Dynamic DNS nsupdate keyfiles have been replaced with a simpler ddns-confgen style file.
5415
 */
5416
function upgrade_173_to_174() {
5417
	$dnsupdate_config = config_get_path('dnsupdates/dnsupdate');
5418

    
5419
	/* Stop if there is nothing to do. */
5420
	if (!is_array($dnsupdate_config)) {
5421
		return;
5422
	}
5423
	/* Remove unused keytype field. */
5424
	foreach ($dnsupdate_config as $i => &$dnsupdate) {
5425
		unset($dnsupdate['keytype']);
5426
	}
5427
	config_set_path('dnsupdates/dnsupdate', $dnsupdate_config);
5428
}
5429

    
5430
/* IPsec Phase1 now supports multiple authentication ciphers to be specified from the webgui.
5431
 * This is useful for mobile users using different OS's supporting different ciphers.
5432
 */
5433
function upgrade_174_to_175() {
5434
	config_init_path('ipsec/phase1');
5435
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
5436
	if (count($ipsec_phase1_config)) {
5437
		$a_phase1 = &$ipsec_phase1_config;
5438
		foreach($a_phase1 as &$phase1) {
5439
			if (empty($phase1) || !is_array($phase1)) {
5440
				continue;
5441
			}
5442
			$item = array();
5443
			if (isset($phase1['encryption-algorithm']) && !empty($phase1['encryption-algorithm'])) {
5444
				$item['encryption-algorithm'] = $phase1['encryption-algorithm'];
5445
				unset($phase1['encryption-algorithm']);
5446
			}
5447
			if (isset($phase1['hash-algorithm']) && !empty($phase1['hash-algorithm'])) {
5448
				$item['hash-algorithm'] = $phase1['hash-algorithm'];
5449
				unset($phase1['hash-algorithm']);
5450
			}
5451
			if (isset($phase1['dhgroup']) && !empty($phase1['dhgroup'])) {
5452
				$item['dhgroup'] = $phase1['dhgroup'];
5453
				unset($phase1['dhgroup']);
5454
			}
5455
			if (!empty($item)) {
5456
				if (!is_array($phase1['encryption'])) {
5457
					$phase1['encryption'] = array();
5458
				}
5459
				if (!is_array($phase1['encryption']['item'])) {
5460
					$phase1['encryption']['item'] = array();
5461
				}
5462
				$phase1['encryption']['item'][] = $item;
5463
			}
5464
		}
5465
		config_set_path('ipsec/phase1', $ipsec_phase1_config);
5466
	}
5467
}
5468

    
5469
/* igmp always was enabled by default if settings were present.
5470
 * So enable it once on upgrade if settings are there.
5471
 * And provide the option through gui to disable it again
5472
 */
5473
function upgrade_175_to_176() {
5474
	if ((count(config_get_path('igmpproxy/igmpentry', [])) > 0)) {
5475
		config_set_path('igmpproxy/enable', true);
5476
	}
5477
}
5478

    
5479
/* Placeholder for a factory update. */
5480
function upgrade_176_to_177() {
5481
}
5482

    
5483
// The image displayed by the picture widget is now stored on the file system
5484
function upgrade_177_to_178() {
5485
	$widgets_config = config_get_path('widgets');
5486
	if (isset($widgets_config)) {
5487
		$idx = 0;
5488

    
5489
		while (isset($widgets_config['picture-' . $idx])) {
5490
			file_put_contents("/conf/widget_image.picture-" . $idx, base64_decode($widgets_config['picture-' . $idx]['picturewidget']));
5491
			$widgets_config['picture-' . $idx]['picturewidget'] = "/conf/widget_image.picture-". $idx;
5492
			$idx++;
5493
		}
5494
		config_set_path('widgets', $widgets_config);
5495
	}
5496
}
5497

    
5498
/* Placeholder for a factory update. */
5499
function upgrade_178_to_179() {
5500
}
5501

    
5502
function upgrade_179_to_180() {
5503
	global $g;
5504

    
5505
	/* Change default to 400000 to make sure bogonsv6 works */
5506
	if (empty(config_get_path('system/maximumtableentries'))) {
5507
		config_set_path('system/maximumtableentries',
5508
		    g_get('minimumtableentries_bogonsv6'));
5509
	}
5510
}
5511

    
5512
/*
5513
 * Automatically enable retrieving captive portal bandwidth limits from RADIUS for each captive portal
5514
 */
5515
function upgrade_180_to_181() {
5516
	if (is_array(config_get_path('captiveportal'))) {
5517
		foreach (config_get_path('captiveportal', []) as $cpzone => $cpcfg) {
5518
			if ($cpcfg['auth_method'] == "radius") {
5519
				config_set_path("captiveportal/{$cpzone}/radiusperuserbw", true);
5520
			}
5521
		}
5522
	}
5523
}
5524

    
5525
function upgrade_181_to_182() {
5526
	/*
5527
	 * Some gateways did not have an ipprotocol set, and some configurations
5528
	 * did not have a default set so one was assumed. To avoid leaving the
5529
	 * user without a default, fix these situations first.
5530
	 */
5531
	$defgw_v4_found = false;
5532
	$defgw_v6_found = false;
5533
	$defgw_v4_candidate = array();
5534
	$defgw_v6_candidate = array();
5535
	$gateway_config = config_get_path('gateways/gateway_item');
5536
	if (is_array($gateway_config)) {
5537
		foreach($gateway_config as &$item) {
5538
			/* Attempt to determine IP protocol for static gateways
5539
			 * missing the protocol definition */
5540
			if (empty($item['ipprotocol'])) {
5541
				if (is_ipaddrv4($item['gateway'])) {
5542
					$item['ipprotocol'] = 'inet';
5543
				} elseif (is_ipaddrv6($item['gateway'])) {
5544
					$item['ipprotocol'] = 'inet6';
5545
				}
5546
			}
5547
			/* Check if we have found a default gw */
5548
			if (isset($item['defaultgw'])) {
5549
				if ($item['ipprotocol'] == 'inet') {
5550
					$defgw_v4_found = true;
5551
				} elseif ($item['ipprotocol'] == 'inet6') {
5552
					$defgw_v6_found = true;
5553
				}
5554
			} else {
5555
				/* This isn't a default gateway, but could it be? */
5556
				if ($item['ipprotocol'] == 'inet') {
5557
					if (!$defgw_v4_found &&
5558
					    ($item['interface'] == "wan")) {
5559
						$defgw_v4_candidate = &$item;
5560
					}
5561
				} elseif ($item['ipprotocol'] == 'inet6') {
5562
					if (!$defgw_v6_found &&
5563
					    ($item['interface'] == "wan")) {
5564
						$defgw_v6_candidate = &$item;
5565
					}
5566
				}
5567
			}
5568
		}
5569
		unset($item);
5570
	}
5571
	/* If there was no other default gateway, use the one of last resort. */
5572
	if (!$defgw_v4_found && !empty($defgw_v4_candidate)) {
5573
		$defgw_v4_candidate['defaultgw'] = true;
5574
	}
5575
	if (!$defgw_v6_found && !empty($defgw_v6_candidate)) {
5576
		$defgw_v6_candidate['defaultgw'] = true;
5577
	}
5578
	config_set_path('gateways/gateway_item', $gateway_config);
5579

    
5580
	if (config_path_enabled('system', 'gw_switch_default')) {
5581
		// default gateway switching was enabled, convert gatewaygroup
5582
		$newgroup4 = array();
5583
		$newgroup6 = array();
5584
		$tiernr4 = 2;
5585
		$tiernr6 = 2;
5586
		$gateways_config = config_get_path('gateways');
5587
		if (is_array($gateways_config)) {
5588
			foreach($gateways_config['gateway_item'] as &$item) {
5589
				if ($item['ipprotocol'] == 'inet') {
5590
					if (isset($item['defaultgw'])) {
5591
						$tier = 1;
5592
						unset($item['defaultgw']);
5593
					} else {
5594
						$tier = $tiernr4;
5595
					}
5596
					$newgroup4['item'][] = $item['name']."|$tier|address";
5597
					if ($tiernr4 < 5) {
5598
						$tiernr4++;
5599
					}
5600
				}
5601
				if ($item['ipprotocol'] == 'inet6') {
5602
					if (isset($item['defaultgw'])) {
5603
						$tier = 1;
5604
						unset($item['defaultgw']);
5605
					} else {
5606
						$tier = $tiernr6;
5607
					}
5608
					$newgroup6['item'][] = $item['name']."|$tier|address";
5609
					if ($tiernr6 < 5) {
5610
						$tiernr6++;
5611
					}
5612
				}
5613
			}
5614
			unset($item);
5615
		}
5616
		if (is_array($newgroup4['item']) && count($newgroup4['item']) > 0) {
5617
			$newname = "Default_Gateway_Group_ipv4";
5618
			if (gateway_or_gwgroup_exists($newname)) { //make sure we create a new name
5619
				$id = 2;
5620
				while (gateway_or_gwgroup_exists($newname."_".$id)) {
5621
					$id++;
5622
				}
5623
				$newname .= "_".$id;
5624
			}
5625
			$newgroup4['name'] = $newname;
5626
			$newgroup4['trigger'] = 0;
5627
			$newgroup4['descr'] = "Default gateway group IPv4";
5628
			$gateways_config['gateway_group'][] = $newgroup4;
5629
			$gateways_config['defaultgw4'] = $newname;
5630
		}
5631
		if (is_array($newgroup6['item']) && count($newgroup6['item']) > 0) {
5632
			$newname = "Default_Gateway_Group_ipv6";
5633
			if (gateway_or_gwgroup_exists($newname)) { //make sure we create a new name
5634
				$id = 2;
5635
				while (gateway_or_gwgroup_exists($newname."_".$id)) {
5636
					$id++;
5637
				}
5638
				$newname .= "_".$id;
5639
			}
5640
			$newgroup6['name'] = $newname;
5641
			$newgroup6['trigger'] = 0;
5642
			$newgroup6['descr'] = "Default gateway group IPv6";
5643
			$gateways_config['gateway_group'][] = $newgroup6;
5644
			$gateways_config['defaultgw6'] = $newname;
5645
		}
5646
		config_set_path('gateways', $gateways_config);
5647
		config_del_path('system/gw_switch_default');// remove old setting, if a group is used switching is already implied
5648
	} else {
5649
		// set new defaultgw selection boxes to old selected default
5650
		$gateways_config = config_get_path('gateways');
5651
		if (is_array($gateways_config) && is_array($gateways_config['gateway_item'])) {
5652
			foreach($gateways_config['gateway_item'] as &$item) {
5653
				if (isset($item['defaultgw'])) {
5654
					if ($item['ipprotocol'] == 'inet') {
5655
						$gateways_config['defaultgw4'] = $item['name'];
5656
					} else {
5657
						$gateways_config['defaultgw6'] = $item['name'];
5658
					}
5659
					unset($item['defaultgw']);
5660
				}
5661
			}
5662
			unset($item);
5663
			config_set_path('gateways', $gateways_config);
5664
		}
5665
	}
5666
}
5667

    
5668
/* Correct gateway group trigger level values.
5669
 * See https://redmine.pfsense.org/issues/8586
5670
 */
5671
function upgrade_182_to_183() {
5672
	$gateways_config = config_get_path('gateways/gateway_item');
5673
	if (!is_array($gateways_config)) {
5674
		/* No gateway groups, nothing to do. */
5675
		return;
5676
	}
5677
	foreach ($gateways_config as &$gwg) {
5678
		switch ($gwg['trigger']) {
5679
			case "0":
5680
				/* '0' => gettext('Member down'), */
5681
				/* 'down' => gettext("Member Down"), */
5682
				$gwg['trigger'] = "down";
5683
				break;
5684
			case "1":
5685
				/* '1' => gettext('Packet Loss'), */
5686
				/* 'downloss' => gettext("Packet Loss"), */
5687
				$gwg['trigger'] = "downloss";
5688
				break;
5689
			case "2":
5690
				/* '2' => gettext('High Latency'), */
5691
				/* 'downlatency' => gettext("High Latency"), */
5692
				$gwg['trigger'] = "downlatency";
5693
				break;
5694
			case "3":
5695
				/* '3' => gettext('Packet Loss or High latency') */
5696
				/* 'downlosslatency' => gettext("Packet Loss or High Latency")); */
5697
				$gwg['trigger'] = "downlosslatency";
5698
				break;
5699
		}
5700
	}
5701
	config_set_path('gateways/gateway_item', $gateways_config);
5702
}
5703

    
5704
function upgrade_183_to_184() {
5705
	/* 'none' was kinda confusing and didnt really do none
5706
	 * now use the new 'automatic' mode if it was set to none. */
5707
	if (config_get_path('gateways/defaultgw4', "") === "-") {
5708
		config_set_path('gateways/defaultgw4', "");
5709
	}
5710
	if (config_get_path('gateways/defaultgw6', "") === "-") {
5711
		config_set_path('gateways/defaultgw6', "");
5712
	}
5713
}
5714

    
5715
// Migrate AutoConfigBackup package settings to integrated ACB system
5716
// and remove package
5717
function upgrade_184_to_185() {
5718
	$acb_pkg_config = config_get_path('installedpackages/autoconfigbackup/config/0');
5719

    
5720
	if (is_array($acb_pkg_config)) {
5721
		$acbpkg = &$acb_pkg_config;
5722

    
5723
		config_init_path('system/acb');
5724
		$acb = config_get_path('system/acb');
5725
		$acb['enable'] = ($acbpkg['enable_acb'] != 'disabled') ?  'yes':'no';
5726
		$acb['gold_encryption_password'] = $acbpkg['crypto_password'];
5727

    
5728
		// If no encryption password has been set up yet, we might as well import the "Gold" password
5729
		// The user can update it later
5730
		if (!isset($acb['encryption_password'])) {
5731
			$acb['encryption_password'] = $acbpkg['crypto_password'];
5732
		}
5733

    
5734
		$acb['gold_password'] = $acbpkg['password'];
5735
		$acb['gold_username'] = $acbpkg['username'];
5736
		config_set_path('system/acb', $acb);
5737

    
5738
		config_del_path('installedpackages/autoconfigbackup/config');
5739
	}
5740
}
5741

    
5742
function upgrade_185_to_186() {
5743
	/* FEC LAGG is deprecated, replace with loadbalance */
5744
	if (!function_exists("file_notice")) {
5745
		require_once("notices.inc");
5746
	}
5747
	$lagg_config = config_get_path('laggs/lagg');
5748
	if (is_array($lagg_config)) {
5749
		foreach ($lagg_config as &$lagg) {
5750
			if ($lagg['proto'] == 'fec') {
5751
				$lagg['proto'] = 'failover';
5752
				file_notice("Interfaces", sprintf(gettext("The FEC LAGG protocol is deprecated. The %s LAGG interface has been set to failover."), $lagg['laggif']));
5753
			}
5754
		}
5755
		config_set_path('laggs/lagg', $lagg_config);
5756
	}
5757
}
5758

    
5759
function generate_usermanager_radius_config($cpzone, $counter, $protocol, $ip, $key, $port, $radiussrcip_attribute, $is_accounting=false, $accounting_port=false) {
5760
	$pconfig = array();
5761
	$pconfig['name'] = "Auto generated from Captive Portal {$cpzone}";
5762
	if ($counter != 1) {
5763
		$pconfig['name'] .= " {$counter}";
5764
	}
5765
	$pconfig['radius_srvcs'] = "auth";
5766
	$pconfig['type'] = 'radius';
5767
	$pconfig['radius_protocol'] = $protocol;
5768
	$pconfig['host'] = $ip;
5769
	$pconfig['radius_secret'] = $key;
5770
	$pconfig['radius_timeout'] = 3;
5771
	$pconfig['radius_auth_port'] = $port;
5772
	$pconfig['radius_nasip_attribute'] = $radiussrcip_attribute;
5773

    
5774
	if($is_accounting) {
5775
		$pconfig['radius_srvcs'] = "both";
5776
		$pconfig['radius_acct_port'] = $accounting_port;
5777
	}
5778

    
5779
	config_set_path('system/authserver/', $pconfig);
5780

    
5781
	return 'radius - '.$pconfig['name'];
5782
}
5783

    
5784
function upgrade_186_to_187() {
5785
	global $g;
5786

    
5787
	if (is_array(config_get_path('captiveportal'))) {
5788
		foreach (config_get_path('captiveportal', []) as $cpzone => $cp) {
5789
			// we flush any existing sqlite3 db.
5790
			// It will be automatically re-generated on next captiveportal_readdb()/captiveportal_writedb()
5791
			$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
5792
			unlink_if_exists($db_path);
5793

    
5794
			if ($cp['auth_method'] === 'radius') { // Radius Auth
5795
				$auth_servers = array();
5796
				$auth_servers2 = array();
5797
				$radiuscounter = 1;
5798

    
5799
				if (intval($cp['radiusport']) == 0) {
5800
					$cp['radiusport'] = 1812;
5801
				}
5802
				if (intval($cp['radiusacctport']) == 0) {
5803
					$cp['radiusacctport'] = 1813;
5804
				}
5805
				if (!isset($cp['radiussrcip_attribute'])) {
5806
					$cp['radiussrcip_attribute'] = 'wan';
5807
				}
5808
				$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']);
5809

    
5810
				if (!empty($cp['radiusip2'])) {
5811
					$radiuscounter++;
5812
					if (intval($cp['radiusport2']) == 0) {
5813
						$cp['radiusport2'] = 1812;
5814
					}
5815
					$auth_servers[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip2'], $cp['radiuskey2'], $cp['radiusport2'], $cp['radiussrcip_attribute'], false, 0);
5816
				}
5817
				if (!empty($cp['radiusip3'])) {
5818
					$radiuscounter++;
5819
					if (intval($cp['radiusport3']) == 0) {
5820
						$cp['radiusport3'] = 1812;
5821
					}
5822
					$auth_servers2[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip3'], $cp['radiuskey3'], $cp['radiusport3'], $cp['radiussrcip_attribute'], false, 0);
5823
				}
5824
				if (!empty($cp['radiusip4'])) {
5825
					$radiuscounter++;
5826
					if (intval($cp['radiusport4']) == 0) {
5827
						$cp['radiusport4'] = 1812;
5828
					}
5829
					$auth_servers2[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip4'], $cp['radiuskey4'], $cp['radiusport4'], $cp['radiussrcip_attribute'], false, 0);
5830
				}
5831

    
5832
				$cp['auth_method'] = 'authserver';
5833
				$cp['auth_server'] = implode(",", $auth_servers);
5834
				$cp['auth_server2'] = implode(",", $auth_servers2);
5835

    
5836
				if (isset($cp['radmac_enable'])) { // RadMac
5837
					$cp['auth_method'] = 'radmac';
5838
				}
5839
				if (isset($cp['radacct_enable'])) { // If accounting was enabled : we select the primary radius server for accounting
5840
					$cp['radacct_server'] = "Auto generated from Captive Portal {$cpzone}";
5841
					if ($cp['reauthenticateacct'] === "") {
5842
						$cp['reauthenticateacct'] = 'none';
5843
					}
5844
				}
5845
			} elseif ($cp['auth_method'] === 'local') { // Local Auth
5846
				$cp['auth_method'] = 'authserver';
5847
				$cp['auth_server'] = "Local Auth - Local Database";
5848
			}
5849
			// we don't need to update anything when "none" auth method is selected
5850

    
5851
			config_set_path("captiveportal/{$cpzone}", $cp);
5852
		}
5853
	}
5854
}
5855

    
5856
function upgrade_187_to_188() {
5857
	$old_cmd = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshlockout";
5858
	$new_cmd = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard";
5859
	config_init_path('cron/item');
5860
	foreach (config_get_path('cron/item', []) as $idx => $entry) {
5861
		if ($entry['command'] == $old_cmd) {
5862
			config_set_path("cron/item/{$idx}/command", $new_cmd);
5863
			break;
5864
		}
5865
	}
5866
}
5867

    
5868
function upgrade_188_to_189() {
5869
	/* Migrate ssh setting to new location */
5870
	if (config_path_enabled('system', 'enablesshd')) {
5871
		config_init_path('system/ssh');
5872
		config_set_path('system/ssh/enable', "enabled");
5873
		config_del_path('system/enablesshd');
5874
	}
5875
	/* Remove accidentally duplicated ssh config
5876
	 * See https://redmine.pfsense.org/issues/8974 */
5877
	config_del_path('system/sshd');
5878
}
5879

    
5880
/* Older preexisting IPsec P1 entries may not have had the protocol explicitly
5881
 * defined. Fill in the default value of 'inet'.
5882
 * https://redmine.pfsense.org/issues/9207 */
5883
function upgrade_189_to_190() {
5884
	config_init_path('ipsec/phase1');
5885
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
5886
	foreach ($ipsec_phase1_config as & $ph1ent) {
5887
		if (empty($ph1ent)) {
5888
			continue;
5889
		}
5890
		if (!isset($ph1ent['protocol']) || empty($ph1ent['protocol'])) {
5891
			$ph1ent['protocol'] = 'inet';
5892
		}
5893
	}
5894
	config_set_path('ipsec/phase1', $ipsec_phase1_config);
5895
}
5896

    
5897
/* sshguard cron jobs are not necessary.
5898
 * See https://redmine.pfsense.org/issues/9223 */
5899
function upgrade_190_to_191() {
5900
	install_cron_job("/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard", false, null, null, null, null, null, null, false);
5901
	install_cron_job("/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 webConfiguratorlockout", false, null, null, null, null, null, null, false);
5902
}
5903

    
5904
/* Deprecate relayd Load Balancer
5905
 * See https://redmine.pfsense.org/issues/9386 */
5906
function upgrade_191_to_192() {
5907
	/* Backup LB config */
5908
	$backup_file = "/conf/deprecated_load_balancer.xml";
5909
	unlink_if_exists($backup_file);
5910
	file_put_contents($backup_file, backup_config_section('load_balancer'));
5911

    
5912
	/* Determine if LB was active and notify (or log if not) */
5913
	$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);
5914
	$loadbalancer_config = config_get_path('load_balancer');
5915
	if (is_array($loadbalancer_config['virtual_server']) &&
5916
	    count($loadbalancer_config['virtual_server']) &&
5917
	    count($loadbalancer_config['lbpool'])) {
5918

    
5919
		if (!function_exists("file_notice")) {
5920
			require_once("notices.inc");
5921
		}
5922
		file_notice("Load Balancer", $deprecation_notice);
5923
	} else {
5924
		log_error("INFO: {$deprecation_notice}");
5925
	}
5926

    
5927
	config_del_path('load_balancer');
5928

    
5929
	/* Remove LB HA Sync Config */
5930
	config_del_path('hasync/synchronizelb');
5931

    
5932
	/* If the LB widget is present, remove it*/
5933
	if (config_path_enabled('widgets', 'sequence') &&
5934
	    (strpos(config_get_path('widgets/sequence'), 'load_balancer_status') !== false)) {
5935
		$widgets = explode(',', trim(config_get_path('widgets/sequence')));
5936
		foreach ($widgets as $idx => &$widget) {
5937
			if (substr( $widget, 0, 20 ) === "load_balancer_status") {
5938
				unset($widgets[$idx]);
5939
			}
5940
		}
5941
		config_set_path('widgets/sequence', implode(',', $widgets));
5942
	}
5943

    
5944
	/* Per-log settings */
5945
	config_del_path('syslog/relayd_settings');
5946
}
5947

    
5948
/* Deprecate growl notifications */
5949
function upgrade_192_to_193() {
5950
	config_del_path('notifications/growl');
5951
}
5952

    
5953
function upgrade_193_to_194() {
5954
	global $g;
5955

    
5956
	if (is_array(config_get_path('captiveportal'))) {
5957
		foreach (config_get_path('captiveportal', []) as $cpzone => $cp) {
5958
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
5959
		}
5960
	}
5961
}
5962

    
5963
/*
5964
 * Reset all log files, including package logs, on upgrade since old logs are in
5965
 * binary clog format.
5966
 * Conversion is not possible since the clog binary will not be present.
5967
 * https://redmine.pfsense.org/issues/8350
5968
 */
5969
function upgrade_194_to_195() {
5970
	global $g;
5971

    
5972
	$logfiles = system_syslogd_get_all_logfilenames();
5973

    
5974
	foreach ($logfiles as $logfile) {
5975
		if (substr($logfile, -4) != '.log') {
5976
			$logfile .= ".log";
5977
		}
5978
		$logpath = "{$g['varlog_path']}/{$logfile}";
5979
		exec("/usr/bin/truncate -s 0 " . escapeshellarg($logpath));
5980
	}
5981
}
5982

    
5983
/* Skipped. See https://redmine.pfsense.org/issues/9730 */
5984
function upgrade_195_to_196() {
5985
}
5986

    
5987
/* Add newsyslog cron job */
5988
function upgrade_196_to_197() {
5989
	global $g;
5990

    
5991
	install_cron_job('/usr/sbin/newsyslog', true, "*/1", '*', '*', '*', '*', 'root', false);
5992
}
5993

    
5994
/* Add periodic cron jobs */
5995
function upgrade_197_to_198() {
5996
	global $g;
5997

    
5998
	install_cron_job('/etc/rc.periodic daily',   true, "1",  '3', '*', '*', '*', 'root', false);
5999
	install_cron_job('/etc/rc.periodic weekly',  true, "15", '4', '*', '*', '6', 'root', false);
6000
	install_cron_job('/etc/rc.periodic monthly', true, "30", '5', '1', '*', '*', 'root', false);
6001
}
6002

    
6003
/* Update IPsec authentication method names
6004
 * https://redmine.pfsense.org/issues/9903 */
6005
function upgrade_198_to_199() {
6006
	/* "RSA" methods changed to the more generic "cert" since they are not only RSA. */
6007
	$namechanges = array(
6008
		'hybrid_rsa_server' => 'hybrid_cert_server',
6009
		'xauth_rsa_server' => 'xauth_cert_server',
6010
		'rsasig' => 'cert',
6011
	);
6012
	config_init_path('ipsec/phase1');
6013
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
6014
	foreach ($ipsec_phase1_config as & $ph1ent) {
6015
		/* If the auth method for this P1 is in the list to change, change it */
6016
		if (array_key_exists($ph1ent['authentication_method'], $namechanges)) {
6017
			$ph1ent['authentication_method'] = $namechanges[$ph1ent['authentication_method']];
6018
		}
6019
	}
6020
	config_set_path('ipsec/phase1', $ipsec_phase1_config);
6021
}
6022

    
6023
/* Superceded. See https://redmine.pfsense.org/issues/11219 and upgrade_212_to_213() */
6024
function upgrade_199_to_200() {
6025
}
6026

    
6027
/* Update LDAP transport values */
6028
function upgrade_200_to_201() {
6029
	/* Normalize/correct names (All are TCP) */
6030
	$namechanges = array(
6031
		'TCP - Standard' => 'Standard TCP',
6032
		'TCP - STARTTLS' => 'STARTTLS Encrypted',
6033
		'SSL - Encrypted' => 'SSL/TLS Encrypted',
6034
	);
6035
	config_init_path('system/authserver');
6036
	$authserver_config = config_get_path('system/authserver');
6037
	foreach ($authserver_config as & $authserver) {
6038
		if (array_key_exists($authserver['ldap_urltype'], $namechanges)) {
6039
			$authserver['ldap_urltype'] = $namechanges[$authserver['ldap_urltype']];
6040
		}
6041
	}
6042
	config_set_path('system/authserver', $authserver_config);
6043
}
6044

    
6045
/* #10525: Handle Chinese (HongKong / Taiwan) locale rename */
6046
function upgrade_201_to_202() {
6047
	if (config_get_path('system/language') == 'zh_HK') {
6048
		config_set_path('system/language', 'zh_Hans_HK');
6049
	} elseif (config_get_path('system/language') == 'zh_TW') {
6050
		config_set_path('system/language', 'zh_Hant_TW');
6051
	}
6052
}
6053

    
6054
function upgrade_202_to_203() {
6055
	$gre_config = config_get_path('gres/gre');
6056
	// Upgrade GREs with IPv6 tunnel networks to new dual stack format
6057
	if (is_array($gre_config)) {
6058
		foreach ($gre_config as $idx => &$gre) {
6059
			if (is_ipaddrv6($gre['tunnel-local-addr'])) {
6060
				$gre['tunnel-local-addr6'] = $gre['tunnel-local-addr'];
6061
				$gre['tunnel-remote-addr6'] = $gre['tunnel-remote-addr'];
6062
				$gre['tunnel-remote-net6'] = $gre['tunnel-remote-net'];
6063
				$gre['tunnel-local-addr'] = '';
6064
				$gre['tunnel-remote-addr'] = '';
6065
				$gre['tunnel-remote-net'] = '';
6066
			} else {
6067
				$gre['tunnel-local-addr6'] = '';
6068
				$gre['tunnel-remote-addr6'] = '';
6069
				$gre['tunnel-remote-net6'] = '';
6070
			}
6071
		}
6072
		config_set_path('gres/gre', $gre_config);
6073
	}
6074
}
6075

    
6076
/*
6077
 * Change IPsec close_action values
6078
 * See https://redmine.pfsense.org/issues/10632
6079
 */
6080

    
6081
function upgrade_203_to_204() {
6082
	config_init_path('ipsec/phase1');
6083
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
6084
	foreach ($ipsec_phase1_config as & $ph1ent) {
6085
		if (empty($ph1ent)) {
6086
			continue;
6087
		}
6088
		if (isset($ph1ent['closeaction'])) {
6089
			switch ($ph1ent['closeaction']) {
6090
				case 'clear':
6091
					/* swanctl.conf combined "clear" and "none" */
6092
					$ph1ent['closeaction'] = "none";
6093
					break;
6094
				case 'restart':
6095
					/* swanctl.conf uses "start" not "restart" */
6096
					$ph1ent['closeaction'] = "start";
6097
					break;
6098
				case 'hold':
6099
					/* swanctl.conf uses "trap" not "hold" */
6100
					$ph1ent['closeaction'] = "trap";
6101
					break;
6102
				default:
6103
					/* "none" does not need changed. */
6104
			}
6105
		}
6106
	}
6107
	config_set_path('ipsec/phase1', $ipsec_phase1_config);
6108
}
6109

    
6110
function upgrade_204_to_205() {
6111
	global $g;
6112

    
6113
	$cp_config = config_get_path('captiveportal');
6114
	if (is_array($cp_config)) {
6115
		foreach ($cp_config as $cpzone => $cp) {
6116
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
6117

    
6118
			if (!empty(config_get_path("voucher/{$cpzone}/vouchersyncdbip"))) {
6119
				$cp_config[$cpzone]['enablebackwardsync'] = '';
6120
				$cp_config[$cpzone]['backwardsyncip'] = config_get_path("voucher/{$cpzone}/vouchersyncdbip");
6121
				$cp_config[$cpzone]['backwardsyncuser'] = config_get_path("voucher/{$cpzone}/vouchersyncusername");
6122
				$cp_config[$cpzone]['backwardsyncpassword'] = config_get_path("voucher/{$cpzone}/vouchersyncpass");
6123
			}
6124
		}
6125
		config_set_path('captiveportal', $cp_config);
6126
	}
6127
}
6128

    
6129
function upgrade_205_to_206() {
6130
	/*
6131
	 * Trigger a boot loader settings update to make sure the contents will
6132
	 * be updated before the reboot.
6133
	 */
6134
	console_configure();
6135
}
6136

    
6137
function upgrade_206_to_207() {
6138
	/*
6139
	 * Trigger a boot loader settings update to make sure the contents will
6140
	 * be updated before the reboot.
6141
	 */
6142
	console_configure();
6143
}
6144

    
6145
function upgrade_207_to_208() {
6146
	config_set_path('system/hn_altq_enable', true);
6147
}
6148

    
6149
/* Update IPsec VTI to new VTIMAP format
6150
 * https://redmine.pfsense.org/issues/9592
6151
 */
6152
function upgrade_208_to_209() {
6153
	require_once("interfaces.inc");
6154

    
6155
	config_init_path('ipsec/vtimaps/item');
6156
	$ipsec_config = config_get_path('ipsec');
6157

    
6158
	if (!is_array($ipsec_config['phase1']) ||
6159
	    !is_array($ipsec_config['phase2'])) {
6160
		return;
6161
	}
6162

    
6163
	foreach ($ipsec_config['phase1'] as $ph1ent) {
6164
		if (!isset($ph1ent['mobile']) &&
6165
		    ($ph1ent['iketype'] == 'ikev1' ||
6166
		    isset($ph1ent['splitconn']))) {
6167
			$vtisubnet_spec = ipsec_vti($ph1ent, true, false);
6168
			if (empty($vtisubnet_spec)) {
6169
				continue;
6170
			}
6171
			foreach ($vtisubnet_spec as $idx => $vtisub) {
6172
				$ipsec_config['vtimaps']['item'][] = array(
6173
					"reqid" => $ph1ent['ikeid'],
6174
					"index" => $idx,
6175
					"ifnum" => "{$ph1ent['ikeid']}00{$idx}"
6176
				);
6177
			}
6178
		} else {
6179
			$ipsec_config['vtimaps']['item'][] = array(
6180
				"reqid" => $ph1ent['ikeid'],
6181
				"index" => "0",
6182
				"ifnum" => "{$ph1ent['ikeid']}000"
6183
			);
6184
		}
6185
	}
6186
	config_set_path('ipsec', $ipsec_config);
6187
}
6188

    
6189
function upgrade_209_to_210() {
6190
	if (config_get_path('system/dnslocalhost') !== null) {
6191
		config_set_path('system/dnslocalhost', 'remote');
6192
	}
6193
}
6194

    
6195
/* OpenVPN Data Cipher changes
6196
 * https://redmine.pfsense.org/issues/10919 */
6197
function upgrade_210_to_211() {
6198
	config_init_path('openvpn/openvpn-server');
6199
	config_init_path('openvpn/openvpn-client');
6200
	$openvpn_config = config_get_path('openvpn');
6201
	foreach(array('server', 'client') as $mode) {
6202
		foreach ($openvpn_config["openvpn-{$mode}"] as & $settings) {
6203
			/* Rename ncp-ciphers to data_ciphers */
6204
			if (!empty($settings['ncp-ciphers'])) {
6205
				$settings['data_ciphers'] = $settings['ncp-ciphers'];
6206
			} elseif ($settings['crypto'] == 'none') {
6207
				$settings['data_ciphers'] = 'none';
6208
			} else {
6209
				$settings['data_ciphers'] = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305';
6210
			}
6211
			if (isset($settings['ncp-ciphers'])) {
6212
				unset($settings['ncp-ciphers']);
6213
			}
6214
			/* Add crypto to data_ciphers */
6215
			if (!empty($settings['crypto']) &&
6216
			    ($settings['crypto'] != 'none') &&
6217
			    !in_array($settings['crypto'], explode(',', $settings['data_ciphers']))) {
6218
				$settings['data_ciphers'] .= ',' . $settings['crypto'];
6219
			}
6220
			/* Rename crypto to data_ciphers_fallback */
6221
			if (isset($settings['crypto'])) {
6222
				$settings['data_ciphers_fallback'] = $settings['crypto'];
6223
				unset($settings['crypto']);
6224
			}
6225
			/* Forcefully enable data cipher negotiation since
6226
			 * disabling negotiation is now deprecated */
6227
			$settings['ncp_enable'] = "enabled";
6228
		}
6229
		unset($settings);
6230
	}
6231
	config_set_path('openvpn', $openvpn_config);
6232
}
6233

    
6234
function upgrade_211_to_212() {
6235
	if (config_path_enabled('unbound', 'sslport')) {
6236
		config_set_path('unbound/tlsport', config_get_path('unbound/sslport'));
6237
		config_del_path('unbound/sslport');
6238
	}
6239
}
6240

    
6241
/* IPsec Expiration and Replacement values which need updated for swanctl format
6242
 * https://redmine.pfsense.org/issues/11219
6243
 * https://redmine.pfsense.org/issues/9983
6244
 */
6245
function upgrade_212_to_213() {
6246
	config_init_path('ipsec/phase1');
6247
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
6248
	foreach ($ipsec_phase1_config as & $ph1ent) {
6249
		if (empty($ph1ent)) {
6250
			continue;
6251
		}
6252

    
6253
		if (isset($ph1ent['reauth_enable'])) {
6254
			/* Disable reauth */
6255
			$ph1ent['reauth_time'] = "0";
6256
		} elseif (!empty($ph1ent['margintime'])) {
6257
			/* If margintime is set, use that to calculte reauth_time */
6258
			$ph1ent['reauth_time'] = ($ph1ent['lifetime'] - $ph1ent['margintime']);
6259
		}
6260
		/* Auto or IKEv2, rekey items */
6261
		if (($ph1ent['iketype'] == 'ikev2') || ($ph1ent['iketype'] == 'auto')) {
6262
			if (isset($ph1ent['rekey_enable'])) {
6263
				/* Disable rekey */
6264
				$ph1ent['rekey_time'] = "0";
6265
				$ph1ent['reauth_time'] = "0";
6266
			} elseif (!empty($ph1ent['margintime'])) {
6267
				/* If margintime is set, use that to calculate rekey_time */
6268
				$ph1ent['rekey_time'] = ($ph1ent['lifetime'] - $ph1ent['margintime']);
6269
			}
6270
		}
6271

    
6272
		if (!empty($ph1ent['margintime'])) {
6273
			$ph1ent['rand_time'] = $ph1ent['margintime'];
6274
		}
6275

    
6276
		/* Older snaps had over_time, now need lifetime back. */
6277
		if (!empty($ph1ent['over_time']) && empty($ph1ent['lifetime'])) {
6278
			$ph1ent['lifetime'] = $ph1ent['over_time'] + max($ph1ent['rekey_time'], $ph1ent['reauth_time']);
6279
		}
6280

    
6281
		if (isset($ph1ent['reauth_enable'])) {
6282
			unset($ph1ent['reauth_enable']);
6283
		}
6284
		if (isset($ph1ent['rekey_enable'])) {
6285
			unset($ph1ent['rekey_enable']);
6286
		}
6287
		if (isset($ph1ent['margintime'])) {
6288
			unset($ph1ent['margintime']);
6289
		}
6290
		if (isset($ph1ent['over_time'])) {
6291
			unset($ph1ent['over_time']);
6292
		}
6293
	}
6294
	config_set_path('ipsec/phase1', $ipsec_phase1_config);
6295
}
6296

    
6297
/* VXLAN support was removed */
6298
function upgrade_213_to_214() {
6299
	config_del_path('vxlans');
6300
}
6301

    
6302
/* WireGuard support was removed */
6303
function upgrade_214_to_215() {
6304
	config_del_path('wireguard');
6305
}
6306

    
6307
/* Fix VTI interface numbers */
6308
function upgrade_215_to_216() {
6309
	if (count(config_get_path('ipsec/vtimaps/item', [])) == 0) {
6310
		return;
6311
	}
6312

    
6313
	/* Deprecated method. */
6314
	function upgrade216_ipsec_create_vtimap($ikeid, $idx) {
6315
		$assigned = array_column(config_get_path('ipsec/vtimaps/item', []), 'ifnum');
6316
		asort($assigned, SORT_NUMERIC);
6317
		$new = 1;
6318
		foreach ($assigned as $ipsecifnum) {
6319
			if ($ipsecifnum != $new) {
6320
				break;
6321
			}
6322
			if ($new++ > 32767) {
6323
				return(NULL);
6324
			}
6325
		}
6326
		return array(
6327
			"reqid" => $ikeid,
6328
			"index" => $idx,
6329
			"ifnum" => $new
6330
		);
6331
	}
6332

    
6333
	$iflist = get_configured_interface_list_by_realif(true);
6334

    
6335
	foreach (config_get_path('ipsec/vtimaps/item', []) as $idx => $vtimap) {
6336
		if ($vtimap['ifnum'] <= 32767) {
6337
			continue;
6338
		}
6339

    
6340
		$new_vtimap = upgrade216_ipsec_create_vtimap($vtimap['reqid'],
6341
		    $vtimap['index']);
6342

    
6343
		/*
6344
		 * NULL means 32767 limit was reached.  It should never hit
6345
		 * this
6346
		 */
6347
		if ($new_vtimap == NULL) {
6348
			break;
6349
		}
6350

    
6351
		$old_if = 'ipsec' . $vtimap['ifnum'];
6352

    
6353
		/* Interface is assigned */
6354
		if (isset($iflist[$old_if])) {
6355
			config_set_path('interfaces/' . $iflist[$old_if] . '/if', 'ipsec' . $new_vtimap['ifnum']);
6356
		}
6357

    
6358
		config_set_path('ipsec/vtimaps/item/' . $idx, $new_vtimap);
6359
	}
6360
}
6361

    
6362
/*
6363
 * Child SA Start Action has replaced the Responder Only option. Update P1
6364
 * to match.
6365
 * https://redmine.pfsense.org/issues/11576
6366
 */
6367
function upgrade_216_to_217() {
6368
	config_init_path('ipsec/phase1');
6369
	$ipsec_phase1_config = config_get_path('ipsec/phase1');
6370
	foreach ($ipsec_phase1_config as & $ph1ent) {
6371
		if (empty($ph1ent)) {
6372
			continue;
6373
		}
6374
		if (isset($ph1ent['responderonly'])) {
6375
			$ph1ent['startaction'] = 'none';
6376
			unset($ph1ent['responderonly']);
6377
		}
6378
	}
6379
	config_set_path('ipsec/phase1', $ipsec_phase1_config);
6380
}
6381

    
6382
/*
6383
 * Disable PC/SC Smart Card Daemon if PKCS#11 authentication is not used
6384
 * https://redmine.pfsense.org/issues/11933
6385
 */
6386
function upgrade_217_to_218() {
6387
	config_init_path('ipsec/phase1');
6388
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
6389
		if (empty($ph1ent)) {
6390
			continue;
6391
		}
6392
		if (($ph1ent['authentication_method'] == 'pkcs11') &&
6393
		    !isset($ph1ent['disabled'])) {
6394
			config_set_path('ipsec/pkcs11support', true);
6395
			break;
6396
		}
6397
	}
6398
}
6399

    
6400
/*
6401
 * Convert VTI interface names to new format
6402
 */
6403
function upgrade_218_to_219() {
6404
	config_init_path('ipsec/phase1');
6405
	config_init_path('ipsec/phase2');
6406
	config_init_path('ipsec/vtimaps/item');
6407

    
6408
	/* Deprecated method.
6409
	 * $ipsecifnum = get_ipsecifnum($ikeid, $idx);
6410
	 * locates and returns an ipsecifnum in the config.
6411
	 */
6412
	function upgrade219_get_ipsecifnum($ikeid, $idx) {
6413
		foreach (config_get_path('ipsec/vtimaps/item', []) as $vtimap) {
6414
			if (($vtimap['reqid'] == $ikeid) &&
6415
			    ($vtimap['index'] == $idx)) {
6416
				return $vtimap['ifnum'];
6417
			}
6418
		}
6419
		return false;
6420
	}
6421

    
6422
	/* If IPsec is disabled or there are no P1 or P2 entries, there cannot
6423
	 * be any current assignments, so bail early */
6424
	if (!ipsec_enabled() ||
6425
	    empty(config_get_path('ipsec/phase1')) ||
6426
	    empty(config_get_path('ipsec/phase2'))) {
6427
		return false;
6428
	}
6429

    
6430
	/* Make an associative array with old name as key and new name as value for all VTI tunnels */
6431
	$ipsecifs = array();
6432
	foreach (config_get_path('ipsec/phase1', []) as $ph1ent) {
6433
		if (empty($ph1ent) || !is_array($ph1ent)) {
6434
			continue;
6435
		}
6436
		$ifent = array();
6437
		/* If there is data here, then it's a VTI tunnel */
6438
		$vtisubnet_spec = ipsec_vti($ph1ent, true);
6439
		if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
6440
			/* Not VTI, so skip it. */
6441
			continue;
6442
		}
6443
		if (!isset($ph1ent['mobile']) && ($ph1ent['iketype'] == 'ikev1' || isset($ph1ent['splitconn']))) {
6444
			foreach ($vtisubnet_spec as $idx => $vtisub) {
6445
				/* Determine old name */
6446
				$old = "ipsec" . upgrade219_get_ipsecifnum($ph1ent['ikeid'], $idx);
6447
				/* Determine new name */
6448
				$new = ipsec_get_ifname($ph1ent, $vtisub['reqid']);
6449
				$ipsecifs[$old] = $new;
6450
			}
6451
		} else {
6452
			/* For IKEv2, only create one interface with additional addresses as aliases */
6453
			/* Determine old name */
6454
			$old = "ipsec" . upgrade219_get_ipsecifnum($ph1ent['ikeid'], 0);
6455
			/* Determine new name */
6456
			$new = ipsec_get_ifname($ph1ent);
6457
			$ipsecifs[$old] = $new;
6458
		}
6459
	}
6460

    
6461
	/* If there are no VTI interfaces, we have nothing to do */
6462
	if (empty($ipsecifs)) {
6463
		return null;
6464
	}
6465

    
6466
	$if_config = config_get_path('interfaces');
6467
	foreach ($if_config as &$ifcfg) {
6468
		/* Check current interface assignments and see if any match a value we want */
6469
		if (array_key_exists($ifcfg['if'], $ipsecifs)) {
6470
			/* Update assignment to new name */
6471
			$ifcfg['if'] = $ipsecifs[$ifcfg['if']];
6472
		}
6473
	}
6474
	config_set_path('interfaces', $if_config);
6475
	config_del_path('ipsec/vtimaps');
6476
}
6477

    
6478
/*
6479
 * Ensure the ACB cron job is installed after upgrade if ACB is enabled
6480
 * If the cron job already exists, no harm is done
6481
 */
6482
function upgrade_219_to_220() {
6483
	config_init_path('system/acb');
6484

    
6485
	if (config_get_path('system/acb/enable') == "yes" && file_exists("/usr/local/sbin/acbupload.php")) {
6486
		install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/acbupload.php", true, "*");
6487
	}
6488
}
6489

    
6490
/*
6491
 * Add new disk widget to dashboard if user already had the system information
6492
 * wiget configured to show disk usage stats.
6493
 */
6494
function upgrade_220_to_221() {
6495
	$widgets = explode(',', config_get_path('widgets/sequence'));
6496

    
6497
	foreach ($widgets as $idx => $widget) {
6498
		[$name, $col, $state, $index] = explode(':', $widget);
6499

    
6500
		if ($name === 'system_information') {
6501
			$widget_settings_key = "{$name}-{$index}";
6502

    
6503
			$filter = explode(',', config_get_path("widgets/{$widget_settings_key}/filter"));
6504

    
6505
			if (!in_array('disk_usage', $filter)) {
6506
				$disk_widget = implode(':', array_filter(['disks', $col, $state, $index]));
6507

    
6508
				if (!in_array($disk_widget, $widgets)) {
6509
					array_splice($widgets, ($idx + 1), 0, $disk_widget);
6510
				}
6511
			}
6512
		}
6513
	}
6514

    
6515
	config_set_path('widgets/sequence', implode(',', $widgets));
6516
}
6517

    
6518
/* No functional changes. */
6519
function upgrade_221_to_222() {
6520
}
6521

    
6522
function upgrade_222_to_223() {
6523
	$user_config = config_get_path('system/user');
6524

    
6525
	foreach ($user_config as & $user) {
6526
		if ($user['name'] == 'admin') {
6527
			$user_home = "/root";
6528
		} else {
6529
			$user_home = "/home/{$user['name']}";
6530
		}
6531
		$fn = "{$user_home}/.keephistory";
6532
		if (file_exists($fn)) {
6533
			$user['keephistory'] = true;
6534
			@unlink($fn);
6535
		}
6536
	}
6537
	config_set_path('system/user', $user_config);
6538
}
6539

    
6540
function upgrade_223_to_224() {
6541
	config_init_path('filter/rule');
6542
	$filter_rule_config = config_get_path('filter/rule');
6543
	foreach ($filter_rule_config as & $rule) {
6544
		if (isset($rule['floating']) && !isset($rule['interface'])) {
6545
			$rule['interface'] = 'any';
6546
		}
6547
	}
6548
	config_set_path('filter/rule', $filter_rule_config);
6549
}
6550

    
6551
function upgrade_224_to_225() {
6552
	$if_config = config_get_path('interfaces');
6553

    
6554
	/* DHCP6 now uses single config for all interfaces
6555
	 * see https://redmine.pfsense.org/issues/6880 */
6556
	foreach ($if_config as & $inf) {
6557
		if (isset($inf['dhcp6debug'])) {
6558
			config_set_path('system/dhcp6debug', true);
6559
			unset($inf['dhcp6debug']);
6560
		}
6561
		if (isset($inf['dhcp6norelease'])) {
6562
			config_set_path('system/dhcp6norelease', true);
6563
			unset($inf['dhcp6norelease']);
6564
		}
6565
	}
6566
	config_set_path('interfaces', $if_config);
6567
}
6568

    
6569
function upgrade_225_to_226() {
6570
	/* Update value of state killing on gateway failure.
6571
	 * https://redmine.pfsense.org/issues/12092
6572
	 */
6573
	if (config_path_enabled('system', 'gw_down_kill_states')) {
6574
		config_set_path('system/gw_down_kill_states', 'all');
6575
	}
6576
}
6577

    
6578
function upgrade_226_to_227() {
6579
	/* Convert dnsmasq (forwarder) custom options to base64.
6580
	 * https://redmine.pfsense.org/issues/13105
6581
	 */
6582
	if (!empty(config_get_path('dnsmasq/custom_options'))) {
6583
		config_set_path('dnsmasq/custom_options', base64_encode(config_get_path('dnsmasq/custom_options')));
6584
	}
6585
}
6586

    
6587
function upgrade_227_to_228() {
6588
	$ipsec_config = config_get_path('ipsec');
6589

    
6590
	$any_removed = false;
6591
	/* We no longer support 3des, blowfish, cast128 or md5 and sha1
6592
	 * authentication for IPSec. */
6593
	if (is_array($ipsec_config)) {
6594
		if (is_array($ipsec_config['phase1'])) {
6595
			foreach ($ipsec_config['phase1'] as & $phase1) {
6596
				if (! isset($phase1['encryption']) || !is_array($phase1['encryption']['item']))
6597
					continue;
6598

    
6599
				$bad_count = 0;
6600
				foreach ($phase1['encryption']['item'] as $k => $enc) {
6601
					$bad = false;
6602
					if (isset($enc['encryption-algorithm']['name']) &&
6603
					    in_array($enc['encryption-algorithm']['name'],
6604
					    array("blowfish", "3des", "cast128"))) {
6605
						$bad = true;
6606
					}
6607
					if (isset($enc['hash-algorithm']) && $enc['hash-algorithm'] == "md5") {
6608
						$bad = true;
6609
					}
6610
					if ($bad) {
6611
						/* Remove this item as it contains deprecated encryption or hashing */
6612
						unset($phase1['encryption']['item'][$k]);
6613
						$bad_count++;
6614
					}
6615
				}
6616
				if ($bad_count > 0) {
6617
					$any_removed = true;
6618
					/* Only notify once per P1 */
6619
					if (count($phase1['encryption']['item']) == 0) {
6620
						/* Only disable P1 if there are no valid encryption options left. */
6621
						$phase1['disabled'] = true;
6622
						unset($phase1['encryption']);
6623
						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']));
6624
					} else {
6625
						/* Let the user know that the P1 was adjusted */
6626
						file_notice("IPsec", sprintf(gettext("Removed deprecated encryption options from IPsec Phase 1 '%s'."), $phase1['descr']));
6627
					}
6628
				}
6629
			}
6630
		}
6631
		if (is_array($ipsec_config['phase2'])) {
6632
			foreach ($ipsec_config['phase2'] as & $phase2) {
6633

    
6634
				$bad_count = 0;
6635
				if (is_array($phase2['encryption-algorithm-option'])) {
6636
					foreach ($phase2['encryption-algorithm-option'] as $k => $opt) {
6637
						if (in_array($opt['name'], array("blowfish", "3des", "cast128"))) {
6638
							/* Remove this item as it contains deprecated encryption */
6639
							unset($phase2['encryption-algorithm-option'][$k]);
6640
							$bad_count++;
6641
						}
6642
					}
6643
				}
6644
				if (is_array($phase2['hash-algorithm-option'])) {
6645
					foreach ($phase2['hash-algorithm-option'] as $k => $opt) {
6646
						if ($opt == "hmac_md5") {
6647
							/* Remove this item as it contains deprecated hashing */
6648
							unset($phase2['hash-algorithm-option'][$k]);
6649
							$bad_count++;
6650
						}
6651
					}
6652
				}
6653

    
6654
				if ($bad_count > 0) {
6655
					$any_removed = true;
6656
					/* Only notify once per P2 */
6657
					if ((count($phase2['encryption-algorithm-option']) == 0) ||
6658
					    (count($phase2['hash-algorithm-option']) == 0)) {
6659
						/* Only disable P2 if there are no valid encryption options left. */
6660
						$phase2['disabled'] = true;
6661
						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']));
6662
					} else {
6663
						/* Let the user know that the P2 was adjusted */
6664
						file_notice("IPsec", sprintf(gettext("Removed deprecated encryption options from IPsec Phase 2 '%s'."), $phase2['descr']));
6665
					}
6666
				}
6667
			}
6668
		}
6669
		config_set_path('ipsec', $ipsec_config);
6670
	}
6671

    
6672
	/* Only list deprecated types once */
6673
	if ($any_removed) {
6674
		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."));
6675
	}
6676
}
6677

    
6678
function upgrade_228_to_229() {
6679
	global $g;
6680
	/* Update System Memory RRD file with new data sources
6681
	 * https://redmine.pfsense.org/issues/14011
6682
	 */
6683
	$rrddbpath = "/var/db/rrd/";
6684
	$database = "system-memory.rrd";
6685
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
6686
	$rrdinterval = 60;
6687
	$valid = $rrdinterval * 2;
6688
	if (is_platform_booting()) {
6689
		echo "Migrating System Memory RRD file to new format\n";
6690
	}
6691
	mwexec("$rrdtool tune {$rrddbpath}{$database} DS:userwire:GAUGE:{$valid}:0:10000000 2>&1");
6692
	mwexec("$rrdtool tune {$rrddbpath}{$database} DS:laundry:GAUGE:{$valid}:0:10000000 2>&1");
6693
	mwexec("$rrdtool tune {$rrddbpath}{$database} DS:buffers:GAUGE:{$valid}:0:10000000 2>&1");
6694
}
6695

    
6696
function upgrade_229_to_230() {
6697
	/* The "target" GUI for outbound NAT rules now behaves similarly to other pages. */
6698
	$obn_rules = config_get_path('nat/outbound/rule', []);
6699
	foreach ($obn_rules as & $obent) {
6700
		if (empty($obent['target'])) {
6701
			// migrate interface address selection
6702
			$obent['target'] = $obent['interface'] . 'ip';
6703
			$obent['target_subnet'] = '';
6704
		} elseif ($obent['target'] == 'other-subnet') {
6705
			// migrate custom subnets
6706
			$obent['target'] = $obent['targetip'];
6707
			$obent['target_subnet'] = (get_specialnet($obent['target'], [SPECIALNET_IFADDR])) ? '' : $obent['targetip_subnet'];
6708
		} else {
6709
			// migrate VIPs and aliases
6710
			$obent['target_subnet'] = '';
6711
		}
6712
		foreach (['targetip', 'targetip_subnet'] as $old) {
6713
			if (array_key_exists($old, $obent)) {
6714
				unset($obent[$old]);
6715
			}
6716
		}
6717
		// migrate destination address
6718
		if (array_key_exists('address', $obent['destination'])) {
6719
			$obent['destination']['network'] = $obent['destination']['address'];
6720
			unset($obent['destination']['address']);
6721
		}
6722
	}
6723
	if (isset($obent)) {
6724
		unset($obent);
6725
	}
6726
	config_set_path('nat/outbound/rule', $obn_rules);
6727

    
6728
	/* A reserved keyword suffix has been added; migrate conflicting aliases */
6729
	$aliases = config_get_path('aliases/alias', []);
6730
	$aliases_rename = [];
6731
	$rename_suffix = '__RENAMED';
6732
	$reserved_suffix = '__NETWORK';
6733
	$interfaces = array_merge(array_keys(config_get_path('interfaces', [])),
6734
	                          array_column(config_get_path('ifgroups/ifgroupentry', []), 'ifname'));
6735
	$interfaces = array_map('strtoupper', $interfaces);
6736
	foreach ($aliases as & $alias) {
6737
		// varify that a name exists; alias names cannot start with a number
6738
		if (empty($alias['name'])) {
6739
			continue;
6740
		}
6741

    
6742
		// check if the alias could conflict
6743
		if ($alias['name'] == $reserved_suffix || !str_ends_with($alias['name'], $reserved_suffix)) {
6744
			continue;
6745
		}
6746

    
6747
		// check if the alias would conflict with an interface name
6748
		if (!in_array(stristr($alias['name'], $reserved_suffix, true), $interfaces)) {
6749
			continue;
6750
		}
6751

    
6752
		// alias conflicts, attempt to rename it and flag it for references update
6753
		if (in_array($alias['name'] . $rename_suffix, array_column($aliases, 'name'))) {
6754
			file_notice('Alias', gettext('The following alias conflicts with a reserved keyword and must' .
6755
			            ' be manually renamed: ' . $alias['name']));
6756
		} else {
6757
			$aliases_rename[] = $alias['name'];
6758
			$alias['name'] .= $rename_suffix;
6759
		}
6760
	}
6761
	if (isset($alias)) {
6762
		unset($alias);
6763
	}
6764
	if (!empty($aliases_rename)) {
6765
		// commit alias changes
6766
		config_set_path('aliases/alias', $aliases);
6767
		// update alias references
6768
		foreach ($aliases_rename as $conflicting_name) {
6769
			update_alias_name($conflicting_name . $rename_suffix, $conflicting_name);
6770
		}
6771
		file_notice('Alias', gettext('The following aliases conflict with a reserved keyword and have been renamed: ') .
6772
		            implode(', ', $aliases_rename));
6773
	}
6774
}
6775

    
6776
/*
6777
 * Check OpenVPN instances for deprecated algorithms and weak certificate
6778
 * digests.
6779
 * https://redmine.pfsense.org/issues/14677
6780
 * https://redmine.pfsense.org/issues/14686
6781
 */
6782
function upgrade_230_to_231() {
6783
	/* Load lists of current usable algorithms */
6784
	$cipher_validation_list = array_keys(openvpn_get_cipherlist());
6785
	$digest_validation_list = array_keys(openvpn_get_digestlist());
6786
	$changed = false;
6787
	$disabled = false;
6788
	foreach(array('server', 'client') as $mode) {
6789
		foreach (config_get_path("openvpn/openvpn-{$mode}", []) as $idx => $settings) {
6790
			$thischanged = false;
6791
			$thisdisabled = false;
6792
			/* Check data_ciphers and filter out any deprecated items */
6793
			if (!empty($settings['data_ciphers'])) {
6794
				$dc = explode(',', $settings['data_ciphers']);
6795
				/* Retain valid entries only, in the original order */
6796
				$dc = array_intersect($dc, $cipher_validation_list);
6797
				$dc = implode(',', $dc);
6798
				if ($settings['data_ciphers'] != $dc) {
6799
					$settings['data_ciphers'] = $dc;
6800
					$thischanged = true;
6801
				}
6802
			}
6803
			/* If no supported ciphers remain, replace with default set. */
6804
			if (empty($settings['data_ciphers'])) {
6805
				$settings['data_ciphers'] = 'AES-256-GCM,AES-128-GCM,CHACHA20-POLY1305';
6806
				$thischanged = true;
6807
			}
6808

    
6809
			/* Check data_ciphers_fallback and if it's deprecated, replace with 'AES-256-CBC' */
6810
			if (!in_array($settings['data_ciphers_fallback'], $cipher_validation_list)) {
6811
				$settings['data_ciphers_fallback'] = 'AES-256-CBC';
6812
				$thischanged = true;
6813
			}
6814

    
6815
			/* Check digest and if it's deprecated, replace with 'SHA256' */
6816
			if (!empty($settings['digest']) &&
6817
			    !in_array($settings['digest'], $digest_validation_list)) {
6818
				$settings['digest'] = 'SHA256';
6819
				$thischanged = true;
6820
			}
6821

    
6822
			/* If using SSL/TLS, check if (server|client) certificate is weak, if so, disable tunnel */
6823
			if (!empty($settings['certref'])) {
6824
				$cert = lookup_cert($settings['certref']);
6825
				$cert = $cert['item'];
6826
				/* Disable only if weak and not already disabled */
6827
				if (cert_has_weak_digest($cert['crt']) &&
6828
					!isset($settings['disable'])) {
6829
					/* Weak digest, disable tunnel. */
6830
					$settings['disable'] = true;
6831
					$thisdisabled = true;
6832
				}
6833
			}
6834

    
6835
			/* If any changes were made, alert user (clarify changed vs disabled). */
6836
			if ($thisdisabled) {
6837
				$disabled = true;
6838
			}
6839
			if ($thischanged) {
6840
				$changed = true;
6841
			}
6842

    
6843
			/* Save changes (if any were made) */
6844
			if ($thisdisabled || $thischanged) {
6845
				config_set_path("openvpn/openvpn-{$mode}/{$idx}", $settings);
6846
			}
6847
		}
6848
	}
6849
	if ($changed) {
6850
		file_notice("OpenVPN", gettext("One or more OpenVPN entries used deprecated algorithms and has been updated to secure defaults."));
6851
	}
6852
	if ($disabled) {
6853
		file_notice("OpenVPN", gettext("One or more OpenVPN entries has been disabled because it used a certificate with a deprecated weak digest algorithm."));
6854
	}
6855
}
6856

    
6857
/*
6858
 * Check GUI and Captive Portal zones for certs with weak digests
6859
 * https://redmine.pfsense.org/issues/14672
6860
 */
6861
function upgrade_231_to_232() {
6862
	/* Check GUI if it is set for HTTPS */
6863
	if (config_get_path('system/webgui/protocol') == "https" &&
6864
	    !empty(config_get_path('system/webgui/ssl-certref'))) {
6865
		$cert = lookup_cert(config_get_path('system/webgui/ssl-certref'));
6866
		$cert = $cert['item'];
6867
		/* If the GUI certificate is invalid or weak, replace it */
6868
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv'] ||
6869
		    cert_chain_has_weak_digest($cert)) {
6870
			$cert = cert_create_selfsigned('', '', false);
6871
			if (is_array($cert) && !empty($cert)) {
6872
				config_set_path('system/webgui/ssl-certref', $cert['refid']);
6873
				file_notice("GUI", gettext("The GUI HTTPS certificate used a deprecated algorithm and has been replaced with a secure default."));
6874
			}
6875
		}
6876
	}
6877

    
6878
	/* Check each portal zone */
6879
	foreach (config_get_path('captiveportal', []) as $zone => $portal) {
6880
		/* Only act if the portal is enabled and using HTTPS login */
6881
		if (!isset($portal['enable']) ||
6882
		    !isset($portal['httpslogin'])||
6883
		    empty($portal['certref'])) {
6884
			continue;
6885
		}
6886

    
6887
		$cert = lookup_cert($portal['certref']);
6888
		$cert = $cert['item'];
6889

    
6890
		/* If the cert is invalid or weak, generate a new self-signed
6891
		 * cert using configured HTTPS server name, if present */
6892
		if (!is_array($cert) ||
6893
		    !$cert['crt'] ||
6894
		    !$cert['prv'] ||
6895
		    cert_chain_has_weak_digest($cert)) {
6896

    
6897
			if (!empty($portal['httpsname']) &&
6898
			    (is_hostname($portal['httpsname']) ||
6899
			    is_fqdn($portal['httpsname']))) {
6900
				$hostname = $portal['httpsname'];
6901
			} else {
6902
				$hostname = '';
6903
			}
6904
			$cert = cert_create_selfsigned("Captive Portal Zone {$zone}", $hostname, false);
6905
			if (is_array($cert) && !empty($cert)) {
6906
				config_set_path("captiveportal/{$zone}/certref", $cert['refid']);
6907

    
6908
				file_notice("Captive Portal",
6909
					sprintf(gettext("The HTTPS certificate for Captive Portal Zone %s used ".
6910
							"a deprecated algorithm and has been replaced with a secure default."), $zone));
6911
			}
6912
		}
6913
	}
6914
}
6915

    
6916
/* Update language internal IDs to match OS Locales where possible
6917
 * Some languages do not have direct equivalents.
6918
 * https://redmine.pfsense.org/issues/13776 */
6919
function upgrade_232_to_233() {
6920
	$lang_changes= [
6921
		"nl" => "nl_NL",
6922
		"fr" => "fr_FR",
6923
		"it" => "it_IT",
6924
		"ko" => "ko_KR",
6925
		"nb" => "nb_NO",
6926
		"pl" => "pl_PL",
6927
		"ru" => "ru_RU",
6928
		"es" => "es_ES",
6929
	];
6930
	$curlang = config_get_path('system/language');
6931

    
6932
	/* If the language is set and is one in our list of languages to rename,
6933
	 * then update the language appropriately. */
6934
	if (!empty($curlang) &&
6935
	    array_key_exists($curlang, $lang_changes)) {
6936
		config_set_path('system/language', $lang_changes[$curlang]);
6937
	}
6938
}
6939

    
6940
/* OpenVPN Client-Specific Override options have changed.
6941
 * https://redmine.pfsense.org/issues/12522 */
6942
 function upgrade_233_to_234() {
6943
	$openvpn_csc_config = config_get_path('openvpn/openvpn-csc', []);
6944
	if (empty($openvpn_csc_config)) {
6945
		return;
6946
	}
6947
	foreach ($openvpn_csc_config as &$settings) {
6948
		if (!is_array($settings)) {
6949
			continue;
6950
		}
6951

    
6952
		// Migrate "remove_route"
6953
		if (isset($settings['remove_route'])) {
6954
			$settings['remove_options'] = 'remove_route';
6955
			unset($settings['remove_route']);
6956
		}
6957
	}
6958
	config_set_path('openvpn/openvpn-csc', $openvpn_csc_config);
6959
}
6960

    
6961
/*
6962
 * Special function that is called independent of current config version. It's
6963
 * a workaround to have config_upgrade running on older versions after next
6964
 * config version was already taken by newer pfSense.
6965
 *
6966
 * XXX Change the way we handle config version to make it based on product
6967
 *     version
6968
 */
6969
function additional_config_upgrade() {
6970
}
6971

    
6972
?>
(53-53/61)