Project

General

Profile

Download (161 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-2018 Rubicon Communications, LLC (Netgate)
7
 * All rights reserved.
8
 *
9
 * Licensed under the Apache License, Version 2.0 (the "License");
10
 * you may not use this file except in compliance with the License.
11
 * You may obtain a copy of the License at
12
 *
13
 * http://www.apache.org/licenses/LICENSE-2.0
14
 *
15
 * Unless required by applicable law or agreed to in writing, software
16
 * distributed under the License is distributed on an "AS IS" BASIS,
17
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
 * See the License for the specific language governing permissions and
19
 * limitations under the License.
20
 */
21

    
22
if (!function_exists("dump_rrd_to_xml")) {
23
	require_once("rrd.inc");
24
}
25
if (!function_exists("read_altq_config")) {
26
	require_once("shaper.inc");
27
}
28

    
29
/* Upgrade functions must be named:
30
*    upgrade_XXX_to_YYY
31
	* where XXX == previous version, zero padded, and YYY == next version, zero padded
32
	*/
33
function upgrade_010_to_011() {
34
	global $config;
35
	$opti = 1;
36
	$ifmap = array('lan' => 'lan', 'wan' => 'wan', 'pptp' => 'pptp');
37

    
38
	/* convert DMZ to optional, if necessary */
39
	if (isset($config['interfaces']['dmz'])) {
40

    
41
		$dmzcfg = &$config['interfaces']['dmz'];
42

    
43
		if ($dmzcfg['if']) {
44
			$config['interfaces']['opt' . $opti] = array();
45
			$optcfg = &$config['interfaces']['opt' . $opti];
46

    
47
			$optcfg['enable'] = $dmzcfg['enable'];
48
			$optcfg['descr'] = "DMZ";
49
			$optcfg['if'] = $dmzcfg['if'];
50
			$optcfg['ipaddr'] = $dmzcfg['ipaddr'];
51
			$optcfg['subnet'] = $dmzcfg['subnet'];
52

    
53
			$ifmap['dmz'] = "opt" . $opti;
54
			$opti++;
55
		}
56

    
57
		unset($config['interfaces']['dmz']);
58
	}
59

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

    
63
		if (!$config['interfaces']['wlan' . $i]['if']) {
64
			unset($config['interfaces']['wlan' . $i]);
65
			continue;
66
		}
67

    
68
		$wlancfg = &$config['interfaces']['wlan' . $i];
69
		$config['interfaces']['opt' . $opti] = array();
70
		$optcfg = &$config['interfaces']['opt' . $opti];
71

    
72
		$optcfg['enable'] = $wlancfg['enable'];
73
		$optcfg['descr'] = "WLAN" . $i;
74
		$optcfg['if'] = $wlancfg['if'];
75
		$optcfg['ipaddr'] = $wlancfg['ipaddr'];
76
		$optcfg['subnet'] = $wlancfg['subnet'];
77
		$optcfg['bridge'] = $wlancfg['bridge'];
78

    
79
		$optcfg['wireless'] = array();
80
		$optcfg['wireless']['mode'] = $wlancfg['mode'];
81
		$optcfg['wireless']['ssid'] = $wlancfg['ssid'];
82
		$optcfg['wireless']['channel'] = $wlancfg['channel'];
83
		$optcfg['wireless']['wep'] = $wlancfg['wep'];
84

    
85
		$ifmap['wlan' . $i] = "opt" . $opti;
86

    
87
		unset($config['interfaces']['wlan' . $i]);
88
		$opti++;
89
	}
90

    
91
	/* convert filter rules */
92
	$n = count($config['filter']['rule']);
93
	for ($i = 0; $i < $n; $i++) {
94

    
95
		$fr = &$config['filter']['rule'][$i];
96

    
97
		/* remap interface */
98
		if (array_key_exists($fr['interface'], $ifmap)) {
99
			$fr['interface'] = $ifmap[$fr['interface']];
100
		} else {
101
			/* remove the rule */
102
			printf(gettext("%sWarning: filter rule removed " .
103
				"(interface '%s' does not exist anymore)."), "\n", $fr['interface']);
104
			unset($config['filter']['rule'][$i]);
105
			continue;
106
		}
107

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

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

    
135
	/* convert shaper rules */
136
	$n = count($config['pfqueueing']['rule']);
137
	if (is_array($config['pfqueueing']['rule'])) {
138
		for ($i = 0; $i < $n; $i++) {
139

    
140
			$fr = &$config['pfqueueing']['rule'][$i];
141

    
142
			/* remap interface */
143
			if (array_key_exists($fr['interface'], $ifmap)) {
144
				$fr['interface'] = $ifmap[$fr['interface']];
145
			} else {
146
				/* remove the rule */
147
				printf(gettext("%sWarning: traffic shaper rule removed " .
148
					"(interface '%s' does not exist anymore)."), "\n", $fr['interface']);
149
				unset($config['pfqueueing']['rule'][$i]);
150
				continue;
151
			}
152

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

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

    
182

    
183
function upgrade_011_to_012() {
184
	global $config;
185
	/* move LAN DHCP server config */
186
	$tmp = $config['dhcpd'];
187
	$config['dhcpd'] = array();
188
	$config['dhcpd']['lan'] = $tmp;
189

    
190
	/* encrypt password */
191
	$config['system']['password'] = crypt($config['system']['password']);
192
}
193

    
194

    
195
function upgrade_012_to_013() {
196
	global $config;
197
	/* convert advanced outbound NAT config */
198
	for ($i = 0; isset($config['nat']['advancedoutbound']['rule'][$i]); $i++) {
199
		$curent = &$config['nat']['advancedoutbound']['rule'][$i];
200
		$src = $curent['source'];
201
		$curent['source'] = array();
202
		$curent['source']['network'] = $src;
203
		$curent['destination'] = array();
204
		$curent['destination']['any'] = true;
205
	}
206

    
207
	/* add an explicit type="pass" to all filter rules to make things consistent */
208
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++) {
209
		$config['filter']['rule'][$i]['type'] = "pass";
210
	}
211
}
212

    
213

    
214
function upgrade_013_to_014() {
215
	global $config;
216
	/* convert shaper rules (make pipes) */
217
	if (is_array($config['pfqueueing']['rule'])) {
218
		$config['pfqueueing']['pipe'] = array();
219

    
220
		for ($i = 0; isset($config['pfqueueing']['rule'][$i]); $i++) {
221
			$curent = &$config['pfqueueing']['rule'][$i];
222

    
223
			/* make new pipe and associate with this rule */
224
			$newpipe = array();
225
			$newpipe['descr'] = $curent['descr'];
226
			$newpipe['bandwidth'] = $curent['bandwidth'];
227
			$newpipe['delay'] = $curent['delay'];
228
			$newpipe['mask'] = $curent['mask'];
229
			$config['pfqueueing']['pipe'][$i] = $newpipe;
230

    
231
			$curent['targetpipe'] = $i;
232

    
233
			unset($curent['bandwidth']);
234
			unset($curent['delay']);
235
			unset($curent['mask']);
236
		}
237
	}
238
}
239

    
240

    
241
function upgrade_014_to_015() {
242
	global $config;
243
	/* Default route moved */
244
	if (isset($config['interfaces']['wan']['gateway'])) {
245
		if ($config['interfaces']['wan']['gateway'] <> "") {
246
			$config['system']['gateway'] = $config['interfaces']['wan']['gateway'];
247
		}
248
		unset($config['interfaces']['wan']['gateway']);
249
	}
250

    
251
	/* Queues are no longer interface specific */
252
	if (isset($config['interfaces']['lan']['schedulertype'])) {
253
		unset($config['interfaces']['lan']['schedulertype']);
254
	}
255
	if (isset($config['interfaces']['wan']['schedulertype'])) {
256
		unset($config['interfaces']['wan']['schedulertype']);
257
	}
258

    
259
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) {
260
		if (isset($config['interfaces']['opt' . $i]['schedulertype'])) {
261
			unset($config['interfaces']['opt' . $i]['schedulertype']);
262
		}
263
	}
264
}
265

    
266

    
267
function upgrade_015_to_016() {
268
	global $config;
269
	/* Alternate firmware URL moved */
270
	if (isset($config['system']['firmwareurl']) && isset($config['system']['firmwarename'])) { // Only convert if *both* are defined.
271
		$config['system']['alt_firmware_url'] = array();
272
		$config['system']['alt_firmware_url']['enabled'] = "";
273
		$config['system']['alt_firmware_url']['firmware_base_url'] = $config['system']['firmwareurl'];
274
		$config['system']['alt_firmware_url']['firmware_filename'] = $config['system']['firmwarename'];
275
	}
276
	if (isset($config['system']['firmwareurl'])) {
277
		unset($config['system']['firmwareurl']);
278
	}
279
	if (isset($config['system']['firmwarename'])) {
280
		unset($config['system']['firmwarename']);
281
	}
282
}
283

    
284

    
285
function upgrade_016_to_017() {
286
	global $config;
287
	/* wipe previous shaper configuration */
288
	if (isset($config['shaper']['queue'])) {
289
		unset($config['shaper']['queue']);
290
	}
291
	if (isset($config['shaper']['rule'])) {
292
		unset($config['shaper']['rule']);
293
	}
294
	if (isset($config['interfaces']['wan']['bandwidth'])) {
295
		unset($config['interfaces']['wan']['bandwidth']);
296
	}
297
	if (isset($config['interfaces']['wan']['bandwidthtype'])) {
298
		unset($config['interfaces']['wan']['bandwidthtype']);
299
	}
300
	if (isset($config['interfaces']['lan']['bandwidth'])) {
301
		unset($config['interfaces']['lan']['bandwidth']);
302
	}
303
	if (isset($config['interfaces']['lan']['bandwidthtype'])) {
304
		unset($config['interfaces']['lan']['bandwidthtype']);
305
	}
306
	$config['shaper']['enable'] = FALSE;
307
}
308

    
309

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

    
359
	/* enable SSH */
360
	if ($config['version'] == "1.8") {
361
		$config['system']['sshenabled'] = true;
362
	}
363
}
364

    
365

    
366
function upgrade_018_to_019() {
367
	global $config;
368
}
369

    
370

    
371
function upgrade_019_to_020() {
372
	global $config;
373
	if (is_array($config['ipsec']['tunnel'])) {
374
		reset($config['ipsec']['tunnel']);
375
		while (list($index, $tunnel) = each($config['ipsec']['tunnel'])) {
376
			/* Sanity check on required variables */
377
			/* This fixes bogus <tunnel> entries - remnant of bug #393 */
378
			if (!isset($tunnel['local-subnet']) && !isset($tunnel['remote-subnet'])) {
379
				unset($config['ipsec']['tunnel'][$tunnel]);
380
			}
381
		}
382
	}
383
}
384

    
385
function upgrade_020_to_021() {
386
	global $config;
387
	/* shaper scheduler moved */
388
	if (isset($config['system']['schedulertype'])) {
389
		$config['shaper']['schedulertype'] = $config['system']['schedulertype'];
390
		unset($config['system']['schedulertype']);
391
	}
392
}
393

    
394

    
395
function upgrade_021_to_022() {
396
	global $config;
397
	/* move gateway to wan interface */
398
	$config['interfaces']['wan']['gateway'] = $config['system']['gateway'];
399
}
400

    
401
function upgrade_022_to_023() {
402
	global $config;
403
	if (isset($config['shaper'])) {
404
		/* wipe previous shaper configuration */
405
		unset($config['shaper']);
406
	}
407
}
408

    
409

    
410
function upgrade_023_to_024() {
411
	global $config;
412
}
413

    
414

    
415
function upgrade_024_to_025() {
416
	global $config;
417
	$config['interfaces']['wan']['use_rrd_gateway'] = $config['system']['use_rrd_gateway'];
418
	if (isset($config['system']['use_rrd_gateway'])) {
419
		unset($config['system']['use_rrd_gateway']);
420
	}
421
}
422

    
423

    
424
function upgrade_025_to_026() {
425
	global $config;
426
	$cron_item = array();
427
	$cron_item['minute'] = "0";
428
	$cron_item['hour'] = "*";
429
	$cron_item['mday'] = "*";
430
	$cron_item['month'] = "*";
431
	$cron_item['wday'] = "*";
432
	$cron_item['who'] = "root";
433
	$cron_item['command'] = "/usr/bin/nice -n20 newsyslog";
434

    
435
	$config['cron']['item'][] = $cron_item;
436

    
437
	$cron_item = array();
438
	$cron_item['minute'] = "1,31";
439
	$cron_item['hour'] = "0-5";
440
	$cron_item['mday'] = "*";
441
	$cron_item['month'] = "*";
442
	$cron_item['wday'] = "*";
443
	$cron_item['who'] = "root";
444
	$cron_item['command'] = "/usr/bin/nice -n20 adjkerntz -a";
445

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

    
448
	$cron_item = array();
449
	$cron_item['minute'] = "1";
450
	$cron_item['hour'] = "*";
451
	$cron_item['mday'] = "1";
452
	$cron_item['month'] = "*";
453
	$cron_item['wday'] = "*";
454
	$cron_item['who'] = "root";
455
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.update_bogons.sh";
456

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

    
459
	$cron_item = array();
460
	$cron_item['minute'] = "*/60";
461
	$cron_item['hour'] = "*";
462
	$cron_item['mday'] = "*";
463
	$cron_item['month'] = "*";
464
	$cron_item['wday'] = "*";
465
	$cron_item['who'] = "root";
466
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshlockout";
467

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

    
470
	$cron_item = array();
471
	$cron_item['minute'] = "1";
472
	$cron_item['hour'] = "1";
473
	$cron_item['mday'] = "*";
474
	$cron_item['month'] = "*";
475
	$cron_item['wday'] = "*";
476
	$cron_item['who'] = "root";
477
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.dyndns.update";
478

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

    
481
	$cron_item = array();
482
	$cron_item['minute'] = "*/60";
483
	$cron_item['hour'] = "*";
484
	$cron_item['mday'] = "*";
485
	$cron_item['month'] = "*";
486
	$cron_item['wday'] = "*";
487
	$cron_item['who'] = "root";
488
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 virusprot";
489

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

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

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

    
504

    
505
function upgrade_026_to_027() {
506
	global $config;
507
}
508

    
509

    
510
function upgrade_027_to_028() {
511
	global $config;
512
}
513

    
514

    
515
function upgrade_028_to_029() {
516
	global $config;
517
	$rule_item = array();
518
	$a_filter = &$config['filter']['rule'];
519
	$rule_item['interface'] = "enc0";
520
	$rule_item['type'] = "pass";
521
	$rule_item['source']['any'] = true;
522
	$rule_item['destination']['any'] = true;
523
	$rule_item['descr'] = gettext("Permit IPsec traffic.");
524
	$rule_item['statetype'] = "keep state";
525
	$a_filter[] = $rule_item;
526
}
527

    
528

    
529
function upgrade_029_to_030() {
530
	global $config;
531
	/* enable the rrd config setting by default */
532
	$config['rrd']['enable'] = true;
533
}
534

    
535

    
536
function upgrade_030_to_031() {
537
	global $config;
538
	/* Insert upgrade code here */
539
}
540

    
541

    
542
function upgrade_031_to_032() {
543
	global $config;
544
	/* Insert upgrade code here */
545
}
546

    
547

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

    
553

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

    
559

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

    
565

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

    
571

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

    
577

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

    
583

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

    
589

    
590
function upgrade_039_to_040() {
591
	global $config, $g;
592
	$config['system']['webgui']['auth_method'] = "session";
593
	$config['system']['webgui']['backing_method'] = "htpasswd";
594

    
595
	if (isset($config['system']['username'])) {
596
		$config['system']['group'] = array();
597
		$config['system']['group'][0]['name'] = "admins";
598
		$config['system']['group'][0]['description'] = gettext("System Administrators");
599
		$config['system']['group'][0]['scope'] = "system";
600
		$config['system']['group'][0]['priv'] = "page-all";
601
		$config['system']['group'][0]['home'] = "index.php";
602
		$config['system']['group'][0]['gid'] = "110";
603

    
604
		$config['system']['user'] = array();
605
		$config['system']['user'][0]['name'] = "{$config['system']['username']}";
606
		$config['system']['user'][0]['descr'] = "System Administrator";
607
		$config['system']['user'][0]['scope'] = "system";
608
		$config['system']['user'][0]['groupname'] = "admins";
609
		$config['system']['user'][0]['password'] = "{$config['system']['password']}";
610
		$config['system']['user'][0]['uid'] = "0";
611
		/* Ensure that we follow what this new "admin" username should be in the session. */
612
		$_SESSION["Username"] = "{$config['system']['username']}";
613

    
614
		$config['system']['user'][0]['priv'] = array();
615
		$config['system']['user'][0]['priv'][0]['id'] = "lockwc";
616
		$config['system']['user'][0]['priv'][0]['name'] = "Lock webConfigurator";
617
		$config['system']['user'][0]['priv'][0]['descr'] = gettext("Indicates whether this user will lock access to the webConfigurator for other users.");
618
		$config['system']['user'][0]['priv'][1]['id'] = "lock-ipages";
619
		$config['system']['user'][0]['priv'][1]['name'] = "Lock individual pages";
620
		$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).");
621
		$config['system']['user'][0]['priv'][2]['id'] = "hasshell";
622
		$config['system']['user'][0]['priv'][2]['name'] = "Has shell access";
623
		$config['system']['user'][0]['priv'][2]['descr'] = gettext("Indicates whether this user is able to login for example via SSH.");
624
		$config['system']['user'][0]['priv'][3]['id'] = "copyfiles";
625
		$config['system']['user'][0]['priv'][3]['name'] = "Is allowed to copy files";
626
		$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_name']);
627
		$config['system']['user'][0]['priv'][4]['id'] = "isroot";
628
		$config['system']['user'][0]['priv'][4]['name'] = "Is root user";
629
		$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).");
630

    
631
		$config['system']['nextuid'] = "111";
632
		$config['system']['nextgid'] = "111";
633

    
634
		/* wipe previous auth configuration */
635
		unset($config['system']['username']);
636
		if (isset($config['system']['password'])) {
637
			unset($config['system']['password']);
638
		}
639
	}
640
}
641

    
642
function upgrade_040_to_041() {
643
	global $config;
644
	if (!$config['sysctl']) {
645
		$config['sysctl']['item'] = array();
646

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

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

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

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

    
663
		$config['sysctl']['item'][4]['tunable'] = "net.inet.ip.redirect";
664
		$config['sysctl']['item'][4]['descr'] =    gettext("Sending of IPv4 ICMP redirects");
665
		$config['sysctl']['item'][4]['value'] =   "default";
666

    
667
		$config['sysctl']['item'][5]['tunable'] = "net.inet6.ip6.redirect";
668
		$config['sysctl']['item'][5]['descr'] =    gettext("Sending of IPv6 ICMP redirects");
669
		$config['sysctl']['item'][5]['value'] =   "default";
670

    
671
		$config['sysctl']['item'][6]['tunable'] = "net.inet.tcp.syncookies";
672
		$config['sysctl']['item'][6]['descr'] =    gettext("Generate SYN cookies for outbound SYN-ACK packets");
673
		$config['sysctl']['item'][6]['value'] =   "default";
674

    
675
		$config['sysctl']['item'][7]['tunable'] = "net.inet.tcp.recvspace";
676
		$config['sysctl']['item'][7]['descr'] =    gettext("Maximum incoming TCP datagram size");
677
		$config['sysctl']['item'][7]['value'] =   "default";
678

    
679
		$config['sysctl']['item'][8]['tunable'] = "net.inet.tcp.sendspace";
680
		$config['sysctl']['item'][8]['descr'] =    gettext("Maximum outgoing TCP datagram size");
681
		$config['sysctl']['item'][8]['value'] =   "default";
682

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

    
687
		$config['sysctl']['item'][10]['tunable'] = "net.inet.udp.maxdgram";
688
		$config['sysctl']['item'][10]['descr'] =    gettext("Maximum outgoing UDP datagram size");
689
		$config['sysctl']['item'][10]['value'] =   "default";
690

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

    
695
		$config['sysctl']['item'][12]['tunable'] = "net.link.tap.user_open";
696
		$config['sysctl']['item'][12]['descr'] =    gettext("Allow unprivileged access to tap(4) device nodes");
697
		$config['sysctl']['item'][12]['value'] =   "default";
698

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

    
703
		$config['sysctl']['item'][14]['tunable'] = "net.inet.tcp.inflight.enable";
704
		$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. ");
705
		$config['sysctl']['item'][14]['value'] =   "default";
706

    
707
		$config['sysctl']['item'][15]['tunable'] = "net.inet.icmp.icmplim";
708
		$config['sysctl']['item'][15]['descr'] =    gettext("Set ICMP Limits");
709
		$config['sysctl']['item'][15]['value'] =   "default";
710

    
711
		$config['sysctl']['item'][16]['tunable'] = "net.inet.tcp.tso";
712
		$config['sysctl']['item'][16]['descr'] =    gettext("TCP Offload engine");
713
		$config['sysctl']['item'][16]['value'] =   "default";
714

    
715
		$config['sysctl']['item'][17]['tunable'] = "net.inet.ip.portrange.first";
716
		$config['sysctl']['item'][17]['descr'] =    "Set the ephemeral port range starting port";
717
		$config['sysctl']['item'][17]['value'] =   "default";
718

    
719
		$config['sysctl']['item'][18]['tunable'] = "hw.syscons.kbd_reboot";
720
		$config['sysctl']['item'][18]['descr'] =    "Enables ctrl+alt+delete";
721
		$config['sysctl']['item'][18]['value'] =   "default";
722

    
723
		$config['sysctl']['item'][19]['tunable'] = "kern.ipc.maxsockbuf";
724
		$config['sysctl']['item'][19]['descr'] =    "Maximum socket buffer size";
725
		$config['sysctl']['item'][19]['value'] =   "default";
726

    
727
	}
728
}
729

    
730

    
731
function upgrade_041_to_042() {
732
	global $config;
733
	if (isset($config['shaper'])) {
734
		unset($config['shaper']);
735
	}
736
	if (isset($config['ezshaper'])) {
737
		unset($config['ezshaper']);
738
	}
739
}
740

    
741

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

    
772
		/* Update all filter rules which might reference this gateway */
