Project

General

Profile

Download (195 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
		unset($config['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
			unset($config['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
		unset($config['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
			unset($config['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
				unset($config['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
				unset($config['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
				unset($config['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
					unset($config['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
					unset($config['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['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['interfaces']['wan']['gateway'];
256
		}
257
		unset($config['interfaces']['wan']['gateway']);
258
	}
259

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

    
268
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) {
269
		if (isset($config['interfaces']['opt' . $i]['schedulertype'])) {
270
			unset($config['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['system']['firmwareurl'];
283
		$config['system']['alt_firmware_url']['firmware_filename'] = $config['system']['firmwarename'];
284
	}
285
	if (isset($config['system']['firmwareurl'])) {
286
		unset($config['system']['firmwareurl']);
287
	}
288
	if (isset($config['system']['firmwarename'])) {
289
		unset($config['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
		unset($config['shaper']['queue']);
299
	}
300
	if (isset($config['shaper']['rule'])) {
301
		unset($config['shaper']['rule']);
302
	}
303
	if (isset($config['interfaces']['wan']['bandwidth'])) {
304
		unset($config['interfaces']['wan']['bandwidth']);
305
	}
306
	if (isset($config['interfaces']['wan']['bandwidthtype'])) {
307
		unset($config['interfaces']['wan']['bandwidthtype']);
308
	}
309
	if (isset($config['interfaces']['lan']['bandwidth'])) {
310
		unset($config['interfaces']['lan']['bandwidth']);
311
	}
312
	if (isset($config['interfaces']['lan']['bandwidthtype'])) {
313
		unset($config['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
		unset($config['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
		unset($config['installedpackages']['carp']);
362
	}
363
	/* Server NAT is no longer needed */
364
	if (isset($config['nat']['servernat'])) {
365
		unset($config['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
				unset($config['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['system']['schedulertype'];
399
		unset($config['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['system']['gateway'];
408
}
409

    
410
function upgrade_022_to_023() {
411
	global $config;
412
	if (isset($config['shaper'])) {
413
		/* wipe previous shaper configuration */
414
		unset($config['shaper']);
415
	}
416
}
417

    
418

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

    
423

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

    
432

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
513

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

    
518

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

    
523

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

    
538

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

    
545

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

    
551

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

    
557

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

    
563

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

    
569

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

    
575

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

    
581

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

    
587

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

    
593

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

    
599

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

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

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

    
624
		$config['system']['user'][0]['priv'] = array();
625
		$config['system']['user'][0]['priv'][0]['id'] = "lockwc";
626
		$config['system']['user'][0]['priv'][0]['name'] = "Lock webConfigurator";
627
		$config['system']['user'][0]['priv'][0]['descr'] = gettext("Indicates whether this user will lock access to the webConfigurator for other users.");
628
		$config['system']['user'][0]['priv'][1]['id'] = "lock-ipages";
629
		$config['system']['user'][0]['priv'][1]['name'] = "Lock individual pages";
630
		$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).");
631
		$config['system']['user'][0]['priv'][2]['id'] = "hasshell";
632
		$config['system']['user'][0]['priv'][2]['name'] = "Has shell access";
633
		$config['system']['user'][0]['priv'][2]['descr'] = gettext("Indicates whether this user is able to login for example via SSH.");
634
		$config['system']['user'][0]['priv'][3]['id'] = "copyfiles";
635
		$config['system']['user'][0]['priv'][3]['name'] = "Is allowed to copy files";
636
		$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['product_label']);
637
		$config['system']['user'][0]['priv'][4]['id'] = "isroot";
638
		$config['system']['user'][0]['priv'][4]['name'] = "Is root user";
639
		$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).");
640

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

    
644
		/* wipe previous auth configuration */
645
		unset($config['system']['username']);
646
		if (isset($config['system']['password'])) {
647
			unset($config['system']['password']);
648
		}
649
	}
650
}
651

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
713
		$config['sysctl']['item'][14]['tunable'] = "net.inet.tcp.inflight.enable";
714
		$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. ");
715
		$config['sysctl']['item'][14]['value'] =   "default";
716

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

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

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

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

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

    
737
	}
738
}
739

    
740

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

    
751

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

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

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

    
805

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

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

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

    
847

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

    
868

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

    
952

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

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

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

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

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

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

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

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

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

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

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

    
989
				/* build new phase1 entry */
990

    
991
				$ph1ent = array();
992

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

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

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

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

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

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

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

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

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

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

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

    
1085
			/* build new phase2 entry */
1086

    
1087
			$ph2ent = array();
1088

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1185
		$mobilecfg = $config['ipsec']['mobileclients'];
1186

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

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

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

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

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

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

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

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

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

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

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

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

    
1316

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

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

    
1380

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

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

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

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

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

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

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

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

    
1448

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

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

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

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

    
1496

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

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

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

    
1539

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

    
1550
	$vpnid = 1;
1551

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

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

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

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

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

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

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

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

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

    
1604
				$index++;
1605
			}
1606

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

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

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

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

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

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

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

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

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

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

    
1720
			$config['openvpn']['openvpn-server'][] = $server;
1721
		}
1722
		unset($config['installedpackages']['openvpnserver']);
1723
	}
1724

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

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

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

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

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

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

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

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

    
1764
				$index++;
1765
			}
1766

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

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

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

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

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

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

    
1834
		unset($config['installedpackages']['openvpnclient']);
1835
	}
1836

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

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

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

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

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

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

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

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

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

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

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

    
1907
		unset($config['installedpackages']['openvpncsc']);
1908
	}
1909

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

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

    
1935
}
1936

    
1937

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

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

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

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

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

    
1973

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

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

    
2060

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2202

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

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

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

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

    
2256

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2410
}
2411

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

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

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

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

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

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

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

    
2506
			$a_ppps[] = $ppp;
2507

    
2508
		}
2509
	}
2510
}
2511

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

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

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

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

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

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

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

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

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

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

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

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

    
2621
			unset($config['nat']['onetoone'][$nidx]['internal']);
2622
			unset($config['nat']['onetoone'][$nidx]['subnet']);
2623
		}
2624

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3146
			}
3147
		}
3148
	}
3149
}
3150

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3374
	$config['nat']['outbound'] = $config['nat']['advancedoutbound'];
3375

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3538
			unset($config['installedpackages']['menu'][$idx]);
3539
			break;
3540
		}
3541
	}
3542

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

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

    
3557
	$pkg = $config['installedpackages']['unbound']['config'][0];
3558

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

    
3563
	$new = array();
3564

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3738
}
3739

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

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

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

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

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

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

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

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

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

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

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

    
3800
}
3801

    
3802

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4033
}
4034

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4379
}
4380

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4467
	return ($ipalias);
4468
}
4469

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

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

    
4482
	return ($carp);
4483
}
4484

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4697
function upgrade_146_to_147() {
4698

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

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

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

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

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

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

    
4737
	read_altq_config();
4738

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5142
			$validNames = array();
5143

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

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

    
5151
		unset($config['widgets']['trafficgraphs']['shown']);
5152
	}
