Project

General

Profile

Download (199 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-2022 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

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

    
44
	/* convert DMZ to optional, if necessary */
45
	if (isset($config['interfaces']['dmz'])) {
46

    
47
		$dmzcfg = &$config['interfaces']['dmz'];
48

    
49
		if ($dmzcfg['if']) {
50
			$config['interfaces']['opt' . $opti] = array();
51
			$optcfg = &$config['interfaces']['opt' . $opti];
52

    
53
			$optcfg['enable'] = $dmzcfg['enable'];
54
			$optcfg['descr'] = "DMZ";
55
			$optcfg['if'] = $dmzcfg['if'];
56
			$optcfg['ipaddr'] = $dmzcfg['ipaddr'];
57
			$optcfg['subnet'] = $dmzcfg['subnet'];
58

    
59
			$ifmap['dmz'] = "opt" . $opti;
60
			$opti++;
61
		}
62

    
63
		config_del_path('interfaces/dmz');
64
	}
65

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

    
69
		if (!$config['interfaces']['wlan' . $i]['if']) {
70
			config_del_path("interfaces/wlan{$i}");
71
			continue;
72
		}
73

    
74
		$wlancfg = &$config['interfaces']['wlan' . $i];
75
		$config['interfaces']['opt' . $opti] = array();
76
		$optcfg = &$config['interfaces']['opt' . $opti];
77

    
78
		$optcfg['enable'] = $wlancfg['enable'];
79
		$optcfg['descr'] = "WLAN" . $i;
80
		$optcfg['if'] = $wlancfg['if'];
81
		$optcfg['ipaddr'] = $wlancfg['ipaddr'];
82
		$optcfg['subnet'] = $wlancfg['subnet'];
83
		$optcfg['bridge'] = $wlancfg['bridge'];
84

    
85
		$optcfg['wireless'] = array();
86
		$optcfg['wireless']['mode'] = $wlancfg['mode'];
87
		$optcfg['wireless']['ssid'] = $wlancfg['ssid'];
88
		$optcfg['wireless']['channel'] = $wlancfg['channel'];
89
		$optcfg['wireless']['wep'] = $wlancfg['wep'];
90

    
91
		$ifmap['wlan' . $i] = "opt" . $opti;
92

    
93
		config_del_path("interfaces/wlan{$i}");
94
		$opti++;
95
	}
96

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

    
102
		$fr = &$config['filter']['rule'][$i];
103

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

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

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

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

    
148
			$fr = &$config['pfqueueing']['rule'][$i];
149

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

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

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

    
190

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

    
198
	/* encrypt password */
199
	$config['system']['password'] = crypt($config['system']['password']);
200
}
201

    
202

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

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

    
221

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

    
229
		for ($i = 0; isset($config['pfqueueing']['rule'][$i]); $i++) {
230
			$curent = &$config['pfqueueing']['rule'][$i];
231

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

    
240
			$curent['targetpipe'] = $i;
241

    
242
			unset($curent['bandwidth']);
243
			unset($curent['delay']);
244
			unset($curent['mask']);
245
		}
246
	}
247
}
248

    
249

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

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

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

    
275

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

    
293

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

    
318

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

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

    
374

    
375
function upgrade_018_to_019() {
376
	global $config;
377
}
378

    
379

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

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

    
403

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

    
410
function upgrade_022_to_023() {
411
	global $config;
412
	if (isset($config['shaper'])) {
413
		config_del_path('shaper');
414
	}
415
}
416

    
417

    
418
function upgrade_023_to_024() {
419
	global $config;
420
}
421

    
422

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

    
431

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

    
443
	$config['cron']['item'][] = $cron_item;
444

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

    
454
	$config['cron']['item'][] = $cron_item;
455

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

    
465
	$config['cron']['item'][] = $cron_item;
466

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

    
476
	$config['cron']['item'][] = $cron_item;
477

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

    
487
	$config['cron']['item'][] = $cron_item;
488

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

    
498
	$config['cron']['item'][] = $cron_item;
499

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

    
509
	$config['cron']['item'][] = $cron_item;
510
}
511

    
512

    
513
function upgrade_026_to_027() {
514
	global $config;
515
}
516

    
517

    
518
function upgrade_027_to_028() {
519
	global $config;
520
}
521

    
522

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

    
537

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

    
544

    
545
function upgrade_030_to_031() {
546
	global $config;
547
	/* Insert upgrade code here */
548
}
549

    
550

    
551
function upgrade_031_to_032() {
552
	global $config;
553
	/* Insert upgrade code here */
554
}
555

    
556

    
557
function upgrade_032_to_033() {
558
	global $config;
559
	/* Insert upgrade code here */
560
}
561

    
562

    
563
function upgrade_033_to_034() {
564
	global $config;
565
	/* Insert upgrade code here */
566
}
567

    
568

    
569
function upgrade_034_to_035() {
570
	global $config;
571
	/* Insert upgrade code here */
572
}
573

    
574

    
575
function upgrade_035_to_036() {
576
	global $config;
577
	/* Insert upgrade code here */
578
}
579

    
580

    
581
function upgrade_036_to_037() {
582
	global $config;
583
	/* Insert upgrade code here */
584
}
585

    
586

    
587
function upgrade_037_to_038() {
588
	global $config;
589
	/* Insert upgrade code here */
590
}
591

    
592

    
593
function upgrade_038_to_039() {
594
	global $config;
595
	/* Insert upgrade code here */
596
}
597

    
598

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

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

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

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

    
640
		$config['system']['nextuid'] = "111";
641
		$config['system']['nextgid'] = "111";
642

    
643
		config_del_path('system/username');
644
		if (isset($config['system']['password'])) {
645
			config_del_path('system/password');
646
		}
647
	}