773
		$j = 0;
774
		foreach ($config['filter']['rule'] as $rule) {
775
			if (is_ipaddr($rule['gateway'])) {
776
				if ($rule['gateway'] == $config['gateways']['gateway_item'][$i]['gateway']) {
777
					$config['filter']['rule'][$j]['gateway'] = $config['gateways']['gateway_item'][$i]['name'];
778
				} else if ($rule['gateway'] == $ifname) {
779
					$config['filter']['rule'][$j]['gateway'] = $config['gateways']['gateway_item'][$i]['name'];
780
				}
781
			}
782
			$j++;
783
		}
784

    
785
		/* rename old Quality RRD files in the process */
786
		$rrddbpath = "/var/db/rrd";
787
		$gwname = "GW_" . strtoupper($ifname);
788
		if (is_readable("{$rrddbpath}/{$ifname}-quality.rrd")) {
789
			rename("{$rrddbpath}/{$ifname}-quality.rrd", "{$rrddbpath}/{$gwname}-quality.rrd");
790
		}
791
		$i++;
792
	}
793
}
794

    
795

    
796
function upgrade_043_to_044() {
797
	global $config;
798

    
799
	/* migrate static routes to the new gateways config */
800
	$gateways = return_gateways_array(true);
801
	$i = 0;
802
	if (is_array($config['staticroutes']['route'])) {
803
		$gwmap = array();
804
		foreach ($config['staticroutes']['route'] as $idx => $sroute) {
805
			$found = false;
806
			foreach ($gateways as $gwname => $gw) {
807
				if ($gw['gateway'] == $sroute['gateway']) {
808
					$config['staticroutes']['route'][$idx]['gateway'] = $gwname;
809
					$found = true;
810
					break;
811
				}
812
			}
813
			if ($gwmap[$sroute['gateway']]) {
814
				/* We already added a gateway name for this IP */
815
				$config['staticroutes']['route'][$idx]['gateway'] = "{$gwmap[$sroute['gateway']]}";
816
				$found = true;
817
			}
818

    
819
			if ($found == false) {
820
				$gateway = array();
821
				$gateway['name'] = "SROUTE{$i}";
822
				$gwmap[$sroute['gateway']] = $gateway['name'];
823
				$gateway['gateway'] = $sroute['gateway'];
824
				$gateway['interface'] = $sroute['interface'];
825
				$gateway['descr'] = sprintf(gettext("Upgraded static route for %s"), $sroute['network']);
826
				if (!is_array($config['gateways']['gateway_item'])) {
827
					$config['gateways']['gateway_item'] = array();
828
				}
829
				$config['gateways']['gateway_item'][] = $gateway;
830
				$config['staticroutes']['route'][$idx]['gateway'] = $gateway['name'];
831
				$i++;
832
			}
833
		}
834
	}
835
}
836

    
837

    
838
function upgrade_044_to_045() {
839
	global $config;
840
	$iflist = get_configured_interface_list(true);
841
	if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
842
		$i = 0;
843
		foreach ($config['vlans']['vlan'] as $id => $vlan) {
844
			/* Make sure to update the interfaces section with the right name */
845
			$vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}";
846
			foreach ($iflist as $ifname) {
847
				if ($config['interfaces'][$ifname]['if'] == "vlan{$i}") {
848
					$config['interfaces'][$ifname]['if'] = $vlan_name;
849
					continue;
850
				}
851
			}
852
			$config['vlans']['vlan'][$i]['vlanif'] = "{$vlan_name}";
853
			$i++;
854
		}