5153
}
5154

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5331
	/* Remove workaround added in 2.3 */
5332
	unset($config['cron']['rc_update_pkg_metadata']);
5333

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5782
		unset($config['installedpackages']['autoconfigbackup']['config']);
5783
	}
5784
}
5785

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5993
	/* Clear old config */
5994
	unset($config['load_balancer']);
5995

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

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

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

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

    
6028
	if (isset($config['notifications']['growl'])) {
6029
		unset($config['notifications']['growl']);
6030
	}
6031
}
6032

    
6033
function upgrade_193_to_194() {
6034
	global $config, $g;
6035

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

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

    
6052
	$logfiles = system_syslogd_get_all_logfilenames();
6053

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
6191
function upgrade_204_to_205() {
6192
	global $config, $g;
6193

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

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

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

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

    
6226
function upgrade_207_to_208() {
6227
	global $config;
6228

    
6229
	$config['system']['hn_altq_enable'] = true;
6230
}
6231

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

    
6239
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6240

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

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

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

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

    
6315
function upgrade_211_to_212() {
6316
	global $config;
6317
	if (isset($config['unbound']['sslport'])) {
6318
		$config['unbound']['tlsport'] = $config['unbound']['sslport'];
6319
		unset($config['unbound']['sslport']);
6320
	}
6321
}
6322

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

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

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

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

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

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

    
6382
	if (isset($config['vxlans'])) {
6383
		unset($config['vxlans']);
6384
	}
6385
}
6386

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

    
6391
	if (isset($config['wireguard'])) {
6392
		unset($config['wireguard']);
6393
	}
6394
}
6395

    
6396
/* Fix VTI interface numbers */
6397
function upgrade_215_to_216() {
6398
	global $config;
6399

    
6400
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6401

    
6402
	if (count($config['ipsec']['vtimaps']['item']) == 0) {
6403
		return;
6404
	}
6405

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

    
6426
	$iflist = get_configured_interface_list_by_realif(true);
6427

    
6428
	foreach ($config['ipsec']['vtimaps']['item'] as $idx => $vtimap) {
6429
		if ($vtimap['ifnum'] <= 32767) {
6430
			continue;
6431
		}
6432

    
6433
		$new_vtimap = upgrade216_ipsec_create_vtimap($vtimap['reqid'],
6434
		    $vtimap['index']);
6435

    
6436
		/*
6437
		 * NULL means 32767 limit was reached.  It should never hit
6438
		 * this
6439
		 */
6440
		if ($new_vtimap == NULL) {
6441
			break;
6442
		}
6443

    
6444
		$old_if = 'ipsec' . $vtimap['ifnum'];
6445

    
6446
		/* Interface is assigned */
6447
		if (isset($iflist[$old_if])) {
6448
			$config['interfaces'][$iflist[$old_if]]['if'] =
6449
			    'ipsec' . $new_vtimap['ifnum'];
6450
		}
6451

    
6452
		$config['ipsec']['vtimaps']['item'][$idx] = $new_vtimap;
6453
	}
6454
}
6455

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

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

    
6494
/*
6495
 * Convert VTI interface names to new format
6496
 */