648
}
649

    
650
function upgrade_040_to_041() {
651
	global $config;
652
	if (!$config['sysctl']) {
653
		$config['sysctl']['item'] = array();
654

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
735
	}
736
}
737

    
738

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

    
749

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

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

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

    
803

    
804
function upgrade_043_to_044() {
805
	global $config;
806

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

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

    
845

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

    
866

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

    
950

    
951
function upgrade_046_to_047() {
952
	global $config;
953
	/* Upgrade IPsec from tunnel to phase1/phase2 */
954

    
955
	if (is_array($config['ipsec']['tunnel'])) {
956

    
957
		$a_phase1 = array();
958
		$a_phase2 = array();
959
		$ikeid = 0;
960

    
961
		foreach ($config['ipsec']['tunnel'] as $tunnel) {
962

    
963
			unset($ph1ent);
964
			unset($ph2ent);
965

    
966
			/*
967
				*  attempt to locate an enabled phase1
968
				*  entry that matches the peer gateway
969
				*/
970

    
971
			if (!isset($tunnel['disabled'])) {
972

    
973
				$remote_gateway = $tunnel['remote-gateway'];
974

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

    
983
			/* none found, create a new one */
984

    
985
			if (!isset($ph1ent)) {
986

    
987
				/* build new phase1 entry */
988

    
989
				$ph1ent = array();
990

    
991
				$ph1ent['ikeid'] = ++$ikeid;
992

    
993
				if (isset($tunnel['disabled'])) {
994
					$ph1ent['disabled'] = $tunnel['disabled'];
995
				}
996

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

    
1006
				$ph1ent['mode'] = $tunnel['p1']['mode'];
1007

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

    
1032
				$ph1ent['peerid_type'] = "peeraddress";
1033

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

    
1056
				$ph1ent['encryption-algorithm'] = $ph1alg;
1057
				$ph1ent['hash-algorithm'] = $tunnel['p1']['hash-algorithm'];
1058
				$ph1ent['dhgroup'] = $tunnel['p1']['dhgroup'];
1059
				$ph1ent['lifetime'] = $tunnel['p1']['lifetime'];
1060
				$ph1ent['authentication_method'] = $tunnel['p1']['authentication_method'];
1061

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

    
1075
				$ph1ent['nat_traversal'] = "on";
1076
				$ph1ent['dpd_enable'] = 1;
1077
				$ph1ent['dpd_delay'] = 10;
1078
				$ph1ent['dpd_maxfail'] = 5;
1079

    
1080
				$a_phase1[] = $ph1ent;
1081
			}
1082

    
1083
			/* build new phase2 entry */
1084

    
1085
			$ph2ent = array();
1086

    
1087
			$ph2ent['ikeid'] = $ph1ent['ikeid'];
1088

    
1089
			if (isset($tunnel['disabled'])) {
1090
				$ph1ent['disabled'] = $tunnel['disabled'];
1091
			}
1092

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

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

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

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

    
1123
			$ph2ent['protocol'] = $tunnel['p2']['protocol'];
1124

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

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

    
1155
			$ph2ent['hash-algorithm-option'] = $tunnel['p2']['hash-algorithm-option'];
1156
			$ph2ent['pfsgroup'] = $tunnel['p2']['pfsgroup'];
1157
			$ph2ent['lifetime'] = $tunnel['p2']['lifetime'];
1158

    
1159
			if (isset($tunnel['pinghost']['pinghost'])) {
1160
				$ph2ent['pinghost'] = $tunnel['pinghost'];
1161
			}
1162

    
1163
			$a_phase2[] = $ph2ent;
1164
		}
1165

    
1166
		config_del_path('ipsec/tunnel');
1167
		$config['ipsec']['phase1'] = $a_phase1;
1168
		$config['ipsec']['phase2'] = $a_phase2;
1169
	}
1170

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

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

    
1183
		$mobilecfg = config_get_path('ipsec/mobileclients');
1184

    
1185
		$ph1ent = array();
1186
		$ph1ent['ikeid'] = ++$ikeid;
1187

    
1188
		if (!isset($mobilecfg['enable'])) {
1189
			$ph1ent['disabled'] = true;
1190
		}
1191

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

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

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

    
1245
		$ph1ent['encryption-algorithm'] = $ph1alg;
1246
		$ph1ent['hash-algorithm'] = $mobilecfg['p1']['hash-algorithm'];
1247
		$ph1ent['dhgroup'] = $mobilecfg['p1']['dhgroup'];
1248
		$ph1ent['lifetime'] = $mobilecfg['p1']['lifetime'];
1249
		$ph1ent['authentication_method'] = $mobilecfg['p1']['authentication_method'];
1250

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

    
1261
		$ph1ent['nat_traversal'] = "on";
1262
		$ph1ent['dpd_enable'] = 1;
1263
		$ph1ent['dpd_delay'] = 10;
1264
		$ph1ent['dpd_maxfail'] = 5;
1265
		$ph1ent['mobile'] = true;
1266

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

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

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

    
1308
		$config['ipsec']['phase1'][] = $ph1ent;
1309
		$config['ipsec']['phase2'][] = $ph2ent;
1310
		config_del_path('ipsec/mobileclients');
1311
	}
1312
}
1313

    
1314

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

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

    
1378

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

    
1389
	if (!is_array($config['system']['user'])) {
1390
		$config['system']['user'] = array();
1391
	}
1392
	if (!is_array($config['system']['group'])) {
1393
		$config['system']['group'] = array();
1394
	}
1395

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

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

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

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

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

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

    
1446

    
1447
function upgrade_049_to_050() {
1448
	global $config;
1449

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

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

    
1490
	/* sync all local account information */
1491
	local_reset_accounts();
1492
}
1493

    
1494

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

    
1508
	if (isset($config['bridge'])) {
1509
		config_del_path('bridge');
1510
	}
1511

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

    
1537

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

    
1548
	$vpnid = 1;
1549

    
1550
	/* openvpn server configurations */
1551
	if (is_array($config['installedpackages']['openvpnserver'])) {
1552
		$config['openvpn']['openvpn-server'] = array();
1553

    
1554
		$index = 1;
1555
		foreach ($config['installedpackages']['openvpnserver']['config'] as $server) {
1556

    
1557
			if (!is_array($server)) {
1558
				continue;
1559
			}
1560

    
1561
			if ($server['auth_method'] == "pki") {
1562

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

    
1570
				/* create ca reference */
1571
				unset($server['ca_cert']);
1572
				$server['caref'] = $ca['refid'];
1573

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

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

    
1597
				/* create cert reference */
1598
				unset($server['server_cert']);
1599
				unset($server['server_key']);
1600
				$server['certref'] = $cert['refid'];
1601

    
1602
				$index++;
1603
			}
1604

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

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

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

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

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

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

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

    
1681
			if (!empty($server['disable'])) {
1682
				$server['disable'] = true;
1683
			} else {
1684
				unset($server['disable']);
1685
			}
1686

    
1687
			/* allocate vpnid */
1688
			$server['vpnid'] = $vpnid++;
1689

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

    
1718
			$config['openvpn']['openvpn-server'][] = $server;
1719
		}
1720
		config_del_path('installedpackages/openvpnserver');
1721
	}
1722

    
1723
	/* openvpn client configurations */
1724
	if (is_array($config['installedpackages']['openvpnclient'])) {
1725
		$config['openvpn']['openvpn-client'] = array();
1726

    
1727
		$index = 1;
1728
		foreach ($config['installedpackages']['openvpnclient']['config'] as $client) {
1729

    
1730
			if (!is_array($client)) {
1731
				continue;
1732
			}
1733

    
1734
			if ($client['auth_method'] == "pki") {
1735

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

    
1744
				/* create ca reference */
1745
				unset($client['ca_cert']);
1746
				unset($client['crl']);
1747
				$client['caref'] = $ca['refid'];
1748

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

    
1757
				/* create cert reference */
1758
				unset($client['client_cert']);
1759
				unset($client['client_key']);
1760
				$client['certref'] = $cert['refid'];
1761

    
1762
				$index++;
1763
			}
1764

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

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

    
1792
			/* allocate vpnid */
1793
			$client['vpnid'] = $vpnid++;
1794

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

    
1823
			if (!empty($client['disable'])) {
1824
				$client['disable'] = true;
1825
			} else {
1826
				unset($client['disable']);
1827
			}
1828

    
1829
			$config['openvpn']['openvpn-client'][] = $client;
1830
		}
1831

    
1832
		config_del_path('installedpackages/openvpnclient');
1833
	}
1834

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

    
1839
		foreach ($config['installedpackages']['openvpncsc']['config'] as $csc) {
1840

    
1841
			if (!is_array($csc)) {
1842
				continue;
1843
			}
1844

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

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

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

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

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

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

    
1896
			if (!empty($csc['disable'])) {
1897
				$csc['disable'] = true;
1898
			} else {
1899
				unset($csc['disable']);
1900
			}
1901

    
1902
			$config['openvpn']['openvpn-csc'][] = $csc;
1903
		}
1904

    
1905
		config_del_path('installedpackages/openvpncsc');
1906
	}