855
	}
856
}
857

    
858

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

    
943

    
944
function upgrade_046_to_047() {
945
	global $config;
946
	/* Upgrade IPsec from tunnel to phase1/phase2 */
947

    
948
	if (is_array($config['ipsec']['tunnel'])) {
949

    
950
		$a_phase1 = array();
951
		$a_phase2 = array();
952
		$ikeid = 0;
953

    
954
		foreach ($config['ipsec']['tunnel'] as $tunnel) {
955

    
956
			unset($ph1ent);
957
			unset($ph2ent);
958

    
959
			/*
960
				*  attempt to locate an enabled phase1
961
				*  entry that matches the peer gateway
962
				*/
963

    
964
			if (!isset($tunnel['disabled'])) {
965

    
966
				$remote_gateway = $tunnel['remote-gateway'];
967

    
968
				foreach ($a_phase1 as $ph1tmp) {
969
					if ($ph1tmp['remote-gateway'] == $remote_gateway) {
970
						$ph1ent = $ph1tmp;
971
						break;
972
					}
973
				}
974
			}
975

    
976
			/* none found, create a new one */
977

    
978
			if (!isset($ph1ent)) {
979

    
980
				/* build new phase1 entry */
981

    
982
				$ph1ent = array();
983

    
984
				$ph1ent['ikeid'] = ++$ikeid;
985

    
986
				if (isset($tunnel['disabled'])) {
987
					$ph1ent['disabled'] = $tunnel['disabled'];
988
				}
989

    
990
				/* convert to the new vip[$vhid] name */
991
				if (preg_match("/^carp/", $tunnel['interface'])) {
992
					$carpid = str_replace("carp", "", $tunnel['interface']);
993
					$tunnel['interface'] = "vip" . $config['virtualip']['vip'][$carpid]['vhid'];
994
				}
995
				$ph1ent['interface'] = $tunnel['interface'];
996
				$ph1ent['remote-gateway'] = $tunnel['remote-gateway'];
997
				$ph1ent['descr'] = $tunnel['descr'];
998

    
999
				$ph1ent['mode'] = $tunnel['p1']['mode'];
1000

    
1001
				if (isset($tunnel['p1']['myident']['myaddress'])) {
1002
					$ph1ent['myid_type'] = "myaddress";
1003
				}
1004
				if (isset($tunnel['p1']['myident']['address'])) {
1005
					$ph1ent['myid_type'] = "address";
1006
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['address'];
1007
				}
1008
				if (isset($tunnel['p1']['myident']['fqdn'])) {
1009
					$ph1ent['myid_type'] = "fqdn";
1010
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['fqdn'];
1011
				}
1012
				if (isset($tunnel['p1']['myident']['ufqdn'])) {
1013
					$ph1ent['myid_type'] = "user_fqdn";
1014
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['ufqdn'];
1015
				}
1016
				if (isset($tunnel['p1']['myident']['asn1dn'])) {
1017
					$ph1ent['myid_type'] = "asn1dn";
1018
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['asn1dn'];
1019
				}
1020
				if (isset($tunnel['p1']['myident']['dyn_dns'])) {
1021
					$ph1ent['myid_type'] = "dyn_dns";
1022
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['dyn_dns'];
1023
				}
1024

    
1025
				$ph1ent['peerid_type'] = "peeraddress";
1026

    
1027
				switch ($tunnel['p1']['encryption-algorithm']) {
1028
					case "des":
1029
						$ph1alg = array('name' => 'des');
1030
						break;
1031
					case "3des":
1032
						$ph1alg = array('name' => '3des');
1033
						break;
1034
					case "blowfish":
1035
						$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1036
						break;
1037
					case "cast128":
1038
						$ph1alg = array('name' => 'cast128');
1039
						break;
1040
					case "rijndael":
1041
						$ph1alg = array('name' => 'aes', 'keylen' => '128');
1042
						break;
1043
					case "rijndael 256":
1044
					case "aes 256":
1045
						$ph1alg = array('name' => 'aes', 'keylen' => '256');
1046
						break;
1047
				}
1048

    
1049
				$ph1ent['encryption-algorithm'] = $ph1alg;
1050
				$ph1ent['hash-algorithm'] = $tunnel['p1']['hash-algorithm'];
1051
				$ph1ent['dhgroup'] = $tunnel['p1']['dhgroup'];
1052
				$ph1ent['lifetime'] = $tunnel['p1']['lifetime'];
1053
				$ph1ent['authentication_method'] = $tunnel['p1']['authentication_method'];
1054

    
1055
				if (isset($tunnel['p1']['pre-shared-key'])) {
1056
					$ph1ent['pre-shared-key'] = $tunnel['p1']['pre-shared-key'];
1057
				}
1058
				if (isset($tunnel['p1']['cert'])) {
1059
					$ph1ent['cert'] = $tunnel['p1']['cert'];
1060
				}
1061
				if (isset($tunnel['p1']['peercert'])) {
1062
					$ph1ent['peercert'] = $tunnel['p1']['peercert'];
1063
				}
1064
				if (isset($tunnel['p1']['private-key'])) {
1065
					$ph1ent['private-key'] = $tunnel['p1']['private-key'];
1066
				}
1067

    
1068
				$ph1ent['nat_traversal'] = "on";
1069
				$ph1ent['dpd_enable'] = 1;
1070
				$ph1ent['dpd_delay'] = 10;
1071
				$ph1ent['dpd_maxfail'] = 5;
1072

    
1073
				$a_phase1[] = $ph1ent;
1074
			}
1075

    
1076
			/* build new phase2 entry */
1077

    
1078
			$ph2ent = array();
1079

    
1080
			$ph2ent['ikeid'] = $ph1ent['ikeid'];
1081

    
1082
			if (isset($tunnel['disabled'])) {
1083
				$ph1ent['disabled'] = $tunnel['disabled'];
1084
			}
1085

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

    
1088
			$type = "lan";
1089
			if ($tunnel['local-subnet']['network']) {
1090
				$type = $tunnel['local-subnet']['network'];
1091
			}
1092
			if ($tunnel['local-subnet']['address']) {
1093
				list($address, $netbits) = explode("/", $tunnel['local-subnet']['address']);
1094
				if (is_null($netbits)) {
1095
					$type = "address";
1096
				} else {
1097
					$type = "network";
1098
				}
1099
			}
1100

    
1101
			switch ($type) {
1102
				case "address":
1103
					$ph2ent['localid'] = array('type' => $type, 'address' => $address);
1104
					break;
1105
				case "network":
1106
					$ph2ent['localid'] = array('type' => $type, 'address' => $address, 'netbits' => $netbits);
1107
					break;
1108
				default:
1109
					$ph2ent['localid'] = array('type' => $type);
1110
					break;
1111
			}
1112

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

    
1116
			$ph2ent['protocol'] = $tunnel['p2']['protocol'];
1117

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

    
1143
				if (!$aes_found || ($aes_count < 2)) {
1144
					$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1145
				}
1146
			}
1147

    
1148
			$ph2ent['hash-algorithm-option'] = $tunnel['p2']['hash-algorithm-option'];
1149
			$ph2ent['pfsgroup'] = $tunnel['p2']['pfsgroup'];
1150
			$ph2ent['lifetime'] = $tunnel['p2']['lifetime'];
1151

    
1152
			if (isset($tunnel['pinghost']['pinghost'])) {
1153
				$ph2ent['pinghost'] = $tunnel['pinghost'];
1154
			}
1155

    
1156
			$a_phase2[] = $ph2ent;
1157
		}
1158

    
1159
		unset($config['ipsec']['tunnel']);
1160
		$config['ipsec']['phase1'] = $a_phase1;
1161
		$config['ipsec']['phase2'] = $a_phase2;
1162
	}
1163

    
1164
	/* Upgrade Mobile IPsec */
1165
	if (isset($config['ipsec']['mobileclients']) &&
1166
	    is_array($config['ipsec']['mobileclients']) &&
1167
	    is_array($config['ipsec']['mobileclients']['p1']) &&
1168
	    is_array($config['ipsec']['mobileclients']['p2'])) {
1169

    
1170
		if (isset($config['ipsec']['mobileclients']['enable'])) {
1171
			$config['ipsec']['client']['enable'] = true;
1172
			$config['ipsec']['client']['user_source'] = 'system';
1173
			$config['ipsec']['client']['group_source'] = 'system';
1174
		}
1175

    
1176
		$mobilecfg = $config['ipsec']['mobileclients'];
1177

    
1178
		$ph1ent = array();
1179
		$ph1ent['ikeid'] = ++$ikeid;
1180

    
1181
		if (!isset($mobilecfg['enable'])) {
1182
			$ph1ent['disabled'] = true;
1183
		}
1184

    
1185
		/* Assume WAN since mobile tunnels couldn't be on a separate interface on 1.2.x */
1186
		$ph1ent['interface'] = 'wan';
1187
		$ph1ent['descr'] = "Mobile Clients (upgraded)";
1188
		$ph1ent['mode'] = $mobilecfg['p1']['mode'];
1189

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

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

    
1238
		$ph1ent['encryption-algorithm'] = $ph1alg;
1239
		$ph1ent['hash-algorithm'] = $mobilecfg['p1']['hash-algorithm'];
1240
		$ph1ent['dhgroup'] = $mobilecfg['p1']['dhgroup'];
1241
		$ph1ent['lifetime'] = $mobilecfg['p1']['lifetime'];
1242
		$ph1ent['authentication_method'] = $mobilecfg['p1']['authentication_method'];
1243

    
1244
		if (isset($mobilecfg['p1']['cert'])) {
1245
			$ph1ent['cert'] = $mobilecfg['p1']['cert'];
1246
		}
1247
		if (isset($mobilecfg['p1']['peercert'])) {
1248
			$ph1ent['peercert'] = $mobilecfg['p1']['peercert'];
1249
		}
1250
		if (isset($mobilecfg['p1']['private-key'])) {
1251
			$ph1ent['private-key'] = $mobilecfg['p1']['private-key'];
1252
		}
1253

    
1254
		$ph1ent['nat_traversal'] = "on";
1255
		$ph1ent['dpd_enable'] = 1;
1256
		$ph1ent['dpd_delay'] = 10;
1257
		$ph1ent['dpd_maxfail'] = 5;
1258
		$ph1ent['mobile'] = true;
1259

    
1260
		$ph2ent = array();
1261
		$ph2ent['ikeid'] = $ph1ent['ikeid'];
1262
		$ph2ent['descr'] = "phase2 for ".$mobilecfg['descr'];
1263
		$ph2ent['localid'] = array('type' => 'none');
1264
		$ph2ent['remoteid'] = array('type' => 'mobile');
1265
		$ph2ent['protocol'] = $mobilecfg['p2']['protocol'];
1266

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

    
1292
			if (!$aes_found || ($aes_count < 2)) {
1293
				$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1294
			}
1295
		}