6497
function upgrade_218_to_219() {
6498
	global $config;
6499
	init_config_arr(array('ipsec', 'phase1'));
6500
	init_config_arr(array('ipsec', 'phase2'));
6501
	init_config_arr(array('ipsec', 'vtimaps', 'item'));
6502

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

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

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

    
6557
	/* If there are no VTI interfaces, we have nothing to do */
6558
	if (empty($ipsecifs)) {
6559
		return null;
6560
	}
6561

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

    
6572
/*
6573
 * Ensure the ACB cron job is installed after upgrade if ACB is enabled
6574
 * If the cron job already exists, no harm is done
6575
 */
6576
function upgrade_219_to_220() {
6577
	global $config;
6578

    
6579
	init_config_arr(array('system', 'acb'));
6580

    
6581
	if ($config['system']['acb']['enable'] == "yes" && file_exists("/usr/local/sbin/acbupload.php")) {
6582
		install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/acbupload.php", true, "*");
6583
	}
6584
}
6585

    
6586
/*
6587
 * Add new disk widget to dashboard if user already had the system information
6588
 * wiget configured to show disk usage stats.
6589
 */
6590
function upgrade_220_to_221() {
6591
	global $config;
6592

    
6593
	$widgets = explode(',', $config['widgets']['sequence']);
6594

    
6595
	foreach ($widgets as $idx => $widget) {
6596
		[$name, $col, $state, $index] = explode(':', $widget);
6597

    
6598
		if ($name === 'system_information') {
6599
			$widget_settings_key = "{$name}-{$index}";
6600

    
6601
			$filter = explode(',', $config['widgets'][$widget_settings_key]['filter']);
6602

    
6603
			if (!in_array('disk_usage', $filter)) {
6604
				$disk_widget = implode(':', array_filter(['disks', $col, $state, $index]));
6605

    
6606
				if (!in_array($disk_widget, $widgets)) {
6607
					array_splice($widgets, ($idx + 1), 0, $disk_widget);
6608
				}
6609
			}
6610
		}
6611
	}
6612

    
6613
	$config['widgets']['sequence'] = implode(',', $widgets);
6614
}
6615

    
6616
/* No functional changes. */
6617
function upgrade_221_to_222() {
6618
}
6619

    
6620
function upgrade_222_to_223() {
6621
	global $config;
6622

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

    
6637
function upgrade_223_to_224() {
6638
	global $config;
6639

    
6640
	init_config_arr(array('filter', 'rule'));
6641
	foreach ($config['filter']['rule'] as & $rule) {
6642
		if (isset($rule['floating']) && !isset($rule['interface'])) {
6643
			$rule['interface'] = 'any';
6644
		}
6645
	}
6646
}
6647

    
6648
function upgrade_224_to_225() {
6649
	global $config;
6650

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

    
6665
function upgrade_225_to_226() {
6666
	global $config;
6667

    
6668
	/* Update value of state killing on gateway failure.
6669
	 * https://redmine.pfsense.org/issues/12092
6670
	 */
6671
	if (isset($config['system']['gw_down_kill_states'])) {
6672
		$config['system']['gw_down_kill_states'] = 'all';
6673
	}
6674
}
6675

    
6676
function upgrade_226_to_227() {
6677
	global $config;
6678

    
6679
	/* Convert dnsmasq (forwarder) custom options to base64.
6680
	 * https://redmine.pfsense.org/issues/13105
6681
	 */
6682
	if (is_array($config['dnsmasq']) && !empty($config['dnsmasq']['custom_options'])) {
6683
		$config['dnsmasq']['custom_options'] = base64_encode($config['dnsmasq']['custom_options']);
6684
	}
6685
}
6686

    
6687
/*
6688
 * Special function that is called independent of current config version. It's
6689
 * a workaround to have config_upgrade running on older versions after next
6690
 * config version was already taken by newer pfSense.
6691
 *
6692
 * XXX Change the way we handle config version to make it based on product
6693
 *     version
6694
 */
6695
function additional_config_upgrade() {
6696
}
6697

    
6698
?>
(53-53/62)