1907

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

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

    
1933
}
1934

    
1935

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

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

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

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

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

    
1970

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

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

    
2057

    
2058
function upgrade_054_to_055() {
2059
	global $config;
2060
	global $g;
2061

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

    
2068
	$rrddbpath = "/var/db/rrd/";
2069
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2070

    
2071
	$rrdinterval = 60;
2072
	$valid = $rrdinterval * 2;
2073

    
2074
	/* Assume GigE for now */
2075
	$downstream = 125000000;
2076
	$upstream = 125000000;
2077

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

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

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

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

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

    
2121
		unset($rrdold);
2122
		@unlink("{$g['tmp_path']}/{$xmldump}");
2123
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2124
	}
2125

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

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

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

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

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

    
2160
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2161
		$rrdold = $rrdold['rrd'];
2162

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

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

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

    
2199

    
2200
function upgrade_055_to_056() {
2201
	global $config;
2202

    
2203
	if (!is_array($config['ca'])) {
2204
		$config['ca'] = array();
2205
	}
2206
	if (!is_array($config['cert'])) {
2207
		$config['cert'] = array();
2208
	}
2209

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

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

    
2253

    
2254
function upgrade_056_to_057() {
2255
	global $config;
2256

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

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

    
2300
function upgrade_058_to_059() {
2301
	global $config;
2302

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

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

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

    
2342
function upgrade_060_to_061() {
2343
	global $config;
2344

    
2345
	if (is_array($config['interfaces']['wan'])) {
2346
		$config['interfaces']['wan']['enable'] = true;
2347
	}
2348
	if (is_array($config['interfaces']['lan'])) {
2349
		$config['interfaces']['lan']['enable'] = true;
2350
	}
2351

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

    
2364
function upgrade_061_to_062() {
2365
	global $config;
2366

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

    
2371
		foreach ($a_nat as &$natent) {
2372
			$natent['disabled'] = false;
2373
			$natent['nordr']    = false;
2374

    
2375
			$natent['source'] = array(
2376
				"not"     => false,
2377
				"any"     => true,
2378
				"port"    => ""
2379
			);
2380

    
2381
			$natent['destination'] = array(
2382
				"not"     => false,
2383
				"address" => $natent['external-address'],
2384
				"port"    => $natent['external-port']
2385
			);
2386

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

    
2395
			unset($natent['external-address']);
2396
			unset($natent['external-port']);
2397
		}
2398

    
2399
		unset($natent);
2400
	}
2401
}
2402

    
2403
function upgrade_062_to_063() {
2404
	/* Upgrade legacy Themes to the new pfsense_ng */
2405
	// Not supported in 2.3+
2406

    
2407
}
2408

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

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

    
2434
	$a_ppps = &$config['ppps']['ppp'];
2435

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

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

    
2486
			$ifcfg[$ifname]['if'] = $ifinfo['ipaddr'].$j;
2487
			$j++;
2488

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

    
2503
			$a_ppps[] = $ppp;
2504

    
2505
		}
2506
	}
2507
}
2508

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

    
2516
function upgrade_065_to_066() {
2517
	global $config;
2518

    
2519
	init_config_arr(array('dhcrelay'));
2520
	$dhcrelaycfg = &$config['dhcrelay'];
2521

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

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

    
2551
function upgrade_067_to_068() {
2552
	global $config;
2553

    
2554
	if (!empty($config['pppoe'])) {
2555
		$config['pppoes'] = array();
2556
		$config['pppoes']['pppoe'] = array();
2557
		$config['pppoes']['pppoe'][] = config_get_path('pppoe/0');
2558

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

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

    
2604
function upgrade_069_to_070() {
2605
	global $config;
2606

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

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

    
2618
			config_del_path("nat/onetoone/{$nidx}/internal");
2619
			config_del_path("nat/onetoone/{$nidx}/subnet");
2620
		}
2621

    
2622
		unset($natent);
2623
	}
2624
}
2625

    
2626
function upgrade_070_to_071() {
2627
	global $config;
2628

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

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

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

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

    
2681
function upgrade_073_to_074() {
2682
	global $config;
2683
	rename_field($config['system']['user'], 'fullname', 'descr');
2684
}
2685

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

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

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

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

    
2749
function upgrade_079_to_080() {
2750
	global $config;
2751

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

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

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

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

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

    
2782
	$rrdinterval = 60;
2783
	$valid = $rrdinterval * 2;
2784

    
2785
	/* Assume GigE for now */
2786
	$downstream = 125000000;
2787
	$upstream = 125000000;
2788

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

    
2796
		if (platform_booting()) {
2797
			echo "Migrate RRD database {$database} to new format for IPv6.\n";
2798
		}
2799

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

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

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

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

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

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

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

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

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

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

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

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

    
2975
function upgrade_084_to_085() {
2976
	global $config;
2977

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

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

    
3021
function upgrade_085_to_086() {
3022
	global $config, $g;
3023

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

    
3040
function upgrade_086_to_087() {
3041
	global $config, $dummynet_pipe_list;
3042

    
3043
	if (!is_array($config['dnshaper']) || !is_array($config['dnshaper']['queue'])) {
3044
		return;
3045
	}
3046

    
3047
	$dnqueue_number = 1;
3048
	$dnpipe_number = 1;
3049

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

    
3061
	unset($dnqueue_number, $dnpipe_number, $qidx, $idx, $dnpipe, $dnqueue);
3062

    
3063
	if (!is_array($config['filter']) || !is_array($config['filter']['rule'])) {
3064
		return;
3065
	}
3066

    
3067
	require_once("shaper.inc");
3068
	read_dummynet_config();
3069

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

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

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

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

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

    
3130
					/* add ca reference to certificate */
3131
					$cert['caref'] = $ca['refid'];
3132
				}
3133

    
3134
				$config['cert'][] = $cert;
3135

    
3136
				/* create cert reference */
3137
				$setting['certref'] = $cert['refid'];
3138

    
3139
				unset($setting['certificate']);
3140
				unset($setting['private-key']);
3141
				unset($setting['cacertificate']);
3142

    
3143
			}
3144
		}
3145
	}
3146
}
3147

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

    
3164
function upgrade_090_to_091() {
3165
	global $config;
3166

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

    
3182
function upgrade_091_to_092() {
3183
	global $config;
3184

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

    
3195
function upgrade_092_to_093() {
3196
	global $g;
3197

    
3198
	$suffixes = array("concurrent", "loggedin");
3199

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

    
3207
	if (!platform_booting()) {
3208
		enable_rrd_graphing();
3209
	}
3210
}
3211

    
3212
function upgrade_093_to_094() {
3213
	global $config;
3214

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

    
3222
function upgrade_094_to_095() {
3223
	global $config;
3224

    
3225
	if (!isset($config['interfaces']) || !is_array($config['interfaces'])) {
3226
		return;
3227
	}
3228

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

    
3238
function upgrade_095_to_096() {
3239
	global $config, $g;
3240

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

    
3246
	/* Assume 2*10GigE for now */
3247
	$stream = 2500000000;
3248

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

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

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

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

    
3281
function upgrade_097_to_098() {
3282
	// no longer used (used to set kill_states)
3283
	return;
3284
}
3285

    
3286
function upgrade_098_to_099() {
3287
	global $config;
3288

    
3289
	if (empty($config['dhcpd']) || !is_array($config['dhcpd'])) {
3290
		return;
3291
	}
3292

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

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

    
3307
function upgrade_100_to_101() {
3308
	global $config, $g;
3309

    
3310
	if (!is_array($config['voucher'])) {
3311
		return;
3312
	}
3313

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

    
3326
function upgrade_101_to_102() {
3327
	global $config, $g;
3328

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

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

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

    
3361
function upgrade_102_to_103() {
3362
	global $config;
3363

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

    
3371
	$config['nat']['outbound'] = config_get_path('nat/advancedoutbound');
3372

    
3373
	if (isset($config['nat']['ipsecpassthru'])) {
3374
		config_del_path('nat/ipsecpassthru');
3375
	}
3376
	if (isset($config['nat']['advancedoutbound'])) {
3377
		config_del_path('nat/advancedoutbound');
3378
	}
3379
}
3380

    
3381
function upgrade_103_to_104() {
3382
	global $config;
3383

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

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

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

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

    
3419
function upgrade_104_to_105() {
3420
	global $config;
3421

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

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

    
3441
function upgrade_106_to_107() {
3442
	global $config;
3443

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

    
3466
function upgrade_107_to_108() {
3467
	global $config;
3468

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

    
3476
function upgrade_108_to_109() {
3477
	global $config;
3478

    
3479
	if (!isset($config['filter']['rule']) || !is_array($config['filter']['rule'])) {
3480
		return;
3481
	}
3482

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

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

    
3496
function upgrade_109_to_110() {
3497
	global $config;
3498

    
3499
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3500
		return;
3501
	}
3502

    
3503
	foreach ($config['ipsec']['phase2'] as &$rule) {
3504
		if (!empty($rule['uniqid'])) {
3505
			continue;
3506
		}
3507

    
3508
		$rule['uniqid'] = uniqid();
3509
	}
3510
}
3511

    
3512
function upgrade_110_to_111() {
3513
	global $config;
3514

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

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

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

    
3535
			config_del_path("installedpackages/menu/{$idx}");
3536
			break;
3537
		}
3538
	}
3539

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

    
3550
	if (!isset($config['installedpackages']['unbound']['config'][0])) {
3551
		return;
3552
	}
3553

    
3554
	$pkg = config_get_path('installedpackages/unbound/config/0');
3555

    
3556
	if (isset($config['installedpackages']['unboundadvanced']['config'][0])) {
3557
		$pkg = array_merge($pkg, $config['installedpackages']['unboundadvanced']['config'][0]);
3558
	}
3559

    
3560
	$new = array();
3561

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

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

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

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

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

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

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

    
3637
	$config['unbound'] = $new;
3638

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

    
3649
	unset($pkg, $new);
3650
}
3651

    
3652
function upgrade_111_to_112() {
3653
	global $config;
3654

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

    
3666
function upgrade_112_to_113() {
3667
	global $config;
3668

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

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

    
3686
function upgrade_113_to_114() {
3687
	global $config;
3688

    
3689
	if (!isset($config['ipsec']['phase1']) ||
3690
	    !is_array($config['ipsec']['phase1'])) {
3691
		return;
3692
	}
3693

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

    
3701
function upgrade_114_to_115() {
3702
	global $config;
3703

    
3704
	if (isset($config['unbound']['custom_options'])) {
3705
		$config['unbound']['custom_options'] = base64_encode($config['unbound']['custom_options']);
3706
	}
3707
}
3708

    
3709
function upgrade_115_to_116() {
3710
	global $config;
3711

    
3712
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3713
		return;
3714
	}
3715

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

    
3723
function upgrade_116_to_117() {
3724
	global $config;
3725

    
3726
	if (!isset($config['ipsec']['client']) ||
3727
	    !isset($config['ipsec']['client']['dns_split']) ||
3728
	    empty($config['ipsec']['client']['dns_split'])) {
3729
		return;
3730
	}
3731

    
3732
	$config['ipsec']['client']['dns_split'] =
3733
		preg_replace('/\s*,\s*/', ' ', trim($config['ipsec']['client']['dns_split']));
3734

    
3735
}
3736

    
3737
function upgrade_117_to_118() {
3738
	global $config;
3739

    
3740
	// 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.
3741
	if (isset($config['system']['ca'])) {
3742
		config_del_path('system/ca');
3743
	}
3744
	if (isset($config['system']['cert'])) {
3745
		config_del_path('system/cert');
3746
	}
3747

    
3748
	init_config_arr(array('ipsec', 'phase1'));
3749
	$a_phase1 = &$config['ipsec']['phase1'];
3750

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

    
3764
function upgrade_118_to_119() {
3765
	global $config;
3766

    
3767
	if (!isset($config['ipsec']['phase1'])) {
3768
		return;
3769
	}
3770

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

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

    
3782
function upgrade_119_to_120() {
3783
	require_once("ipsec.inc");
3784
	global $config, $ipsec_log_cats;
3785

    
3786
	if (!is_array($config['ipsec'])) {
3787
		return;
3788
	}
3789

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

    
3797
}
3798

    
3799

    
3800
function upgrade_120_to_121() {
3801
	global $config;
3802

    
3803
	if (!isset($config['installedpackages']['miniupnpd']['config'][0])) {
3804
		return;
3805
	}
3806

    
3807
	$miniupnpd = &$config['installedpackages']['miniupnpd']['config'][0];
3808

    
3809
	$miniupnpd['row'] = array();
3810

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

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

    
3828
function upgrade_122_to_123() {
3829
	global $config;
3830

    
3831
	// PPTP server was removed
3832
	if (isset($config['pptpd'])) {
3833
		config_del_path('pptpd');
3834
	}
3835

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

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

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

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

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

    
3926
function upgrade_123_to_124() {
3927
	if (isset($config['system']['altpkgrepo'])) {
3928
		config_del_path('system/altpkgrepo');
3929
	}
3930

    
3931
	if (isset($config['theme'])) {
3932
		config_del_path('theme');
3933
	}
3934
}
3935

    
3936
function upgrade_124_to_125() {
3937
	global $config;
3938

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

    
3945
		/* Generate a notice, disable interface, remove WEP settings */
3946
		if (isset($intf['wireless']['wep']['enable'])) {
3947
			if (!function_exists("file_notice")) {
3948
				require_once("notices.inc");
3949
			}
3950
			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));
3951
			config_del_path("interfaces/{$ifname}/wireless/wep");
3952
			if (isset($intf['enable'])) {
3953
				config_del_path("interfaces/{$ifname}/enable");
3954
			}
3955
		}
3956
	}
3957
}
3958

    
3959
function upgrade_125_to_126() {
3960
	require_once("ipsec.inc");
3961
	global $config, $ipsec_log_cats, $ipsec_log_sevs;
3962

    
3963
	$def_loglevel = 1;
3964
	if (!is_array($config['ipsec'])) {
3965
		return;
3966
	}
3967

    
3968
	if (!isset($config['ipsec']['logging']) || !is_array($config['ipsec']['logging'])) {
3969
		$config['ipsec']['logging'] = array();
3970
	}
3971

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

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

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

    
3999
	if (!isset($config['widgets']['sequence'])) {
4000
		return;
4001
	}
4002

    
4003
	$cur_widgets = explode(',', trim($config['widgets']['sequence']));
4004
	$new_widgets = array();
4005

    
4006
	foreach ($cur_widgets as $widget) {
4007
		list($file, $col, $display) = explode(':', $widget);
4008

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

    
4022
		/* Remove '-container' from widget name */
4023
		$file = preg_replace('/-container$/', '', $file);
4024

    
4025
		$new_widgets[] = "{$file}:{$col}:{$display}";
4026
	}
4027

    
4028
	$config['widgets']['sequence'] = implode(',', $new_widgets);
4029

    
4030
}
4031

    
4032
function upgrade_127_to_128() {
4033
	global $config;
4034

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

    
4044
function upgrade_128_to_129() {
4045
	global $config;
4046

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

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

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

    
4076
function upgrade_129_to_130() {
4077
	global $config;
4078

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

    
4092
function upgrade_130_to_131() {
4093
	global $config;
4094

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

    
4101
	if (isset($config['syslog']['apinger'])) {
4102
		$config['syslog']['dpinger'] = true;
4103
		config_del_path('syslog/apinger');
4104
	}
4105

    
4106
	if (isset($config['system']['apinger_debug'])) {
4107
		config_del_path('system/apinger_debug');
4108
	}
4109

    
4110
	if (!isset($config['gateways']['gateway_item']) ||
4111
	    !is_array($config['gateways']['gateway_item'])) {
4112
		return;
4113
	}
4114

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

    
4123
			if (isset($gw['interval'])) {
4124
				$effective_interval = $gw['interval'];
4125
			} else {
4126
				$effective_interval = $default_interval;
4127
			}
4128

    
4129
			if (isset($gw['down']) &&
4130
				is_numeric($gw['down'])) {
4131
				$gw['time_period'] = $gw['down'] * 1000;
4132
				unset($gw['down']);
4133
			}
4134

    
4135
			if (isset($gw['time_period'])) {
4136
				$effective_time_period = $gw['time_period'];
4137
			} else {
4138
				$effective_time_period = $default_time_period;
4139
			}
4140

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

    
4149
			if (isset($gw['loss_interval'])) {
4150
				$effective_loss_interval = $gw['loss_interval'];
4151
			} else {
4152
				$effective_loss_interval = $default_loss_interval;
4153
			}
4154

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

    
4163
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4164
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4165
			}
4166

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

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

    
4197
function upgrade_132_to_133() {
4198
	global $config;
4199

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

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

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

    
4231
// Determine the highest column number in use and set dashboardcolumns accordingly
4232
function upgrade_133_to_134() {
4233
	global $config;
4234

    
4235
	if (!isset($config['widgets']['sequence']) || isset($config['system']['webgui']['dashboardcolumns'])) {
4236
		return;
4237
	}
4238

    
4239
	$cur_widgets = explode(',', trim($config['widgets']['sequence']));
4240
	$maxcols = 2;
4241

    
4242
	foreach ($cur_widgets as $widget) {
4243
		list($file, $col, $display) = explode(':', $widget);
4244

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

    
4253
	$config['system']['webgui']['dashboardcolumns'] = $maxcols % 10;
4254
}
4255

    
4256
function upgrade_134_to_135() {
4257
	global $config;
4258

    
4259
	if (isset($config['syslog']['nologlighttpd'])) {
4260
		config_del_path('syslog/nologlighttpd');
4261
		$config['syslog']['nolognginx'] = true;
4262
	}
4263
}
4264

    
4265
function upgrade_135_to_136() {
4266
	global $config;
4267

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

    
4285
function upgrade_136_to_137() {
4286
	global $config;
4287

    
4288
	if (is_array($config['dhcpd'])) {
4289
		foreach ($config['dhcpd'] as &$dhcpd) {
4290
			if (!is_array($dhcpd['numberoptions']['item'])) {
4291
				continue;
4292
			}
4293

    
4294
			foreach ($dhcpd['numberoptions']['item'] as &$item) {
4295
				$item['value'] = base64_encode($item['value']);
4296
			}
4297
		}
4298
	}
4299

    
4300
	if (is_array($config['dhcpdv6'])) {
4301
		foreach ($config['dhcpdv6'] as &$dhcpdv6) {
4302
			if (!is_array($dhcpdv6['numberoptions']['item'])) {
4303
				continue;
4304
			}
4305

    
4306
			foreach ($dhcpdv6['numberoptions']['item'] as &$item) {
4307
				$item['value'] = base64_encode($item['value']);
4308
			}
4309
		}
4310
	}
4311
}
4312

    
4313
function upgrade_137_to_138() {
4314
	global $config;
4315

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

    
4325
function upgrade_138_to_139() {
4326
	global $config;
4327

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

    
4337
function upgrade_139_to_140() {
4338
	global $config;
4339

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

    
4351
function upgrade_140_to_141() {
4352
	global $config;
4353

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

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

    
4376
}
4377

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

    
4382
	init_config_arr(array('dyndnses', 'dyndns'));
4383
	$a_dyndns = &$config['dyndnses']['dyndns'];
4384

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

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

    
4406
// Updated to check for empty separator definitions via is_array()
4407
function upgrade_142_to_143() {
4408
	global $config;
4409

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

    
4414
			if (is_array($separators)) {
4415
				foreach ($separators as $sepn => $separator) {
4416

    
4417
					$seprow = substr($separator['row']['0'], 2);
4418
					$sepif  = $separator['if'];
4419

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

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

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

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

    
4452
function get_vip_from_ip_alias($ipalias) {
4453
	global $config;
4454

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

    
4464
	return ($ipalias);
4465
}
4466

    
4467
function get_vip_from_oldcarp($carp) {
4468
	global $config;
4469

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

    
4479
	return ($carp);
4480
}
4481

    
4482
function upgrade_143_to_144() {
4483
	global $config;
4484

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

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

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

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

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

    
4565
function upgrade_144_to_145() {
4566
	global $config;
4567

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

    
4587
function upgrade_145_to_146() {
4588
	// Add standard deviation to the quality rrds
4589
	global $config, $g;
4590

    
4591
	$rrddbpath = "/var/db/rrd";
4592
	$rrdtool = "/usr/local/bin/rrdtool";
4593

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

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

    
4629
		if (platform_booting()) {
4630
			echo "Update RRD database {$database}.\n";
4631
		}
4632

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

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

    
4646
function upgrade_bgpd_146_to_147() {
4647
	global $config;
4648

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

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

    
4670
function upgrade_quagga_146_to_147() {
4671
	global $config;
4672

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

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

    
4694
function upgrade_146_to_147() {
4695

    
4696
	upgrade_bgpd_146_to_147();
4697
	upgrade_quagga_146_to_147();
4698
}
4699

    
4700
function upgrade_147_to_148() {
4701
	global $config;
4702

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

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

    
4727
function upgrade_148_to_149() {
4728
	global $config;
4729
	global $altq_list_queues;
4730

    
4731
        if (!isset($config['shaper']['queue']) || !is_array($config['shaper']['queue']))
4732
                return;
4733

    
4734
	read_altq_config();
4735

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

    
4755
function upgrade_149_to_150() {
4756
	global $config;
4757

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

    
4769
function upgrade_150_to_151() {
4770
	global $config;
4771

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

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

    
4788
			if (isset($gw['alert_interval'])) {
4789
				$effective_alert_interval = $gw['alert_interval'];
4790
			} else {
4791
				$effective_alert_interval = $default_alert_interval;
4792
			}
4793

    
4794
			if (isset($gw['loss_interval'])) {
4795
				$effective_loss_interval = $gw['loss_interval'];
4796
			} else {
4797
				$effective_loss_interval = $default_loss_interval;
4798
			}
4799

    
4800
			if (isset($gw['time_period'])) {
4801
				$effective_time_period = $gw['time_period'];
4802
			} else {
4803
				$effective_time_period = $default_time_period;
4804
			}
4805

    
4806
			if (isset($gw['latencyhigh'])) {
4807
				$effective_latencyhigh = $gw['latencyhigh'];
4808
			} else {
4809
				$effective_latencyhigh = $default_latencyhigh;
4810
			}
4811

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

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

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

    
4830
function upgrade_151_to_152() {
4831
	global $g, $config;
4832

    
4833
	require_once("/etc/inc/services.inc");
4834

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

    
4843
function upgrade_152_to_153() {
4844
	global $config;
4845

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

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

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

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

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

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

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

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

    
4942
function upgrade_155_to_156() {
4943
	// Unused
4944
}
4945

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

    
4950
	init_config_arr(array('dyndnses', 'dyndns'));
4951
	$a_dyndns = &$config['dyndnses']['dyndns'];
4952

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

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

    
4974
function upgrade_157_to_158() {
4975
	global $config;
4976
	/* Convert Dynamic DNS passwords to base64 encoding. Redmine #6688 */
4977

    
4978
	init_config_arr(array('dyndnses', 'dyndns'));
4979
	$a_dyndns = &$config['dyndnses']['dyndns'];
4980

    
4981
	foreach ($a_dyndns as &$dyndns) {
4982
		$dyndns['password'] = base64_encode($dyndns['password']);
4983
	}
4984
}
4985

    
4986
/* Unset references to glxsb in the config. See #6755 */
4987
function upgrade_158_to_159() {
4988
	global $config;
4989

    
4990
	if ($config['system']['crypto_hardware'] == "glxsb") {
4991
		config_del_path('system/crypto_hardware');
4992
	}
4993
}
4994

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

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

    
5025
/* RAM Disk Management */
5026
function upgrade_160_to_161() {
5027
	global $g, $config;
5028

    
5029
	if (!isset($config['system']['use_mfs_tmpvar'])) {
5030
		return;
5031
	}
5032

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

    
5039
		$rrdrestore = "";
5040
		$rrdreturn = "";
5041
		unlink_if_exists("{$rrddbpath}/*.xml");
5042

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

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

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

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

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

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

    
5100
	// Restore RAM Disk Store if updated.
5101
	if ($ramds_updated) {
5102
		exec("/etc/rc.restore_ramdisk_store");
5103
	}
5104
}
5105

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

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

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

    
5131
	if (isset($config['widgets']['trafficgraphs']['shown'])) {
5132
		if (is_array($config['widgets']['trafficgraphs']['shown']['item'])) {
5133
			$ifdescrs = get_configured_interface_with_descr();
5134

    
5135
			if (ipsec_enabled()) {
5136
				$ifdescrs['enc0'] = "IPsec";
5137
			}
5138

    
5139
			$validNames = array();
5140

    
5141
			foreach ($ifdescrs as $ifdescr => $ifname) {
5142
				array_push($validNames, $ifdescr);
5143
			}
5144

    
5145
			$config['widgets']['traffic_graphs']['filter'] = implode(',', array_diff($validNames, $config['widgets']['trafficgraphs']['shown']['item']));
5146
		}
5147

    
5148
		config_del_path('widgets/trafficgraphs/shown');
5149
	}
5150
}
5151

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

    
5158
	if ($newname == '') {
5159
		$newname = $oldname . '-0';
5160
	}
5161

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

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

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

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

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

    
5208
				if (isset($user['widgets'][$oldname])) {
5209
					unset($user['widgets'][$oldname]);
5210
				}
5211
			}
5212
		}
5213

    
5214
		if (isset($config['widgets'][$oldname])) {
5215
			config_del_path("widgets/{$oldname}");
5216
		}
5217
	}
5218
}
5219

    
5220
function upgrade_163_to_164() {
5221
	global $config;
5222

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

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

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

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

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

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

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

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

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

    
5317
		$config['widgets']['sequence'] = implode(",", $newsequence);
5318
	}
5319
}
5320

    
5321
function upgrade_167_to_168() {
5322
	upgrade_166_to_167();
5323
}
5324

    
5325
function upgrade_168_to_169() {
5326
	global $config;
5327

    
5328
	config_del_path('cron/rc_update_pkg_metadata');
5329

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

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

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

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

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

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

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

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

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

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

    
5452
		$config['ppps']['ppp'][$id]['ports'] = str_replace('_vlan', '.',
5453
		    $ppp['ports']);
5454
	}
5455
}
5456

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

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

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

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

    
5522
/* Placeholder for a factory update. */
5523
function upgrade_176_to_177() {
5524
}
5525

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

    
5530
	if (isset($config['widgets'])) {
5531
		$idx = 0;
5532

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

    
5541
/* Placeholder for a factory update. */
5542
function upgrade_178_to_179() {
5543
}
5544

    
5545
function upgrade_179_to_180() {
5546
	global $config, $g;
5547

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

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

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

    
5570
function upgrade_181_to_182() {
5571
	global $config;
5572

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

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

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

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

    
5756
// Migrate AutoConfigBackup package settings to integrated ACB system
5757
// and remove package
5758
function upgrade_184_to_185() {
5759
	global $config;
5760

    
5761
	if (is_array($config['installedpackages']['autoconfigbackup']['config'][0])) {
5762
		$acbpkg = &$config['installedpackages']['autoconfigbackup']['config'][0];
5763

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

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

    
5775
		$acb['gold_password'] = $acbpkg['password'];
5776
		$acb['gold_username'] = $acbpkg['username'];
5777

    
5778
		config_del_path('installedpackages/autoconfigbackup/config');
5779
	}
5780
}
5781

    
5782
function upgrade_185_to_186() {
5783
	global $config;
5784

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

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

    
5804
	if (!is_array($config['system']['authserver'])) {
5805
		$config['system']['authserver'] = array();
5806
	}
5807

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

    
5821
	if($is_accounting) {
5822
		$pconfig['radius_srvcs'] = "both";
5823
		$pconfig['radius_acct_port'] = $accounting_port;
5824
	}
5825

    
5826
	$config['system']['authserver'][] = $pconfig;
5827

    
5828
	return 'radius - '.$pconfig['name'];
5829
}
5830

    
5831
function upgrade_186_to_187() {
5832
	global $config;
5833
	global $g;
5834

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

    
5842
			if ($cp['auth_method'] === 'radius') { // Radius Auth
5843
				$auth_servers = array();
5844
				$auth_servers2 = array();
5845
				$radiuscounter = 1;
5846

    
5847
				if (intval($cp['radiusport']) == 0) {
5848
					$cp['radiusport'] = 1812;
5849
				}
5850
				if (intval($cp['radiusacctport']) == 0) {
5851
					$cp['radiusacctport'] = 1813;
5852
				}
5853
				if (!isset($cp['radiussrcip_attribute'])) {
5854
					$cp['radiussrcip_attribute'] = 'wan';
5855
				}
5856
				$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']);
5857

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

    
5880
				$cp['auth_method'] = 'authserver';
5881
				$cp['auth_server'] = implode(",", $auth_servers);
5882
				$cp['auth_server2'] = implode(",", $auth_servers2);
5883

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

    
5899
			$config['captiveportal'][$cpzone] = $cp;
5900
		}
5901
	}
5902
}
5903

    
5904
function upgrade_187_to_188() {
5905
	global $config;
5906

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

    
5925
function upgrade_188_to_189() {
5926
	global $config;
5927

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

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

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

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

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

    
5975
	/* Determine if LB was active and notify (or log if not) */
5976
	$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);
5977
	if (is_array($config['load_balancer']['virtual_server']) &&
5978
	    count($config['load_balancer']['virtual_server']) &&
5979
	    count($config['load_balancer']['lbpool'])) {
5980

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

    
5989
	config_del_path('load_balancer');
5990

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

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

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

    
6019
/* Deprecate growl notifications */
6020
function upgrade_192_to_193() {
6021
	global $config;
6022

    
6023
	if (isset($config['notifications']['growl'])) {
6024
		config_del_path('notifications/growl');
6025
	}
6026
}
6027

    
6028
function upgrade_193_to_194() {
6029
	global $config, $g;
6030

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

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

    
6047
	$logfiles = system_syslogd_get_all_logfilenames();
6048

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

    
6058
/* Skipped. See https://redmine.pfsense.org/issues/9730 */
6059
function upgrade_195_to_196() {
6060
}
6061

    
6062
/* Add newsyslog cron job */
6063
function upgrade_196_to_197() {
6064
	global $g, $config;
6065

    
6066
	install_cron_job('/usr/sbin/newsyslog', true, "*/1", '*', '*', '*', '*', 'root', false);
6067
}
6068

    
6069
/* Add periodic cron jobs */
6070
function upgrade_197_to_198() {
6071
	global $g, $config;
6072

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

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

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

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

    
6119
/* #10525: Handle Chinese (HongKong / Taiwan) locale rename */
6120
function upgrade_201_to_202() {
6121
	global $config;
6122

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

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

    
6153
/*
6154
 * Change IPsec close_action values
6155
 * See https://redmine.pfsense.org/issues/10632
6156
 */
6157

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

    
6186
function upgrade_204_to_205() {
6187
	global $config, $g;
6188

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

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

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

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

    
6221
function upgrade_207_to_208() {
6222
	global $config;
6223

    
6224
	$config['system']['hn_altq_enable'] = true;
6225
}
6226

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

    
6234
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6235

    
6236
	if (!is_array($config['ipsec']['phase1']) ||
6237
	    !is_array($config['ipsec']['phase2'])) {
6238
		return;
6239
	}
6240

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

    
6266
function upgrade_209_to_210() {
6267
	global $config;
6268
	if (isset($config['system']['dnslocalhost'])) {
6269
		$config['system']['dnslocalhost'] = 'remote';
6270
	}
6271
}
6272

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

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

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

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

    
6349
		if (!empty($ph1ent['margintime'])) {
6350
			$ph1ent['rand_time'] = $ph1ent['margintime'];
6351
		}
6352

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

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

    
6373
/* VXLAN support was removed */
6374
function upgrade_213_to_214() {
6375
	global $config;
6376

    
6377
	if (isset($config['vxlans'])) {
6378
		config_del_path('vxlans');
6379
	}
6380
}
6381

    
6382
/* WireGuard support was removed */
6383
function upgrade_214_to_215() {
6384
	global $config;
6385

    
6386
	if (isset($config['wireguard'])) {
6387
		config_del_path('wireguard');
6388
	}
6389
}
6390

    
6391
/* Fix VTI interface numbers */
6392
function upgrade_215_to_216() {
6393
	global $config;
6394

    
6395
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6396

    
6397
	if (count($config['ipsec']['vtimaps']['item']) == 0) {
6398
		return;
6399
	}
6400

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

    
6421
	$iflist = get_configured_interface_list_by_realif(true);
6422

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

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

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

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

    
6441
		/* Interface is assigned */
6442
		if (isset($iflist[$old_if])) {
6443
			$config['interfaces'][$iflist[$old_if]]['if'] =
6444
			    'ipsec' . $new_vtimap['ifnum'];
6445
		}
6446

    
6447
		$config['ipsec']['vtimaps']['item'][$idx] = $new_vtimap;
6448
	}
6449
}
6450

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

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

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

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

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

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

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

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

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

    
6574
	init_config_arr(array('system', 'acb'));
6575

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

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

    
6588
	$widgets = explode(',', $config['widgets']['sequence']);
6589

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

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

    
6596
			$filter = explode(',', $config['widgets'][$widget_settings_key]['filter']);
6597

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

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

    
6608
	$config['widgets']['sequence'] = implode(',', $widgets);
6609
}
6610

    
6611
/* No functional changes. */
6612
function upgrade_221_to_222() {
6613
}
6614

    
6615
function upgrade_222_to_223() {
6616
	global $config;
6617

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

    
6632
function upgrade_223_to_224() {
6633
	global $config;
6634

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

    
6643
function upgrade_224_to_225() {
6644
	global $config;
6645

    
6646
	/* DHCP6 now uses single config for all interfaces
6647
	 * see https://redmine.pfsense.org/issues/6880 */
6648
	foreach ($config['interfaces'] as & $inf) {
6649
		if (isset($inf['dhcp6debug'])) {
6650
			$config['system']['dhcp6debug'] = true;
6651
			unset($inf['dhcp6debug']);
6652
		}
6653
		if (isset($inf['dhcp6norelease'])) {
6654
			$config['system']['dhcp6norelease'] = true;
6655
			unset($inf['dhcp6norelease']);
6656
		}
6657
	}
6658
}
6659

    
6660
function upgrade_225_to_226() {
6661
	global $config;
6662

    
6663
	/* Update value of state killing on gateway failure.
6664
	 * https://redmine.pfsense.org/issues/12092
6665
	 */
6666
	if (isset($config['system']['gw_down_kill_states'])) {
6667
		$config['system']['gw_down_kill_states'] = 'all';
6668
	}
6669
}
6670

    
6671
function upgrade_226_to_227() {
6672
	global $config;
6673

    
6674
	/* Convert dnsmasq (forwarder) custom options to base64.
6675
	 * https://redmine.pfsense.org/issues/13105
6676
	 */
6677
	if (is_array($config['dnsmasq']) && !empty($config['dnsmasq']['custom_options'])) {
6678
		$config['dnsmasq']['custom_options'] = base64_encode($config['dnsmasq']['custom_options']);
6679
	}
6680
}
6681

    
6682
function upgrade_227_to_228() {
6683
	global $config;
6684

    
6685
	$any_removed = false;
6686
	/* We no longer support 3des, blowfish, cast128 or md5 and sha1
6687
	 * authentication for IPSec. */
6688
	if (is_array($config['ipsec'])) {
6689
		if (is_array($config['ipsec']['phase1'])) {
6690
			foreach ($config['ipsec']['phase1'] as & $phase1) {
6691
				if (! isset($phase1['encryption']) || !is_array($phase1['encryption']['item']))
6692
					continue;
6693

    
6694
				$bad_count = 0;
6695
				foreach ($phase1['encryption']['item'] as $k => $enc) {
6696
					$bad = false;
6697
					if (isset($enc['encryption-algorithm']['name']) &&
6698
					    in_array($enc['encryption-algorithm']['name'],
6699
					    array("blowfish", "3des", "cast128"))) {
6700
						$bad = true;
6701
					}
6702
					if (isset($enc['hash-algorithm']) && $enc['hash-algorithm'] == "md5") {
6703
						$bad = true;
6704
					}
6705
					if ($bad) {
6706
						/* Remove this item as it contains deprecated encryption or hashing */
6707
						unset($phase1['encryption']['item'][$k]);
6708
						$bad_count++;
6709
					}
6710
				}
6711
				if ($bad_count > 0) {
6712
					$any_removed = true;
6713
					/* Only notify once per P1 */
6714
					if (count($phase1['encryption']['item']) == 0) {
6715
						/* Only disable P1 if there are no valid encryption options left. */
6716
						$phase1['disabled'] = true;
6717
						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']));
6718
					} else {
6719
						/* Let the user know that the P1 was adjusted */
6720
						file_notice("IPsec", sprintf(gettext("Removed deprecated encryption options from IPsec Phase 1 '%s'."), $phase1['descr']));
6721
					}
6722
				}
6723
			}
6724
		}
6725
		if (is_array($config['ipsec']['phase2'])) {
6726
			foreach ($config['ipsec']['phase2'] as & $phase2) {
6727

    
6728
				$bad_count = 0;
6729
				if (is_array($phase2['encryption-algorithm-option'])) {
6730
					foreach ($phase2['encryption-algorithm-option'] as $k => $opt) {
6731
						if (in_array($opt['name'], array("blowfish", "3des", "cast128"))) {
6732
							/* Remove this item as it contains deprecated encryption */
6733
							unset($phase2['encryption-algorithm-option'][$k]);
6734
							$bad_count++;
6735
						}
6736
					}
6737
				}
6738
				if (is_array($phase2['hash-algorithm-option'])) {
6739
					foreach ($phase2['hash-algorithm-option'] as $k => $opt) {
6740
						if ($opt == "hmac_md5") {
6741
							/* Remove this item as it contains deprecated hashing */
6742
							unset($phase2['hash-algorithm-option'][$k]);
6743
							$bad_count++;
6744
						}
6745
					}
6746
				}
6747

    
6748
				if ($bad_count > 0) {
6749
					$any_removed = true;
6750
					/* Only notify once per P2 */
6751
					if ((count($phase2['encryption-algorithm-option']) == 0) ||
6752
					    (count($phase2['hash-algorithm-option']) == 0)) {
6753
						/* Only disable P2 if there are no valid encryption options left. */
6754
						$phase2['disabled'] = true;
6755
						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']));
6756
					} else {
6757
						/* Let the user know that the P2 was adjusted */
6758
						file_notice("IPsec", sprintf(gettext("Removed deprecated encryption options from IPsec Phase 2 '%s'."), $phase2['descr']));
6759
					}
6760
				}
6761
			}
6762
		}
6763
	}
6764

    
6765
	/* Only list deprecated types once */
6766
	if ($any_removed) {
6767
		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."));
6768
	}
6769
}
6770

    
6771
/*
6772
 * Special function that is called independent of current config version. It's
6773
 * a workaround to have config_upgrade running on older versions after next
6774
 * config version was already taken by newer pfSense.
6775
 *
6776
 * XXX Change the way we handle config version to make it based on product
6777
 *     version
6778
 */
6779
function additional_config_upgrade() {
6780
}
6781

    
6782
?>
(53-53/61)