1296
		$ph2ent['hash-algorithm-option'] = $mobilecfg['p2']['hash-algorithm-option'];
1297
		$ph2ent['pfsgroup'] = $mobilecfg['p2']['pfsgroup'];
1298
		$ph2ent['lifetime'] = $mobilecfg['p2']['lifetime'];
1299
		$ph2ent['mobile'] = true;
1300

    
1301
		$config['ipsec']['phase1'][] = $ph1ent;
1302
		$config['ipsec']['phase2'][] = $ph2ent;
1303
		unset($config['ipsec']['mobileclients']);
1304
	}
1305
}
1306

    
1307

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

    
1341
	if (is_array($config['pppoe']) && is_array($config['pppoe'][0])) {
1342
		$pconfig = array();
1343
		$pconfig['username'] = $config['pppoe'][0]['username'];
1344
		$pconfig['password'] = $config['pppoe'][0]['password'];
1345
		$pconfig['provider'] = $config['pppoe'][0]['provider'];
1346
		$pconfig['ondemand'] = isset($config['pppoe'][0]['ondemand']);
1347
		$pconfig['timeout'] = $config['pppoe'][0]['timeout'];
1348
		unset($config['pppoe']);
1349
		$config['interfaces']['wan']['pppoe_username'] = $pconfig['username'];
1350
		$config['interfaces']['wan']['pppoe_password'] = $pconfig['password'];
1351
		$config['interfaces']['wan']['provider'] = $pconfig['provider'];
1352
		$config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']);
1353
		$config['interfaces']['wan']['timeout'] = $pconfig['timeout'];
1354
	}
1355
	if (is_array($config['pptp'])) {
1356
		$pconfig = array();
1357
		$pconfig['username'] = $config['pptp']['username'];
1358
		$pconfig['password'] = $config['pptp']['password'];
1359
		$pconfig['provider'] = $config['pptp']['provider'];
1360
		$pconfig['ondemand'] = isset($config['pptp']['ondemand']);
1361
		$pconfig['timeout'] = $config['pptp']['timeout'];
1362
		unset($config['pptp']);
1363
		$config['interfaces']['wan']['pptp_username'] = $pconfig['username'];
1364
		$config['interfaces']['wan']['pptp_password'] = $pconfig['password'];
1365
		$config['interfaces']['wan']['provider'] = $pconfig['provider'];
1366
		$config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']);
1367
		$config['interfaces']['wan']['timeout'] = $pconfig['timeout'];
1368
	}
1369
}
1370

    
1371

    
1372
function upgrade_048_to_049() {
1373
	global $config;
1374
	/* setup new all users group */
1375
	$all = array();
1376
	$all['name'] = "all";
1377
	$all['description'] = gettext("All Users");
1378
	$all['scope'] = "system";
1379
	$all['gid'] = 1998;
1380
	$all['member'] = array();
1381

    
1382
	if (!is_array($config['system']['user'])) {
1383
		$config['system']['user'] = array();
1384
	}
1385
	if (!is_array($config['system']['group'])) {
1386
		$config['system']['group'] = array();
1387
	}
1388

    
1389
	/* work around broken uid assignments */
1390
	$config['system']['nextuid'] = 2000;
1391
	foreach ($config['system']['user'] as & $user) {
1392
		if (isset($user['uid']) && !$user['uid']) {
1393
			continue;
1394
		}
1395
		$user['uid'] = $config['system']['nextuid']++;
1396
	}
1397

    
1398
	/* work around broken gid assignments */
1399
	$config['system']['nextgid'] = 2000;
1400
	foreach ($config['system']['group'] as & $group) {
1401
		if ($group['name'] == $g['admin_group']) {
1402
			$group['gid'] = 1999;
1403
		} else {
1404
			$group['gid'] = $config['system']['nextgid']++;
1405
		}
1406
	}
1407

    
1408
	/* build group membership information */
1409
	foreach ($config['system']['group'] as & $group) {
1410
		$group['member'] = array();
1411
		foreach ($config['system']['user'] as & $user) {
1412
			$groupnames = explode(",", $user['groupname']);
1413
			if (in_array($group['name'], $groupnames)) {
1414
				$group['member'][] = $user['uid'];
1415
			}
1416
		}
1417
	}
1418

    
1419
	/* reset user group information */
1420
	foreach ($config['system']['user'] as & $user) {
1421
		unset($user['groupname']);
1422
		$all['member'][] = $user['uid'];
1423
	}
1424

    
1425
	/* reset group scope information */
1426
	foreach ($config['system']['group'] as & $group) {
1427
		if ($group['name'] != $g['admin_group']) {
1428
			$group['scope'] = "user";
1429
		}
1430
	}
1431

    
1432
	/* insert new all group */
1433
	$groups = Array();
1434
	$groups[] = $all;
1435
	$groups = array_merge($config['system']['group'], $groups);
1436
	$config['system']['group'] = $groups;
1437
}
1438

    
1439

    
1440
function upgrade_049_to_050() {
1441
	global $config;
1442

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

    
1466
	/* update group privileges */
1467
	foreach ($config['system']['group'] as & $group) {
1468
		$privs = array();
1469
		if (!is_array($group['pages'])) {
1470
			unset($group['pages']);
1471
			continue;
1472
		}
1473
		foreach ($group['pages'] as $page) {
1474
			$priv = map_page_privname($page);
1475
			if ($priv) {
1476
				$privs[] = $priv;
1477
			}
1478
		}
1479
		unset($group['pages']);
1480
		$group['priv'] = $privs;
1481
	}
1482

    
1483
	/* sync all local account information */
1484
	local_sync_accounts();
1485
}
1486

    
1487

    
1488
function upgrade_050_to_051() {
1489
	global $config;
1490
	$pconfig = array();
1491
	$pconfig['descr'] = "Set to 0 to disable filtering on the incoming and outgoing member interfaces.";
1492
	$pconfig['tunable'] = "net.link.bridge.pfil_member";
1493
	$pconfig['value'] = "1";
1494
	$config['sysctl']['item'][] = $pconfig;
1495
	$pconfig = array();
1496
	$pconfig['descr'] = "Set to 1 to enable filtering on the bridge interface";
1497
	$pconfig['tunable'] = "net.link.bridge.pfil_bridge";
1498
	$pconfig['value'] = "0";
1499
	$config['sysctl']['item'][] = $pconfig;
1500

    
1501
	if (isset($config['bridge'])) {
1502
		unset($config['bridge']);
1503
	}
1504

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

    
1530

    
1531
function upgrade_051_to_052() {
1532
	global $config;
1533
	$config['openvpn'] = array();
1534
	if (!is_array($config['ca'])) {
1535
		$config['ca'] = array();
1536
	}
1537
	if (!is_array($config['cert'])) {
1538
		$config['cert'] = array();
1539
	}
1540

    
1541
	$vpnid = 1;
1542

    
1543
	/* openvpn server configurations */
1544
	if (is_array($config['installedpackages']['openvpnserver'])) {
1545
		$config['openvpn']['openvpn-server'] = array();
1546

    
1547
		$index = 1;
1548
		foreach ($config['installedpackages']['openvpnserver']['config'] as $server) {
1549

    
1550
			if (!is_array($server)) {
1551
				continue;
1552
			}
1553

    
1554
			if ($server['auth_method'] == "pki") {
1555

    
1556
				/* create ca entry */
1557
				$ca = array();
1558
				$ca['refid'] = uniqid();
1559
				$ca['descr'] = "OpenVPN Server CA #{$index}";
1560
				$ca['crt'] = $server['ca_cert'];
1561
				$config['ca'][] = $ca;
1562

    
1563
				/* create ca reference */
1564
				unset($server['ca_cert']);
1565
				$server['caref'] = $ca['refid'];
1566

    
1567
				/* create a crl entry if needed */
1568
				if (!empty($server['crl'][0])) {
1569
					$crl = array();
1570
					$crl['refid'] = uniqid();
1571
					$crl['descr'] = "Imported OpenVPN CRL #{$index}";
1572
					$crl['caref'] = $ca['refid'];
1573
					$crl['text'] = $server['crl'][0];
1574
					if (!is_array($config['crl'])) {
1575
						$config['crl'] = array();
1576
					}
1577
					$config['crl'][] = $crl;
1578
					$server['crlref'] = $crl['refid'];
1579
				}
1580
				unset($server['crl']);
1581

    
1582
				/* create cert entry */
1583
				$cert = array();
1584
				$cert['refid'] = uniqid();
1585
				$cert['descr'] = "OpenVPN Server Certificate #{$index}";
1586
				$cert['crt'] = $server['server_cert'];
1587
				$cert['prv'] = $server['server_key'];
1588
				$config['cert'][] = $cert;
1589

    
1590
				/* create cert reference */
1591
				unset($server['server_cert']);
1592
				unset($server['server_key']);
1593
				$server['certref'] = $cert['refid'];
1594

    
1595
				$index++;
1596
			}
1597

    
1598
			/* determine operational mode */
1599
			if ($server['auth_method'] == 'pki') {
1600
				if ($server['nopool']) {
1601
					$server['mode'] = "p2p_tls";
1602
				} else {
1603
					$server['mode'] = "server_tls";
1604
				}
1605
			} else {
1606
				$server['mode'] = "p2p_shared_key";
1607
			}
1608
			unset($server['auth_method']);
1609

    
1610
			/* modify configuration values */
1611
			$server['dh_length'] = 1024;
1612
			unset($server['dh_params']);
1613
			if (!$server['interface']) {
1614
				$server['interface'] = 'any';
1615
			}
1616
			$server['tunnel_network'] = $server['addresspool'];
1617
			unset($server['addresspool']);
1618
			if (isset($server['use_lzo']) && ($server['use_lzo'] == "on")) {
1619
				$server['compression'] = "on";
1620
				unset($server['use_lzo']);
1621
			}
1622
			if ($server['nopool']) {
1623
				$server['pool_enable'] = false;
1624
			} else {
1625
				$server['pool_enable'] = "yes";
1626
			}
1627
			unset($server['nopool']);
1628
			$server['dns_domain'] = $server['dhcp_domainname'];
1629
			unset($server['dhcp_domainname']);
1630

    
1631
			$tmparr = explode(";", $server['dhcp_dns'], 4);
1632
			$d=1;
1633
			foreach ($tmparr as $tmpa) {
1634
				$server["dns_server{$d}"] = $tmpa;
1635
				$d++;
1636
			}
1637
			unset($server['dhcp_dns']);
1638

    
1639
			$tmparr = explode(";", $server['dhcp_ntp'], 2);
1640
			$d=1;
1641
			foreach ($tmparr as $tmpa) {
1642
				$server["ntp_server{$d}"] = $tmpa;
1643
				$d++;
1644
			}
1645
			unset($server['dhcp_ntp']);
1646

    
1647
			if ($server['dhcp_nbtdisable']) {
1648
				$server['netbios_enable'] = false;
1649
			} else {
1650
				$server['netbios_enable'] = "yes";
1651
			}
1652
			unset($server['dhcp_nbtdisable']);
1653
			$server['netbios_ntype'] = $server['dhcp_nbttype'];
1654
			unset($server['dhcp_nbttype']);
1655
			$server['netbios_scope'] = $server['dhcp_nbtscope'];
1656
			unset($server['dhcp_nbtscope']);
1657

    
1658
			$tmparr = explode(";", $server['dhcp_nbdd'], 2);
1659
			$d=1;
1660
			foreach ($tmparr as $tmpa) {
1661
				$server["nbdd_server{$d}"] = $tmpa;
1662
				$d++;
1663
			}
1664
			unset($server['dhcp_nbdd']);
1665

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

    
1674
			if (!empty($server['disable'])) {
1675
				$server['disable'] = true;
1676
			} else {
1677
				unset($server['disable']);
1678
			}
1679

    
1680
			/* allocate vpnid */
1681
			$server['vpnid'] = $vpnid++;
1682

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

    
1711
			$config['openvpn']['openvpn-server'][] = $server;
1712
		}
1713
		unset($config['installedpackages']['openvpnserver']);
1714
	}
1715

    
1716
	/* openvpn client configurations */
1717
	if (is_array($config['installedpackages']['openvpnclient'])) {
1718
		$config['openvpn']['openvpn-client'] = array();
1719

    
1720
		$index = 1;
1721
		foreach ($config['installedpackages']['openvpnclient']['config'] as $client) {
1722

    
1723
			if (!is_array($client)) {
1724
				continue;
1725
			}
1726

    
1727
			if ($client['auth_method'] == "pki") {
1728

    
1729
				/* create ca entry */
1730
				$ca = array();
1731
				$ca['refid'] = uniqid();
1732
				$ca['descr'] = "OpenVPN Client CA #{$index}";
1733
				$ca['crt'] = $client['ca_cert'];
1734
				$ca['crl'] = $client['crl'];
1735
				$config['ca'][] = $ca;
1736

    
1737
				/* create ca reference */
1738
				unset($client['ca_cert']);
1739
				unset($client['crl']);
1740
				$client['caref'] = $ca['refid'];
1741

    
1742
				/* create cert entry */
1743
				$cert = array();
1744
				$cert['refid'] = uniqid();
1745
				$cert['descr'] = "OpenVPN Client Certificate #{$index}";
1746
				$cert['crt'] = $client['client_cert'];
1747
				$cert['prv'] = $client['client_key'];
1748
				$config['cert'][] = $cert;
1749

    
1750
				/* create cert reference */
1751
				unset($client['client_cert']);
1752
				unset($client['client_key']);
1753
				$client['certref'] = $cert['refid'];
1754

    
1755
				$index++;
1756
			}
1757

    
1758
			/* determine operational mode */
1759
			if ($client['auth_method'] == 'pki') {
1760
				$client['mode'] = "p2p_tls";
1761
			} else {
1762
				$client['mode'] = "p2p_shared_key";
1763
			}
1764
			unset($client['auth_method']);
1765

    
1766
			/* modify configuration values */
1767
			if (!$client['interface']) {
1768
				$client['interface'] = 'wan';
1769
			}
1770
			$client['tunnel_network'] = $client['interface_ip'];
1771
			unset($client['interface_ip']);
1772
			$client['server_addr'] = $client['serveraddr'];
1773
			unset($client['serveraddr']);
1774
			$client['server_port'] = $client['serverport'];
1775
			unset($client['serverport']);
1776
			$client['proxy_addr'] = $client['poxy_hostname'];
1777
			unset($client['proxy_addr']);
1778
			if (isset($client['use_lzo']) && ($client['use_lzo'] == "on")) {
1779
				$client['compression'] = "on";
1780
				unset($client['use_lzo']);
1781
			}
1782
			$client['resolve_retry'] = $client['infiniteresolvretry'];
1783
			unset($client['infiniteresolvretry']);
1784

    
1785
			/* allocate vpnid */
1786
			$client['vpnid'] = $vpnid++;
1787

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

    
1816
			if (!empty($client['disable'])) {
1817
				$client['disable'] = true;
1818
			} else {
1819
				unset($client['disable']);
1820
			}
1821

    
1822
			$config['openvpn']['openvpn-client'][] = $client;
1823
		}
1824

    
1825
		unset($config['installedpackages']['openvpnclient']);
1826
	}
1827

    
1828
	/* openvpn client specific configurations */
1829
	if (is_array($config['installedpackages']['openvpncsc'])) {
1830
		$config['openvpn']['openvpn-csc'] = array();
1831

    
1832
		foreach ($config['installedpackages']['openvpncsc']['config'] as $csc) {
1833

    
1834
			if (!is_array($csc)) {
1835
				continue;
1836
			}
1837

    
1838
			/* modify configuration values */
1839
			$csc['common_name'] = $csc['commonname'];
1840
			unset($csc['commonname']);
1841
			$csc['tunnel_network'] = $csc['ifconfig_push'];
1842
			unset($csc['ifconfig_push']);
1843
			$csc['dns_domain'] = $csc['dhcp_domainname'];
1844
			unset($csc['dhcp_domainname']);
1845

    
1846
			$tmparr = explode(";", $csc['dhcp_dns'], 4);
1847
			$d=1;
1848
			foreach ($tmparr as $tmpa) {
1849
				$csc["dns_server{$d}"] = $tmpa;
1850
				$d++;
1851
			}
1852
			unset($csc['dhcp_dns']);
1853

    
1854
			$tmparr = explode(";", $csc['dhcp_ntp'], 2);
1855
			$d=1;
1856
			foreach ($tmparr as $tmpa) {
1857
				$csc["ntp_server{$d}"] = $tmpa;
1858
				$d++;
1859
			}
1860
			unset($csc['dhcp_ntp']);
1861

    
1862
			if ($csc['dhcp_nbtdisable']) {
1863
				$csc['netbios_enable'] = false;
1864
			} else {
1865
				$csc['netbios_enable'] = "yes";
1866
			}
1867
			unset($csc['dhcp_nbtdisable']);
1868
			$csc['netbios_ntype'] = $csc['dhcp_nbttype'];
1869
			unset($csc['dhcp_nbttype']);
1870
			$csc['netbios_scope'] = $csc['dhcp_nbtscope'];
1871
			unset($csc['dhcp_nbtscope']);
1872

    
1873
			$tmparr = explode(";", $csc['dhcp_nbdd'], 2);
1874
			$d=1;
1875
			foreach ($tmparr as $tmpa) {
1876
				$csc["nbdd_server{$d}"] = $tmpa;
1877
				$d++;
1878
			}
1879
			unset($csc['dhcp_nbdd']);
1880

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

    
1889
			if (!empty($csc['disable'])) {
1890
				$csc['disable'] = true;
1891
			} else {
1892
				unset($csc['disable']);
1893
			}
1894

    
1895
			$config['openvpn']['openvpn-csc'][] = $csc;
1896
		}
1897

    
1898
		unset($config['installedpackages']['openvpncsc']);
1899
	}
1900

    
1901
	if (count($config['openvpn']['openvpn-server']) > 0 ||
1902
	    count($config['openvpn']['openvpn-client']) > 0) {
1903
		$ovpnrule = array();
1904
		$ovpnrule['type'] = "pass";
1905
		$ovpnrule['interface'] = "openvpn";
1906
		$ovpnrule['statetype'] = "keep state";
1907
		$ovpnrule['source'] = array();
1908
		$ovpnrule['destination'] = array();
1909
		$ovpnrule['source']['any'] = true;
1910
		$ovpnrule['destination']['any'] = true;
1911
		$ovpnrule['descr'] = gettext("Auto added OpenVPN rule from config upgrade.");
1912
		$config['filter']['rule'][] = $ovpnrule;
1913
	}
1914

    
1915
	/*
1916
		* FIXME: hack to keep things working with no installedpackages
1917
		* or carp array in the configuration data.
1918
		*/
1919
	if (!is_array($config['installedpackages'])) {
1920
		$config['installedpackages'] = array();
1921
	}
1922
	if (!is_array($config['installedpackages']['carp'])) {
1923
		$config['installedpackages']['carp'] = array();
1924
	}
1925

    
1926
}
1927

    
1928

    
1929
function upgrade_052_to_053() {
1930
	global $config;
1931
	if (!is_array($config['ca'])) {
1932
		$config['ca'] = array();
1933
	}
1934
	if (!is_array($config['cert'])) {
1935
		$config['cert'] = array();
1936
	}
1937

    
1938
	/* migrate advanced admin page webui ssl to certificate manager */
1939
	if ($config['system']['webgui']['certificate'] &&
1940
	    $config['system']['webgui']['private-key']) {
1941

    
1942
		/* create cert entry */
1943
		$cert = array();
1944
		$cert['refid'] = uniqid();
1945
		$cert['descr'] = "webConfigurator SSL Certificate";
1946
		$cert['crt'] = $config['system']['webgui']['certificate'];
1947
		$cert['prv'] = $config['system']['webgui']['private-key'];
1948
		$config['cert'][] = $cert;
1949

    
1950
		/* create cert reference */
1951
		unset($config['system']['webgui']['certificate']);
1952
		unset($config['system']['webgui']['private-key']);
1953
		$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1954
	}
1955

    
1956
	/* migrate advanced admin page ssh keys to user manager */
1957
	if ($config['system']['ssh']['authorizedkeys']) {
1958
		$admin_user =& getUserEntryByUID(0);
1959
		$admin_user['authorizedkeys'] = $config['system']['ssh']['authorizedkeys'];
1960
		unset($config['system']['ssh']['authorizedkeys']);
1961
	}
1962
}
1963

    
1964

    
1965
function upgrade_053_to_054() {
1966
	global $config;
1967
	if (is_array($config['load_balancer']['lbpool'])) {
1968
		$lbpool_arr = $config['load_balancer']['lbpool'];
1969
		$lbpool_srv_arr = array();
1970
		$gateway_group_arr = array();
1971
		$gateways = return_gateways_array();
1972
		$group_name_changes = array();
1973
		if (!is_array($config['gateways']['gateway_item'])) {
1974
			$config['gateways']['gateway_item'] = array();
1975
		}
1976

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

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

    
2054

    
2055
function upgrade_054_to_055() {
2056
	global $config;
2057
	global $g;
2058

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

    
2065
	$rrddbpath = "/var/db/rrd/";
2066
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2067

    
2068
	$rrdinterval = 60;
2069
	$valid = $rrdinterval * 2;
2070

    
2071
	/* Asume GigE for now */
2072
	$downstream = 125000000;
2073
	$upstream = 125000000;
2074

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

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

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

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

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

    
2118
		unset($rrdold);
2119
		@unlink("{$g['tmp_path']}/{$xmldump}");
2120
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2121
	}
2122

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

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

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

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

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

    
2157
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2158
		$rrdold = $rrdold['rrd'];
2159

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

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

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

    
2196

    
2197
function upgrade_055_to_056() {
2198
	global $config;
2199

    
2200
	if (!is_array($config['ca'])) {
2201
		$config['ca'] = array();
2202
	}
2203
	if (!is_array($config['cert'])) {
2204
		$config['cert'] = array();
2205
	}
2206

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

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

    
2250

    
2251
function upgrade_056_to_057() {
2252
	global $config;
2253

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

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

    
2297
function upgrade_058_to_059() {
2298
	global $config;
2299

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

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

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

    
2339
function upgrade_060_to_061() {
2340
	global $config;
2341

    
2342
	if (is_array($config['interfaces']['wan'])) {
2343
		$config['interfaces']['wan']['enable'] = true;
2344
	}
2345
	if (is_array($config['interfaces']['lan'])) {
2346
		$config['interfaces']['lan']['enable'] = true;
2347
	}
2348

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

    
2361
function upgrade_061_to_062() {
2362
	global $config;
2363

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

    
2368
		foreach ($a_nat as &$natent) {
2369
			$natent['disabled'] = false;
2370
			$natent['nordr']    = false;
2371

    
2372
			$natent['source'] = array(
2373
				"not"     => false,
2374
				"any"     => true,
2375
				"port"    => ""
2376
			);
2377

    
2378
			$natent['destination'] = array(
2379
				"not"     => false,
2380
				"address" => $natent['external-address'],
2381
				"port"    => $natent['external-port']
2382
			);
2383

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

    
2392
			unset($natent['external-address']);
2393
			unset($natent['external-port']);
2394
		}
2395

    
2396
		unset($natent);
2397
	}
2398
}
2399

    
2400
function upgrade_062_to_063() {
2401
	/* Upgrade legacy Themes to the new pfsense_ng */
2402
	// Not supported in 2.3+
2403

    
2404
}
2405

    
2406
function upgrade_063_to_064() {
2407
	global $config;
2408
	$j = 0;
2409
	$ifcfg = &$config['interfaces'];
2410

    
2411
	if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
2412
		foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
2413
			$config['ppps']['ppp'][$pppid]['if'] = "ppp".$j;
2414
			$config['ppps']['ppp'][$pppid]['ptpid'] = $j;
2415
			$j++;
2416
			if (isset($ppp['port'])) {
2417
				$config['ppps']['ppp'][$pppid]['ports'] = $ppp['port'];
2418
				unset($config['ppps']['ppp'][$pppid]['port']);
2419
			}
2420
			if (!isset($ppp['type'])) {
2421
				$config['ppps']['ppp'][$pppid]['type'] = "ppp";
2422
			}
2423
			if (isset($ppp['defaultgw'])) {
2424
				unset($config['ppps']['ppp'][$pppid]['defaultgw']);
2425
			}
2426
		}
2427
	}
2428

    
2429
	if (!is_array($config['ppps']['ppp'])) {
2430
		$config['ppps']['ppp'] = array();
2431
	}
2432
	$a_ppps = &$config['ppps']['ppp'];
2433

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

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

    
2484
			$ifcfg[$ifname]['if'] = $ifinfo['ipaddr'].$j;
2485
			$j++;
2486

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

    
2501
			$a_ppps[] = $ppp;
2502

    
2503
		}
2504
	}
2505
}
2506

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

    
2514
function upgrade_065_to_066() {
2515
	global $config;
2516

    
2517
	$dhcrelaycfg =& $config['dhcrelay'];
2518

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

    
2536
function upgrade_066_to_067() {
2537
	global $config;
2538
	if (isset($config['system']['ca'])) {
2539
		$config['ca'] = $config['system']['ca'];
2540
		unset($config['system']['ca']);
2541
	}
2542
	if (isset($config['system']['cert'])) {
2543
		$config['cert'] = $config['system']['cert'];
2544
		unset($config['system']['cert']);
2545
	}
2546
}
2547

    
2548
function upgrade_067_to_068() {
2549
	global $config;
2550

    
2551
	if (!empty($config['pppoe'])) {
2552
		$config['pppoes'] = array();
2553
		$config['pppoes']['pppoe'] = array();
2554
		$config['pppoes']['pppoe'][] = $config['pppoe'][0];
2555

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

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

    
2601
function upgrade_069_to_070() {
2602
	global $config;
2603

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

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

    
2615
			unset($config['nat']['onetoone'][$nidx]['internal']);
2616
			unset($config['nat']['onetoone'][$nidx]['subnet']);
2617
		}
2618

    
2619
		unset($natent);
2620
	}
2621
}
2622

    
2623
function upgrade_070_to_071() {
2624
	global $config;
2625

    
2626
	if (is_array($config['cron']['item'])) {
2627
		foreach ($config['cron']['item'] as $idx => $cronitem) {
2628
			if (stristr($cronitem['command'], "checkreload.sh")) {
2629
				unset($config['cron']['item'][$idx]);
2630
				break;
2631
			}
2632
		}
2633
	}
2634
}
2635

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

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

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

    
2678
function upgrade_073_to_074() {
2679
	global $config;
2680
	rename_field($config['system']['user'], 'fullname', 'descr');
2681
}
2682

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

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

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

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

    
2746
function upgrade_079_to_080() {
2747
	global $config;
2748

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

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

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

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

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

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

    
2782
	/* Asume GigE for now */
2783
	$downstream = 125000000;
2784
	$upstream = 125000000;
2785

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

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

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

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

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

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

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

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

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

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

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

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

    
2927
function upgrade_081_to_082() {
2928
	/* don't enable the allow IPv6 toggle */
2929
}
2930

    
2931
function upgrade_082_to_083() {
2932
	global $config;
2933

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

    
2954
function upgrade_083_to_084() {
2955
	global $config;
2956
	if (!isset($config['hasync'])) {
2957
		if (!empty($config['installedpackages']) &&
2958
		    !empty($config['installedpackages']['carpsettings']) &&
2959
		    !empty($config['installedpackages']['carpsettings']['config'])) {
2960
			$config['hasync'] = $config['installedpackages']['carpsettings']['config'][0];
2961
			unset($config['installedpackages']['carpsettings']);
2962
		}
2963
		if (empty($config['installedpackages']['carpsettings']) && isset($config['installedpackages']['carpsettings'])) {
2964
			unset($config['installedpackages']['carpsettings']);
2965
		}
2966
		if (empty($config['installedpackages']) && isset($config['installedpackages'])) {
2967
			unset($config['installedpackages']);
2968
		}
2969
	}
2970
}
2971

    
2972
function upgrade_084_to_085() {
2973
	global $config;
2974

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

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

    
3018
function upgrade_085_to_086() {
3019
	global $config, $g;
3020

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

    
3037
function upgrade_086_to_087() {
3038
	global $config, $dummynet_pipe_list;
3039

    
3040
	if (!is_array($config['dnshaper']) || !is_array($config['dnshaper']['queue'])) {
3041
		return;
3042
	}
3043

    
3044
	$dnqueue_number = 1;
3045
	$dnpipe_number = 1;
3046

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

    
3058
	unset($dnqueue_number, $dnpipe_number, $qidx, $idx, $dnpipe, $dnqueue);
3059

    
3060
	if (!is_array($config['filter']) || !is_array($config['filter']['rule'])) {
3061
		return;
3062
	}
3063

    
3064
	require_once("shaper.inc");
3065
	read_dummynet_config();
3066

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

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

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

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

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

    
3127
					/* add ca reference to certificate */
3128
					$cert['caref'] = $ca['refid'];
3129
				}
3130

    
3131
				$config['cert'][] = $cert;
3132

    
3133
				/* create cert reference */
3134
				$setting['certref'] = $cert['refid'];
3135

    
3136
				unset($setting['certificate']);
3137
				unset($setting['private-key']);
3138
				unset($setting['cacertificate']);
3139

    
3140
			}
3141
		}
3142
	}
3143
}
3144

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

    
3161
function upgrade_090_to_091() {
3162
	global $config;
3163

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

    
3179
function upgrade_091_to_092() {
3180
	global $config;
3181

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

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

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

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

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

    
3209
function upgrade_093_to_094() {
3210
	global $config;
3211

    
3212
	if (isset($config['system']['powerd_mode'])) {
3213
		$config['system']['powerd_ac_mode'] = $config['system']['powerd_mode'];
3214
		$config['system']['powerd_battery_mode'] = $config['system']['powerd_mode'];
3215
		unset($config['system']['powerd_mode']);
3216
	}
3217
}
3218

    
3219
function upgrade_094_to_095() {
3220
	global $config;
3221

    
3222
	if (!isset($config['interfaces']) || !is_array($config['interfaces'])) {
3223
		return;
3224
	}
3225

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

    
3235
function upgrade_095_to_096() {
3236
	global $config, $g;
3237

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

    
3243
	/* Assume 2*10GigE for now */
3244
	$stream = 2500000000;
3245

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

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

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

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

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

    
3283
function upgrade_098_to_099() {
3284
	global $config;
3285

    
3286
	if (empty($config['dhcpd']) || !is_array($config['dhcpd'])) {
3287
		return;
3288
	}
3289

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

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

    
3304
function upgrade_100_to_101() {
3305
	global $config, $g;
3306

    
3307
	if (!is_array($config['voucher'])) {
3308
		return;
3309
	}
3310

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

    
3323
function upgrade_101_to_102() {
3324
	global $config, $g;
3325

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

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

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

    
3358
function upgrade_102_to_103() {
3359
	global $config;
3360

    
3361
	if (isset($config['nat']['advancedoutbound']['enable'])) {
3362
		$config['nat']['advancedoutbound']['mode'] = "advanced";
3363
		unset($config['nat']['advancedoutbound']['enable']);
3364
	} else {
3365
		$config['nat']['advancedoutbound']['mode'] = "automatic";
3366
	}
3367

    
3368
	$config['nat']['outbound'] = $config['nat']['advancedoutbound'];
3369

    
3370
	if (isset($config['nat']['ipsecpassthru'])) {
3371
		unset($config['nat']['ipsecpassthru']);
3372
	}
3373
	if (isset($config['nat']['advancedoutbound'])) {
3374
		unset($config['nat']['advancedoutbound']);
3375
	}
3376
}
3377

    
3378
function upgrade_103_to_104() {
3379
	global $config;
3380

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

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

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

    
3412
	/* sync all local account information */
3413
	local_sync_accounts();
3414
}
3415

    
3416
function upgrade_104_to_105() {
3417
	global $config;
3418

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

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

    
3438
function upgrade_106_to_107() {
3439
	global $config;
3440

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

    
3463
function upgrade_107_to_108() {
3464
	global $config;
3465

    
3466
	if (isset($config['system']['webgui']['noautocomplete'])) {
3467
		unset($config['system']['webgui']['noautocomplete']);
3468
	} else {
3469
		$config['system']['webgui']['loginautocomplete'] = true;
3470
	}
3471
}
3472

    
3473
function upgrade_108_to_109() {
3474
	global $config;
3475

    
3476
	if (!isset($config['filter']['rule']) || !is_array($config['filter']['rule'])) {
3477
		return;
3478
	}
3479

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

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

    
3493
function upgrade_109_to_110() {
3494
	global $config;
3495

    
3496
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3497
		return;
3498
	}
3499

    
3500
	foreach ($config['ipsec']['phase2'] as &$rule) {
3501
		if (!empty($rule['uniqid'])) {
3502
			continue;
3503
		}
3504

    
3505
		$rule['uniqid'] = uniqid();
3506
	}
3507
}
3508

    
3509
function upgrade_110_to_111() {
3510
	global $config;
3511

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

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

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

    
3532
			unset($config['installedpackages']['menu'][$idx]);
3533
			break;
3534
		}
3535
	}
3536

    
3537
	if (isset($config['installedpackages']['service']) && is_array($config['installedpackages']['service'])) {
3538
		foreach ($config['installedpackages']['service'] as $idx => $service) {
3539
			if ($service['name'] != 'unbound') {
3540
				continue;
3541
			}
3542
			unset($config['installedpackages']['service'][$idx]);
3543
			break;
3544
		}
3545
	}
3546

    
3547
	if (!isset($config['installedpackages']['unbound']['config'][0])) {
3548
		return;
3549
	}
3550

    
3551
	$pkg = $config['installedpackages']['unbound']['config'][0];
3552

    
3553
	if (isset($config['installedpackages']['unboundadvanced']['config'][0])) {
3554
		$pkg = array_merge($pkg, $config['installedpackages']['unboundadvanced']['config'][0]);
3555
	}
3556

    
3557
	$new = array();
3558

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

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

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

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

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

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

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

    
3634
	$config['unbound'] = $new;
3635

    
3636
	if (isset($config['installedpackages']['unbound'])) {
3637
		unset($config['installedpackages']['unbound']);
3638
	}
3639
	if (isset($config['installedpackages']['unboundadvanced'])) {
3640
		unset($config['installedpackages']['unboundadvanced']);
3641
	}
3642
	if (isset($config['installedpackages']['unboundacls'])) {
3643
		unset($config['installedpackages']['unboundacls']);
3644
	}
3645

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

    
3649
function upgrade_111_to_112() {
3650
	global $config;
3651

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

    
3663
function upgrade_112_to_113() {
3664
	global $config;
3665

    
3666
	if (isset($config['notifications']['smtp']['ssl'])) {
3667
		if ($config['notifications']['smtp']['ssl'] == "checked") {
3668
			$config['notifications']['smtp']['ssl'] = true;
3669
		} else {
3670
			unset($config['notifications']['smtp']['ssl']);
3671
		}
3672
	}
3673

    
3674
	if (isset($config['notifications']['smtp']['tls'])) {
3675
		if ($config['notifications']['smtp']['tls'] == "checked") {
3676
			$config['notifications']['smtp']['tls'] = true;
3677
		} else {
3678
			unset($config['notifications']['smtp']['tls']);
3679
		}
3680
	}
3681
}
3682

    
3683
function upgrade_113_to_114() {
3684
	global $config;
3685

    
3686
	if (!isset($config['ipsec']['phase1']) ||
3687
	    !is_array($config['ipsec']['phase1'])) {
3688
		return;
3689
	}
3690

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

    
3698
function upgrade_114_to_115() {
3699
	global $config;
3700

    
3701
	if (isset($config['unbound']['custom_options'])) {
3702
		$config['unbound']['custom_options'] = base64_encode($config['unbound']['custom_options']);
3703
	}
3704
}
3705

    
3706
function upgrade_115_to_116() {
3707
	global $config;
3708

    
3709
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3710
		return;
3711
	}
3712

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

    
3720
function upgrade_116_to_117() {
3721
	global $config;
3722

    
3723
	if (!isset($config['ipsec']['client']) ||
3724
	    !isset($config['ipsec']['client']['dns_split']) ||
3725
	    empty($config['ipsec']['client']['dns_split'])) {
3726
		return;
3727
	}
3728

    
3729
	$config['ipsec']['client']['dns_split'] =
3730
		preg_replace('/\s*,\s*/', ' ', trim($config['ipsec']['client']['dns_split']));
3731

    
3732
}
3733

    
3734
function upgrade_117_to_118() {
3735
	global $config;
3736

    
3737
	// 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.
3738
	if (isset($config['system']['ca'])) {
3739
		unset($config['system']['ca']);
3740
	}
3741
	if (isset($config['system']['cert'])) {
3742
		unset($config['system']['cert']);
3743
	}
3744

    
3745
	if (!isset($config['ipsec']['phase1'])) {
3746
		return;
3747
	}
3748

    
3749
	$a_phase1 =& $config['ipsec']['phase1'];
3750

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

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

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

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

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

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

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

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

    
3796
}
3797

    
3798

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4029
}
4030

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

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

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

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

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

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

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

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

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

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

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

    
4105
	if (isset($config['system']['apinger_debug'])) {
4106
		unset($config['system']['apinger_debug']);
4107
	}
4108

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4375
}
4376

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

    
4381
	if (!is_array($config['dyndnses'])) {
4382
		$config['dyndnses'] = array();
4383
	}
4384
	if (!is_array($config['dyndnses']['dyndns'])) {
4385
		$config['dyndnses']['dyndns'] = array();
4386
	}
4387
	$a_dyndns = &$config['dyndnses']['dyndns'];
4388

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

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

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

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

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

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

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

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

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

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

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

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

    
4468
	return ($ipalias);
4469
}
4470

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

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

    
4483
	return ($carp);
4484
}
4485

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

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

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

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

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

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

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

    
4572
	// Enable DHCPv6 server and radvd config for track6 interfaces,
4573
	// matching what used to be automatically enabled with no user
4574
	// configurability.
4575
	if (is_array($config['interfaces'])) {
4576
		foreach ($config['interfaces'] as $ifname => $ifcfg) {
4577
			if (isset($ifcfg['enable'])) {
4578
				if ($ifcfg['ipaddrv6'] == "track6") {
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_sync_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
	if (!is_array($config['dyndnses'])) {
4954
		$config['dyndnses'] = array();
4955
	}
4956
	if (!is_array($config['dyndnses']['dyndns'])) {
4957
		$config['dyndnses']['dyndns'] = array();
4958
	}
4959
	$a_dyndns = &$config['dyndnses']['dyndns'];
4960

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

    
4972
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
4973
	if (is_array($config['cron']['item'])) {
4974
		foreach ($config['cron']['item'] as $idx => $cronitem) {
4975
			if ($cronitem['command'] == "/etc/pppoerestart") {
4976
				unset($config['cron']['item'][$idx]);
4977
			}
4978
		}
4979
	}
4980
}
4981

    
4982
function upgrade_157_to_158() {
4983
	global $config;
4984
	/* Convert Dynamic DNS passwords to base64 encoding. Redmine #6688 */
4985

    
4986
	if (!is_array($config['dyndnses'])) {
4987
		$config['dyndnses'] = array();
4988
	}
4989
	if (!is_array($config['dyndnses']['dyndns'])) {
4990
		$config['dyndnses']['dyndns'] = array();
4991
	}
4992
	$a_dyndns = &$config['dyndnses']['dyndns'];
4993

    
4994
	foreach ($a_dyndns as &$dyndns) {
4995
		$dyndns['password'] = base64_encode($dyndns['password']);
4996
	}
4997
}
4998

    
4999
/* Unset references to glxsb in the config. See #6755 */
5000
function upgrade_158_to_159() {
5001
	global $config;
5002

    
5003
	if ($config['system']['crypto_hardware'] == "glxsb") {
5004
		unset($config['system']['crypto_hardware']);
5005
	}
5006
}
5007

    
5008
/* Convert OpenVPN "protocol" to new style for OpenVPN 2.4, old udp/tcp was
5009
 * IPv4 only, now is dual stack, so change it to udp4/tcp4
5010
 */
5011
function upgrade_159_to_160() {
5012
	global $config;
5013

    
5014
	if (isset($config['openvpn']) && is_array($config['openvpn'])) {
5015
		if (is_array($config['openvpn']['openvpn-server'])) {
5016
			foreach ($config['openvpn']['openvpn-server'] 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
		if (is_array($config['openvpn']['openvpn-client'])) {
5026
			foreach ($config['openvpn']['openvpn-client'] as &$vpn) {
5027
				if ($vpn['protocol'] == "UDP") {
5028
					$vpn['protocol'] = "UDP4";
5029
				}
5030
				if ($vpn['protocol'] == "TCP") {
5031
					$vpn['protocol'] = "TCP4";
5032
				}
5033
			}
5034
		}
5035
	}
5036
}
5037

    
5038
/* RAM Disk Management */
5039
function upgrade_160_to_161() {
5040
	global $g, $config;
5041

    
5042
	if (!isset($config['system']['use_mfs_tmpvar'])) {
5043
		return;
5044
	}
5045

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

    
5052
		$rrdrestore = "";
5053
		$rrdreturn = "";
5054
		unlink_if_exists("{$rrddbpath}/*.xml");
5055

    
5056
		unset($rrdrestore);
5057
		$_gb = exec("LANG=C /usr/bin/tar -tf {$g['cf_conf_path']}/rrd.tgz", $rrdrestore, $rrdreturn);
5058
		if ($rrdreturn != 0) {
5059
			log_error(sprintf(gettext('RRD restore failed exited with %1$s, the error is: %2$s'), $rrdreturn, $rrdrestore));
5060
		} else {
5061
			foreach ($rrdrestore as $xml_file) {
5062
				$rrd_file = '/' . substr($xml_file, 0, -4) . '.rrd';
5063
				unlink_if_exists("{$rrd_file}");
5064

    
5065
				file_put_contents("{$g['tmp_path']}/rrd_restore", $xml_file);
5066
				$_gb = exec("LANG=C /usr/bin/tar -xf {$g['cf_conf_path']}/rrd.tgz -C / -T {$g['tmp_path']}/rrd_restore");
5067
				if (!file_exists("/{$xml_file}")) {
5068
					log_error(sprintf(gettext("Could not extract %s RRD xml file from archive!"), $xml_file));
5069
					continue;
5070
				}
5071
				$_gb = exec("$rrdtool restore -f '/{$xml_file}' '{$rrd_file}'", $output, $status);
5072
				if ($status) {
5073
					log_error(sprintf(gettext("rrdtool restore -f '%1\$s' '%2\$s' failed returning %3\$s."), $xml_file, $rrd_file, $status));
5074
					continue;
5075
				}
5076
				unset($output);
5077
				@unlink("/{$xml_file}");
5078
			}
5079
			unset($rrdrestore);
5080
			@unlink("{$g['tmp_path']}/rrd_restore");
5081

    
5082
			// Create a new RRD backup to the RAM Disk Store (without RRD XML dump).
5083
			exec("/etc/rc.backup_rrd.sh");
5084
			$ramds_updated = true;
5085

    
5086
			// Rename previous RRD backup so it will not restore again.  Don't delete in case needed for recovery.
5087
			rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/rrd.tgz.old");
5088
		}
5089
	}
5090

    
5091
	// Move existing DHCP leases backup to the RAM Disk Store if it don't already exist there.
5092
	if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz") && ! file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/dhcpleases.tgz")) {
5093
		rename("{$g['cf_conf_path']}/dhcpleases.tgz", "{$g['cf_conf_path']}/RAM_Disk_Store/dhcpleases.tgz");
5094
		$ramds_updated = true;
5095
	}
5096

    
5097
	// Move existing alias table backups to the RAM Disk Store if they don't already exist there.
5098
	$dbpath = "{$g['vardb_path']}/aliastables/";
5099
	$files = glob("{$g['cf_conf_path']}/RAM_Disk_Store{$dbpath}*.tgz");
5100
	if (count($files)) {
5101
		foreach ($files as $file) {
5102
			if (! file_exists("{$g['cf_conf_path']}/RAM_Disk_Store/".basename($file))) {
5103
				rename($file, "{$g['cf_conf_path']}/RAM_Disk_Store/".basename($file));
5104
				$ramds_updated = true;
5105
			}
5106
		}
5107
		// Remove existing alias table backups directory if empty.
5108
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/db/aliastables");
5109
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/db/");
5110
		@rmdir("{$g['cf_conf_path']}/RAM_Disk_Store/var/");
5111
	}
5112

    
5113
	// Restore RAM Disk Store if updated.
5114
	if ($ramds_updated) {
5115
		exec("/etc/rc.restore_ramdisk_store");
5116
	}
5117
}
5118

    
5119
/* Previous versions of pfSense had cryptodev built into the kernel.
5120
 * To retain the expected behavior on upgrade, load the cryptodev
5121
 * module for users that did not choose a module.
5122
 */
5123
function upgrade_161_to_162() {
5124
	global $config;
5125
	if (empty($config['system']['crypto_hardware'])) {
5126
		$config['system']['crypto_hardware'] = "cryptodev";
5127
	}
5128
}
5129

    
5130
/* Traffic graphs widget settings are now stored in a layout similar
5131
 * to other widgets. Migrate any old settings.
5132
 */
5133
function upgrade_162_to_163() {
5134
	require_once("ipsec.inc");
5135
	global $config;
5136

    
5137
	foreach (array('refreshinterval', 'invert', 'size', 'backgroundupdate') as $setting) {
5138
		if (isset($config['widgets']['trafficgraphs'][$setting])) {
5139
			$config['widgets']['traffic_graphs'][$setting] = $config['widgets']['trafficgraphs'][$setting];
5140
			unset($config['widgets']['trafficgraphs'][$setting]);
5141
		}
5142
	}
5143

    
5144
	if (isset($config['widgets']['trafficgraphs']['shown'])) {
5145
		if (is_array($config['widgets']['trafficgraphs']['shown']['item'])) {
5146
			$ifdescrs = get_configured_interface_with_descr();
5147

    
5148
			if (ipsec_enabled()) {
5149
				$ifdescrs['enc0'] = "IPsec";
5150
			}
5151

    
5152
			$validNames = array();
5153

    
5154
			foreach ($ifdescrs as $ifdescr => $ifname) {
5155
				array_push($validNames, $ifdescr);
5156
			}
5157

    
5158
			$config['widgets']['traffic_graphs']['filter'] = implode(',', array_diff($validNames, $config['widgets']['trafficgraphs']['shown']['item']));
5159
		}
5160

    
5161
		unset($config['widgets']['trafficgraphs']['shown']);
5162
	}
5163
}
5164

    
5165
/* Dashboard widget settings config format has changed to support having possibly multiple
5166
 * of a widget on the dashboard. Migrate any old settings.
5167
 */
5168
function convert_widget_164($oldname, $newname, $settings_keys) {
5169
	global $config;
5170

    
5171
	if ($newname == '') {
5172
		$newname = $oldname . '-0';
5173
	}
5174

    
5175
	if ($oldname == '') {
5176
		// These settings were stored directly in $config['widgets']
5177
		// Move them down under their new key.
5178
		// e.g. $config['widgets']['filterlogentries']
5179
		// becomes $config['widgets']['log-0']['filterlogentries']
5180
		foreach ($settings_keys as $oldkey => $newkey) {
5181
			if ($newkey == '') {
5182
				$newkey = $oldkey;
5183
			}
5184

    
5185
			// Modify the system-wide entry
5186
			if (isset($config['widgets'][$oldkey])) {
5187
				$config['widgets'][$newname][$newkey] = $config['widgets'][$oldkey];
5188
				unset($config['widgets'][$oldkey]);
5189
			}
5190

    
5191
			// Modify any user-specific entries
5192
			foreach ($config['system']['user'] as & $user) {
5193
				if (isset($user['widgets'][$oldkey])) {
5194
					$user['widgets'][$newname][$newkey] = $user['widgets'][$oldkey];
5195
					unset($user['widgets'][$oldkey]);
5196
				}
5197
			}
5198
		}
5199
	} else {
5200
		// These settings were stored in some key under 'widgets',
5201
		// e.g. $config['widgets']['gateways_widget']['display_type']
5202
		// becomes $config['widgets']['gateways-0']['display_type']
5203
		foreach ($settings_keys as $oldkey => $newkey) {
5204
			if ($newkey == '') {
5205
				$newkey = $oldkey;
5206
			}
5207

    
5208
			// Modify the system-wide entry
5209
			if (isset($config['widgets'][$oldname][$oldkey])) {
5210
				$config['widgets'][$newname][$newkey] = $config['widgets'][$oldname][$oldkey];
5211
				unset($config['widgets'][$oldname][$oldkey]);
5212
			}
5213

    
5214
			// Modify any user-specific entries
5215
			foreach ($config['system']['user'] as & $user) {
5216
				if (isset($user['widgets'][$oldname][$oldkey])) {
5217
					$user['widgets'][$newname][$newkey] = $user['widgets'][$oldname][$oldkey];
5218
					unset($user['widgets'][$oldname][$oldkey]);
5219
				}
5220

    
5221
				if (isset($user['widgets'][$oldname])) {
5222
					unset($user['widgets'][$oldname]);
5223
				}
5224
			}
5225
		}
5226

    
5227
		if (isset($config['widgets'][$oldname])) {
5228
			unset($config['widgets'][$oldname]);
5229
		}
5230
	}
5231
}
5232

    
5233
function upgrade_163_to_164() {
5234
	global $config;
5235

    
5236
	convert_widget_164('dyn_dns_status', '', array('filter' => ''));
5237
	convert_widget_164('gateways_widget', 'gateways-0', array('display_type' => '', 'gatewaysfilter' => ''));
5238
	convert_widget_164('interface_statistics', '', array('iffilter' => ''));
5239
	convert_widget_164('interfaces', '', array('iffilter' => ''));
5240
	convert_widget_164('', 'log-0',
5241
		array(
5242
			'filterlogentries' => '',
5243
			'filterlogentriesacts' => '',
5244
			'filterlogentriesinterfaces' => '',
5245
			'filterlogentriesinterval' => ''));
5246
	convert_widget_164('openvpn', '', array('filter' => ''));
5247
	convert_widget_164('', 'picture-0', array('picturewidget' => '', 'picturewidget_filename' => ''));
5248
	convert_widget_164('', 'rss-0', array('rssfeed' => '', 'rssmaxitems' => '', 'rsswidgetheight' => '', 'rsswidgettextlength' => ''));
5249
	convert_widget_164('', 'services_status-0', array('servicestatusfilter' => 'filter'));
5250
	convert_widget_164('smart_status', '', array('filter' => ''));
5251
	convert_widget_164('system_information', '', array('filter' => ''));
5252
	convert_widget_164('thermal_sensors_widget', 'thermal_sensors-0',
5253
		array(
5254
			'thermal_sensors_widget_zone_warning_threshold' => '',
5255
			'thermal_sensors_widget_zone_critical_threshold' => '',
5256
			'thermal_sensors_widget_core_warning_threshold' => '',
5257
			'thermal_sensors_widget_core_critical_threshold' => '',
5258
			'thermal_sensors_widget_show_raw_output' => '',
5259
			'thermal_sensors_widget_show_full_sensor_name' => '',
5260
			'thermal_sensors_widget_pulsate_warning' => '',
5261
			'thermal_sensors_widget_pulsate_critical' => ''
5262
		));
5263
	convert_widget_164('wol', 'wake_on_lan-0', array('filter' => ''));
5264
}
5265

    
5266
/* Work around broken wizard rules. See https://redmine.pfsense.org/issues/7434 */
5267
function upgrade_164_to_165() {
5268
	global $config;
5269
	foreach ($config['filter']['rule'] as & $rule) {
5270
		if ($rule['destination']['port'] == "137-139-137-139") {
5271
			$rule['destination']['port'] = "137-139";
5272
		}
5273
	}
5274
}
5275

    
5276
/* Fixup digest algorithm selection for OpenVPN clients and servers so they do not use aliased names. */
5277
function upgrade_165_to_166() {
5278
	require_once('openvpn.inc');
5279
	global $config;
5280

    
5281
	if (isset($config['openvpn']) && is_array($config['openvpn'])) {
5282
		if (is_array($config['openvpn']['openvpn-server'])) {
5283
			foreach ($config['openvpn']['openvpn-server'] as &$vpn) {
5284
				$vpn['digest'] = openvpn_remap_digest($vpn['digest']);
5285
			}
5286
		}
5287
		if (is_array($config['openvpn']['openvpn-client'])) {
5288
			foreach ($config['openvpn']['openvpn-client'] as &$vpn) {
5289
				$vpn['digest'] = openvpn_remap_digest($vpn['digest']);
5290
			}
5291
		}
5292
	}
5293
}
5294

    
5295
/* Force the Netgate Services and Support widget to be active on upgrade.
5296
   New widget is added at the top of column 2 */
5297
function upgrade_166_to_167() {
5298
	global $config;
5299

    
5300
	if (strpos($config['widgets']['sequence'],
5301
	    'netgate_services_and_support') === false) {
5302
		$widgets = explode(",", $config['widgets']['sequence']);
5303
		$cnt = count($widgets);
5304
		$col2 = $cnt;
5305
		$newsequence = array();
5306

    
5307
		// Locate the firt column 2 widget
5308
		for ($idx=0;$idx<$cnt;$idx++) {
5309
			if (strpos($widgets[$idx], 'col2') !== false) {
5310
				$col2 = $idx;
5311
				break;
5312
			}
5313
		}
5314

    
5315
		/*
5316
		 * Loop through the widgets inserting the new widget before
5317
		 * the first col2 widget
5318
		 */
5319
		for ($old=0,$new=0;$old<$cnt;$old++,$new++) {
5320
			$newsequence[$new] = $widgets[$old];
5321

    
5322
			if ($old != ($col2 - 1)) {
5323
				continue;
5324
			}
5325
			$new++;
5326
			$newsequence[$new] =
5327
			    "netgate_services_and_support:col2:open:0";
5328
		}
5329

    
5330
		$config['widgets']['sequence'] = implode(",", $newsequence);
5331
	}
5332
}
5333

    
5334
function upgrade_167_to_168() {
5335
	upgrade_166_to_167();
5336
}
5337

    
5338
function upgrade_168_to_169() {
5339
	global $config;
5340

    
5341
	/* Remove workaround added in 2.3 */
5342
	unset($config['cron']['rc_update_pkg_metadata']);
5343

    
5344
	$command = '/usr/bin/nice -n20 /etc/rc.update_pkg_metadata';
5345
	if (is_array($config['cron']['item'])) {
5346
		foreach ($config['cron']['item'] as $entry) {
5347
			if ($entry['command'] == $command) {
5348
				return;
5349
			}
5350
		}
5351
	}
5352

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

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

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

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

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

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

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

    
5443
/*
5444
 * Upgrade the VLAN interface names to use $if.$tag on PPP items
5445
 */
5446
function upgrade_172_to_173() {
5447
	global $config;
5448

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

    
5460
		$config['ppps']['ppp'][$id]['ports'] = str_replace('_vlan', '.',
5461
		    $ppp['ports']);
5462
	}
5463
}
5464

    
5465
/*
5466
 * Dynamic DNS nsupdate keyfiles have been replaced with a simpler ddns-confgen style file.
5467
 */
5468
function upgrade_173_to_174() {
5469
	global $config;
5470

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

    
5481
/*
5482
 * Special function that is called independent of current config version. It's
5483
 * a workaround to have config_upgrade running on older versions after next
5484
 * config version was already taken by newer pfSense.
5485
 *
5486
 * XXX Change the way we handle config version to make it based on product
5487
 *     version
5488
 */
5489
function additional_config_upgrade() {
5490
	global $config;
5491
}
5492

    
5493
/* IPsec Phase1 now supports multiple authentication ciphers to be specified from the webgui.
5494
 * This is usefull for mobile users using different OS's supporting different ciphers.
5495
 */
5496
function upgrade_174_to_175() {
5497
	global $config;
5498
	if (is_array($config['ipsec']['phase1'])) {
5499
		$a_phase1 = &$config['ipsec']['phase1'];
5500
		foreach($a_phase1 as &$phase1) {
5501
			$item = array();
5502
			$item['encryption-algorithm'] = $phase1['encryption-algorithm'];
5503
			$item['hash-algorithm'] = $phase1['hash-algorithm'];
5504
			$item['dhgroup'] = $phase1['dhgroup'];
5505
			$phase1['encryption']['item'][] = $item;
5506
			unset($phase1['encryption-algorithm']);
5507
			unset($phase1['hash-algorithm']);
5508
			unset($phase1['dhgroup']);
5509
		}
5510
	}
5511
}
5512
?>
(46-46/55)