Project

General

Profile

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

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

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

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

    
43
		$dmzcfg = &$config['interfaces']['dmz'];
44

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

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

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

    
59
		unset($config['interfaces']['dmz']);
60
	}
61

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

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

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

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

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

    
87
		$ifmap['wlan' . $i] = "opt" . $opti;
88

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

    
93
	/* convert filter rules */
94
	init_config_arr(array('filter', 'rule'));
95
	$n = count($config['filter']['rule']);
96
	for ($i = 0; $i < $n; $i++) {
97

    
98
		$fr = &$config['filter']['rule'][$i];
99

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

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

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

    
138
	/* convert shaper rules */
139
	init_config_arr(array('pfqueueing', 'rule'));
140
	$n = count($config['pfqueueing']['rule']);
141
	if (is_array($config['pfqueueing']['rule'])) {
142
		for ($i = 0; $i < $n; $i++) {
143

    
144
			$fr = &$config['pfqueueing']['rule'][$i];
145

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

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

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

    
186

    
187
function upgrade_011_to_012() {
188
	global $config;
189
	/* move LAN DHCP server config */
190
	$tmp = $config['dhcpd'];
191
	$config['dhcpd'] = array();
192
	$config['dhcpd']['lan'] = $tmp;
193

    
194
	/* encrypt password */
195
	$config['system']['password'] = crypt($config['system']['password']);
196
}
197

    
198

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

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

    
217

    
218
function upgrade_013_to_014() {
219
	global $config;
220
	/* convert shaper rules (make pipes) */
221
	if (is_array($config['pfqueueing']['rule'])) {
222
		init_config_arr(array('pfqueueing', 'pipe'));
223
		$config['pfqueueing']['pipe'] = array();
224

    
225
		for ($i = 0; isset($config['pfqueueing']['rule'][$i]); $i++) {
226
			$curent = &$config['pfqueueing']['rule'][$i];
227

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

    
236
			$curent['targetpipe'] = $i;
237

    
238
			unset($curent['bandwidth']);
239
			unset($curent['delay']);
240
			unset($curent['mask']);
241
		}
242
	}
243
}
244

    
245

    
246
function upgrade_014_to_015() {
247
	global $config;
248
	/* Default route moved */
249
	if (isset($config['interfaces']['wan']['gateway'])) {
250
		if ($config['interfaces']['wan']['gateway'] <> "") {
251
			$config['system']['gateway'] = $config['interfaces']['wan']['gateway'];
252
		}
253
		unset($config['interfaces']['wan']['gateway']);
254
	}
255

    
256
	/* Queues are no longer interface specific */
257
	if (isset($config['interfaces']['lan']['schedulertype'])) {
258
		unset($config['interfaces']['lan']['schedulertype']);
259
	}
260
	if (isset($config['interfaces']['wan']['schedulertype'])) {
261
		unset($config['interfaces']['wan']['schedulertype']);
262
	}
263

    
264
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) {
265
		if (isset($config['interfaces']['opt' . $i]['schedulertype'])) {
266
			unset($config['interfaces']['opt' . $i]['schedulertype']);
267
		}
268
	}
269
}
270

    
271

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

    
289

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

    
314

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

    
364
	/* enable SSH */
365
	if ($config['version'] == "1.8") {
366
		$config['system']['sshenabled'] = true;
367
	}
368
}
369

    
370

    
371
function upgrade_018_to_019() {
372
	global $config;
373
}
374

    
375

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

    
390
function upgrade_020_to_021() {
391
	global $config;
392
	/* shaper scheduler moved */
393
	if (isset($config['system']['schedulertype'])) {
394
		$config['shaper']['schedulertype'] = $config['system']['schedulertype'];
395
		unset($config['system']['schedulertype']);
396
	}
397
}
398

    
399

    
400
function upgrade_021_to_022() {
401
	global $config;
402
	/* move gateway to wan interface */
403
	$config['interfaces']['wan']['gateway'] = $config['system']['gateway'];
404
}
405

    
406
function upgrade_022_to_023() {
407
	global $config;
408
	if (isset($config['shaper'])) {
409
		/* wipe previous shaper configuration */
410
		unset($config['shaper']);
411
	}
412
}
413

    
414

    
415
function upgrade_023_to_024() {
416
	global $config;
417
}
418

    
419

    
420
function upgrade_024_to_025() {
421
	global $config;
422
	$config['interfaces']['wan']['use_rrd_gateway'] = $config['system']['use_rrd_gateway'];
423
	if (isset($config['system']['use_rrd_gateway'])) {
424
		unset($config['system']['use_rrd_gateway']);
425
	}
426
}
427

    
428

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

    
440
	$config['cron']['item'][] = $cron_item;
441

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

    
451
	$config['cron']['item'][] = $cron_item;
452

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

    
462
	$config['cron']['item'][] = $cron_item;
463

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

    
473
	$config['cron']['item'][] = $cron_item;
474

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

    
484
	$config['cron']['item'][] = $cron_item;
485

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

    
495
	$config['cron']['item'][] = $cron_item;
496

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

    
506
	$config['cron']['item'][] = $cron_item;
507
}
508

    
509

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

    
514

    
515
function upgrade_027_to_028() {
516
	global $config;
517
}
518

    
519

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

    
534

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

    
541

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

    
547

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

    
553

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

    
559

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

    
565

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

    
571

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

    
577

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

    
583

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

    
589

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

    
595

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

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

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

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

    
637
		$config['system']['nextuid'] = "111";
638
		$config['system']['nextgid'] = "111";
639

    
640
		/* wipe previous auth configuration */
641
		unset($config['system']['username']);
642
		if (isset($config['system']['password'])) {
643
			unset($config['system']['password']);
644
		}
645
	}
646
}
647

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
709
		$config['sysctl']['item'][14]['tunable'] = "net.inet.tcp.inflight.enable";
710
		$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. ");
711
		$config['sysctl']['item'][14]['value'] =   "default";
712

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

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

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

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

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

    
733
	}
734
}
735

    
736

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

    
747

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

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

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

    
801

    
802
function upgrade_043_to_044() {
803
	global $config;
804

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

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

    
843

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

    
864

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

    
948

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

    
953
	if (is_array($config['ipsec']['tunnel'])) {
954

    
955
		$a_phase1 = array();
956
		$a_phase2 = array();
957
		$ikeid = 0;
958

    
959
		foreach ($config['ipsec']['tunnel'] as $tunnel) {
960

    
961
			unset($ph1ent);
962
			unset($ph2ent);
963

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

    
969
			if (!isset($tunnel['disabled'])) {
970

    
971
				$remote_gateway = $tunnel['remote-gateway'];
972

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

    
981
			/* none found, create a new one */
982

    
983
			if (!isset($ph1ent)) {
984

    
985
				/* build new phase1 entry */
986

    
987
				$ph1ent = array();
988

    
989
				$ph1ent['ikeid'] = ++$ikeid;
990

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

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

    
1004
				$ph1ent['mode'] = $tunnel['p1']['mode'];
1005

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

    
1030
				$ph1ent['peerid_type'] = "peeraddress";
1031

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

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

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

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

    
1078
				$a_phase1[] = $ph1ent;
1079
			}
1080

    
1081
			/* build new phase2 entry */
1082

    
1083
			$ph2ent = array();
1084

    
1085
			$ph2ent['ikeid'] = $ph1ent['ikeid'];
1086

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

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

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

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

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

    
1121
			$ph2ent['protocol'] = $tunnel['p2']['protocol'];
1122

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

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

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

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

    
1161
			$a_phase2[] = $ph2ent;
1162
		}
1163

    
1164
		unset($config['ipsec']['tunnel']);
1165
		$config['ipsec']['phase1'] = $a_phase1;
1166
		$config['ipsec']['phase2'] = $a_phase2;
1167
	}
1168

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

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

    
1181
		$mobilecfg = $config['ipsec']['mobileclients'];
1182

    
1183
		$ph1ent = array();
1184
		$ph1ent['ikeid'] = ++$ikeid;
1185

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

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

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

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

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

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

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

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

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

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

    
1306
		$config['ipsec']['phase1'][] = $ph1ent;
1307
		$config['ipsec']['phase2'][] = $ph2ent;
1308
		unset($config['ipsec']['mobileclients']);
1309
	}
1310
}
1311

    
1312

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

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

    
1376

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

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

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

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

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

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

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

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

    
1444

    
1445
function upgrade_049_to_050() {
1446
	global $config;
1447

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

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

    
1488
	/* sync all local account information */
1489
	local_reset_accounts();
1490
}
1491

    
1492

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

    
1506
	if (isset($config['bridge'])) {
1507
		unset($config['bridge']);
1508
	}
1509

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

    
1535

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

    
1546
	$vpnid = 1;
1547

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

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

    
1555
			if (!is_array($server)) {
1556
				continue;
1557
			}
1558

    
1559
			if ($server['auth_method'] == "pki") {
1560

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

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

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

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

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

    
1600
				$index++;
1601
			}
1602

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

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

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

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

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

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

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

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

    
1685
			/* allocate vpnid */
1686
			$server['vpnid'] = $vpnid++;
1687

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

    
1716
			$config['openvpn']['openvpn-server'][] = $server;
1717
		}
1718
		unset($config['installedpackages']['openvpnserver']);
1719
	}
1720

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

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

    
1728
			if (!is_array($client)) {
1729
				continue;
1730
			}
1731

    
1732
			if ($client['auth_method'] == "pki") {
1733

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

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

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

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

    
1760
				$index++;
1761
			}
1762

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

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

    
1790
			/* allocate vpnid */
1791
			$client['vpnid'] = $vpnid++;
1792

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

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

    
1827
			$config['openvpn']['openvpn-client'][] = $client;
1828
		}
1829

    
1830
		unset($config['installedpackages']['openvpnclient']);
1831
	}
1832

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

    
1837
		foreach ($config['installedpackages']['openvpncsc']['config'] as $csc) {
1838

    
1839
			if (!is_array($csc)) {
1840
				continue;
1841
			}
1842

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

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

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

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

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

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

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

    
1900
			$config['openvpn']['openvpn-csc'][] = $csc;
1901
		}
1902

    
1903
		unset($config['installedpackages']['openvpncsc']);
1904
	}
1905

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

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

    
1931
}
1932

    
1933

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

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

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

    
1955
		/* create cert reference */
1956
		unset($config['system']['webgui']['certificate']);
1957
		unset($config['system']['webgui']['private-key']);
1958
		$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1959
	}
1960

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

    
1969

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

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

    
2056

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

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

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

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

    
2073
	/* Asume GigE for now */
2074
	$downstream = 125000000;
2075
	$upstream = 125000000;
2076

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2198

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

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

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

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

    
2252

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2406
}
2407

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

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

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

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

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

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

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

    
2502
			$a_ppps[] = $ppp;
2503

    
2504
		}
2505
	}
2506
}
2507

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2784
	/* Asume GigE for now */
2785
	$downstream = 125000000;
2786
	$upstream = 125000000;
2787

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2933
function upgrade_082_to_083() {
2934
	global $config;
2935

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3142
			}
3143
		}
3144
	}
3145
}
3146

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3370
	$config['nat']['outbound'] = $config['nat']['advancedoutbound'];
3371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3553
	$pkg = $config['installedpackages']['unbound']['config'][0];
3554

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

    
3559
	$new = array();
3560

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3734
}
3735

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

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

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

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

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

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

    
3770
	// change peerid_type to 'any' for EAP types to retain previous behavior of omitting rightid
3771
	init_config_arr(array('ipsec', 'phase1'));
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
	init_config_arr(array('dyndnses', 'dyndns'));
4382
	$a_dyndns = &$config['dyndnses']['dyndns'];
4383

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

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

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

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

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

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

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

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

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

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

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

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

    
4463
	return ($ipalias);
4464
}
4465

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

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

    
4478
	return ($carp);
4479
}
4480

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

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

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

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

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

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

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

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

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

    
4589
	$rrddbpath = "/var/db/rrd";
4590
	$rrdtool = "/usr/local/bin/rrdtool";
4591

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

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

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

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

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

    
4644
function upgrade_bgpd_146_to_147() {
4645
	global $config;
4646

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

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

    
4668
function upgrade_quagga_146_to_147() {
4669
	global $config;
4670

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

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

    
4692
function upgrade_146_to_147() {
4693

    
4694
	upgrade_bgpd_146_to_147();
4695
	upgrade_quagga_146_to_147();
4696
}
4697

    
4698
function upgrade_147_to_148() {
4699
	global $config;
4700

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

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

    
4725
function upgrade_148_to_149() {
4726
	global $config;
4727
	global $altq_list_queues;
4728

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

    
4732
	read_altq_config();
4733

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

    
4753
function upgrade_149_to_150() {
4754
	global $config;
4755

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

    
4767
function upgrade_150_to_151() {
4768
	global $config;
4769

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

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

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

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

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

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

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

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

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

    
4828
function upgrade_151_to_152() {
4829
	global $g, $config;
4830

    
4831
	require_once("/etc/inc/services.inc");
4832

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

    
4841
function upgrade_152_to_153() {
4842
	global $config;
4843

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

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

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

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

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

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

    
4920
	if (is_array($config['gifs']['gif'])) {
4921
		foreach ($config['gifs']['gif'] as $idx => $gif) {
4922
			if (isset($gif['link0'])) {
4923
				unset($config['gifs']['gif'][$idx]['link0']);
4924
			}
4925
		}
4926
	}
4927

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

    
4940
function upgrade_155_to_156() {
4941
	// Unused
4942
}
4943

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

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

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

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

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

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

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

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

    
4988
	if ($config['system']['crypto_hardware'] == "glxsb") {
4989
		unset($config['system']['crypto_hardware']);
4990
	}
4991
}
4992

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5122
	foreach (array('refreshinterval', 'invert', 'size', 'backgroundupdate') as $setting) {
5123
		if (isset($config['widgets']['trafficgraphs'][$setting])) {
5124
			$config['widgets']['traffic_graphs'][$setting] = $config['widgets']['trafficgraphs'][$setting];
5125
			unset($config['widgets']['trafficgraphs'][$setting]);
5126
		}
5127
	}
5128

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

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

    
5137
			$validNames = array();
5138

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

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

    
5146
		unset($config['widgets']['trafficgraphs']['shown']);
5147
	}
5148
}
5149

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

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

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

    
5170
			// Modify the system-wide entry
5171
			if (isset($config['widgets'][$oldkey])) {
5172
				$config['widgets'][$newname][$newkey] = $config['widgets'][$oldkey];
5173
				unset($config['widgets'][$oldkey]);
5174
			}
5175

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

    
5193
			// Modify the system-wide entry
5194
			if (isset($config['widgets'][$oldname][$oldkey])) {
5195
				$config['widgets'][$newname][$newkey] = $config['widgets'][$oldname][$oldkey];
5196
				unset($config['widgets'][$oldname][$oldkey]);
5197
			}
5198

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

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

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

    
5218
function upgrade_163_to_164() {
5219
	global $config;
5220

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

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

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

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

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

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

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

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

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

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

    
5319
function upgrade_167_to_168() {
5320
	upgrade_166_to_167();
5321
}
5322

    
5323
function upgrade_168_to_169() {
5324
	global $config;
5325

    
5326
	/* Remove workaround added in 2.3 */
5327
	unset($config['cron']['rc_update_pkg_metadata']);
5328

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5472
/* IPsec Phase1 now supports multiple authentication ciphers to be specified from the webgui.
5473
 * This is usefull for mobile users using different OS's supporting different ciphers.
5474
 */
5475
function upgrade_174_to_175() {
5476
	global $config;
5477
	init_config_arr(array('ipsec', 'phase1'));
5478
	if (count($config['ipsec']['phase1'])) {
5479
		$a_phase1 = &$config['ipsec']['phase1'];
5480
		foreach($a_phase1 as &$phase1) {
5481
			if (empty($phase1)) {
5482
				continue;
5483
			}
5484
			$item = array();
5485
			$item['encryption-algorithm'] = $phase1['encryption-algorithm'];
5486
			$item['hash-algorithm'] = $phase1['hash-algorithm'];
5487
			$item['dhgroup'] = $phase1['dhgroup'];
5488
			$phase1['encryption']['item'][] = $item;
5489
			unset($phase1['encryption-algorithm']);
5490
			unset($phase1['hash-algorithm']);
5491
			unset($phase1['dhgroup']);
5492
		}
5493
	}
5494
}
5495

    
5496
/* igmp always was enabled by default if settings were present.
5497
 * So enable it once on upgrade if settings are there.
5498
 * And provide the option through gui to disable it again
5499
 */
5500
function upgrade_175_to_176() {
5501
	global $config;
5502
	if (is_array($config['igmpproxy']['igmpentry']) && (count($config['igmpproxy']['igmpentry']) > 0)) {
5503
		$config['igmpproxy']['enable'] = true;
5504
	}
5505
}
5506

    
5507
/* Placeholder for a factory update. */
5508
function upgrade_176_to_177() {
5509
}
5510

    
5511
// The image displayed by the picture widget is now stored on the file system
5512
function upgrade_177_to_178() {
5513
	global $config;
5514

    
5515
	if (isset($config['widgets'])) {
5516
		$idx = 0;
5517

    
5518
		while (isset($config['widgets']['picture-' . $idx])) {
5519
			file_put_contents("/conf/widget_image.picture-" . $idx, base64_decode($config['widgets']['picture-' . $idx]['picturewidget']));
5520
			$config['widgets']['picture-' . $idx]['picturewidget'] = "/conf/widget_image.picture-". $idx;
5521
			$idx++;
5522
		}
5523
	}
5524
}
5525

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

    
5530
function upgrade_179_to_180() {
5531
	global $config, $g;
5532

    
5533
	/* Change default to 400000 to make sure bogonsv6 works */
5534
	if (empty($config['system']['maximumtableentries'])) {
5535
		$config['system']['maximumtableentries'] =
5536
		    $g['minimumtableentries_bogonsv6'];
5537
	}
5538
}
5539

    
5540
/*
5541
 * Automatically enable retrieving captive portal bandwidth limits from RADIUS for each captive portal
5542
 */
5543
function upgrade_180_to_181() {
5544
	global $config;
5545

    
5546
	if (is_array($config['captiveportal'])) {
5547
		foreach ($config['captiveportal'] as $cpzone => $cpcfg) {
5548
			if ($cpcfg['auth_method'] == "radius") {
5549
				$config['captiveportal'][$cpzone]['radiusperuserbw'] = true;
5550
			}
5551
		}
5552
	}
5553
}
5554

    
5555
function upgrade_181_to_182() {
5556
	global $config;
5557

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

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

    
5691
/* Correct gateway group trigger level values.
5692
 * See https://redmine.pfsense.org/issues/8586
5693
 */
5694
function upgrade_182_to_183() {
5695
	global $config;
5696
	if (!is_array($config['gateways']) ||
5697
	    !is_array($config['gateways']['gateway_group'])) {
5698
		/* No gateway groups, nothing to do. */
5699
		return;
5700
	}
5701
	foreach ($config['gateways']['gateway_group'] as &$gwg) {
5702
		switch ($gwg['trigger']) {
5703
			case "0":
5704
				/* '0' => gettext('Member down'), */
5705
				/* 'down' => gettext("Member Down"), */
5706
				$gwg['trigger'] = "down";
5707
				break;
5708
			case "1":
5709
				/* '1' => gettext('Packet Loss'), */
5710
				/* 'downloss' => gettext("Packet Loss"), */
5711
				$gwg['trigger'] = "downloss";
5712
				break;
5713
			case "2":
5714
				/* '2' => gettext('High Latency'), */
5715
				/* 'downlatency' => gettext("High Latency"), */
5716
				$gwg['trigger'] = "downlatency";
5717
				break;
5718
			case "3":
5719
				/* '3' => gettext('Packet Loss or High latency') */
5720
				/* 'downlosslatency' => gettext("Packet Loss or High Latency")); */
5721
				$gwg['trigger'] = "downlosslatency";
5722
				break;
5723
		}
5724
	}
5725
}
5726

    
5727
function upgrade_183_to_184() {
5728
	/* 'none' was kinda confusing and didnt really do none
5729
	 * now use the new 'automatic' mode if it was set to none. */
5730
	global $config;
5731
	if ($config['gateways']['defaultgw4'] === "-") {
5732
		$config['gateways']['defaultgw4'] = "";
5733
	}
5734
	if ($config['gateways']['defaultgw6'] === "-") {
5735
		$config['gateways']['defaultgw6'] = "";
5736
	}
5737
}
5738

    
5739
// Migrate AutoConfigBackup package settings to integtrated ACB system
5740
// and remove package
5741
function upgrade_184_to_185() {
5742
	global $config;
5743

    
5744
	if (is_array($config['installedpackages']['autoconfigbackup']['config'][0])) {
5745
		$acbpkg = &$config['installedpackages']['autoconfigbackup']['config'][0];
5746

    
5747
		init_config_arr(array('system', 'acb'));
5748
		$acb = &$config['system']['acb'];
5749
		$acb['enable'] = ($acbpkg['enable_acb'] != 'disabled') ?  'yes':'no';
5750
		$acb['gold_encryption_password'] = $acbpkg['crypto_password'];
5751

    
5752
		// If no encryption password has been set up yet, we might as well import the "Gold" password
5753
		// The user can update it later
5754
		if (!isset($acb['encryption_password'])) {
5755
			$acb['encryption_password'] = $acbpkg['crypto_password'];
5756
		}
5757

    
5758
		$acb['gold_password'] = $acbpkg['password'];
5759
		$acb['gold_username'] = $acbpkg['username'];
5760

    
5761
		unset($config['installedpackages']['autoconfigbackup']['config']);
5762
	}
5763
}
5764

    
5765
function upgrade_185_to_186() {
5766
	global $config;
5767

    
5768
	/* FEC LAGG is deprecated, replace with loadbalance */
5769
	if (!function_exists("file_notice")) {
5770
		require_once("notices.inc");
5771
	}
5772
	if (is_array($config['laggs']) &&
5773
	    is_array($config['laggs']['lagg'])) {
5774
		foreach ($config['laggs']['lagg'] as &$lagg) {
5775
			if ($lagg['proto'] == 'fec') {
5776
				$lagg['proto'] = 'failover';
5777
				file_notice("Interfaces", sprintf(gettext("The FEC LAGG protocol is deprecated. The %s LAGG interface has been set to failover."), $lagg['laggif']));
5778
			}
5779
		}
5780
	}
5781
}
5782

    
5783
function generate_usermanager_radius_config($cpzone, $counter, $protocol, $ip, $key, $port, $radiussrcip_attribute, $is_accounting=false, $accounting_port=false) {
5784
	global $config;
5785
	$pconfig = array();
5786
	
5787
	if (!is_array($config['system']['authserver'])) {
5788
		$config['system']['authserver'] = array();
5789
	}
5790
	
5791
	$pconfig['name'] = "Auto generated from Captive Portal {$cpzone}";
5792
	if ($counter != 1) {
5793
		$pconfig['name'] .= " {$counter}";
5794
	}
5795
	$pconfig['radius_srvcs'] = "auth";
5796
	$pconfig['type'] = 'radius';
5797
	$pconfig['radius_protocol'] = $protocol;
5798
	$pconfig['host'] = $ip;
5799
	$pconfig['radius_secret'] = $key;
5800
	$pconfig['radius_timeout'] = 3;
5801
	$pconfig['radius_auth_port'] = $port;
5802
	$pconfig['radius_nasip_attribute'] = $radiussrcip_attribute;
5803
	
5804
	if($is_accounting) {
5805
		$pconfig['radius_srvcs'] = "both";
5806
		$pconfig['radius_acct_port'] = $accounting_port;
5807
	}
5808
	
5809
	$config['system']['authserver'][] = $pconfig;
5810
	
5811
	return 'radius - '.$pconfig['name'];
5812
}
5813

    
5814
function upgrade_186_to_187() {
5815
	global $config;
5816
	global $g;
5817

    
5818
	if (is_array($config['captiveportal'])) {
5819
		foreach ($config['captiveportal'] as $cpzone => $cp) {
5820
			// we flush any existing sqlite3 db. 
5821
			// It will be automatically re-generated on next captiveportal_readdb()/captiveportal_writedb()
5822
			$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
5823
			unlink_if_exists($db_path);
5824
		
5825
			if ($cp['auth_method'] === 'radius') { // Radius Auth	
5826
				$auth_servers = array();
5827
				$auth_servers2 = array();
5828
				$radiuscounter = 1;
5829
				
5830
				if (intval($cp['radiusport']) == 0) {
5831
					$cp['radiusport'] = 1812;
5832
				}
5833
				if (intval($cp['radiusacctport']) == 0) {
5834
					$cp['radiusacctport'] = 1813;
5835
				}
5836
				if (!isset($cp['radiussrcip_attribute'])) {
5837
					$cp['radiussrcip_attribute'] = 'wan';
5838
				}
5839
				$auth_servers[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip'], $cp['radiuskey'], $cp['radiusport'], $cp['radiussrcip_attribute'], isset($cp['radacct_enable']), $cp['radiusacctport']);
5840
				  
5841
				if (!empty($cp['radiusip2'])) {
5842
					$radiuscounter++;
5843
					if (intval($cp['radiusport2']) == 0) {
5844
						$cp['radiusport2'] = 1812;
5845
					}		
5846
					$auth_servers[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip2'], $cp['radiuskey2'], $cp['radiusport2'], $cp['radiussrcip_attribute'], false, 0); 
5847
				}
5848
				if (!empty($cp['radiusip3'])) {
5849
					$radiuscounter++;
5850
					if (intval($cp['radiusport3']) == 0) {
5851
						$cp['radiusport3'] = 1812;
5852
					}
5853
					$auth_servers2[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip3'], $cp['radiuskey3'], $cp['radiusport3'], $cp['radiussrcip_attribute'], false, 0); 
5854
				}
5855
				if (!empty($cp['radiusip4'])) {
5856
					$radiuscounter++;
5857
					if (intval($cp['radiusport4']) == 0) {
5858
						$cp['radiusport4'] = 1812;
5859
					}
5860
					$auth_servers2[] = generate_usermanager_radius_config($cpzone, $radiuscounter, $cp['radius_protocol'], $cp['radiusip4'], $cp['radiuskey4'], $cp['radiusport4'], $cp['radiussrcip_attribute'], false, 0); 
5861
				}
5862
				
5863
				$cp['auth_method'] = 'authserver';
5864
				$cp['auth_server'] = implode(",", $auth_servers);
5865
				$cp['auth_server2'] = implode(",", $auth_servers2);
5866

    
5867
				if (isset($cp['radmac_enable'])) { // RadMac
5868
					$cp['auth_method'] = 'radmac';
5869
				}
5870
				if (isset($cp['radacct_enable'])) { // If accounting was enabled : we select the primary radius server for accounting
5871
					$cp['radacct_server'] = "Auto generated from Captive Portal {$cpzone}";
5872
					if ($cp['reauthenticateacct'] === "") {
5873
						$cp['reauthenticateacct'] = 'none';
5874
					}
5875
				}
5876
			} elseif ($cp['auth_method'] === 'local') { // Local Auth
5877
				$cp['auth_method'] = 'authserver';
5878
				$cp['auth_server'] = "Local Auth - Local Database";
5879
			} 
5880
			// we don't need to update anything when "none" auth method is selected
5881
			
5882
			$config['captiveportal'][$cpzone] = $cp;
5883
		}
5884
	}
5885
}
5886

    
5887
function upgrade_187_to_188() {
5888
	global $config;
5889

    
5890
	$old_cmd = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshlockout";
5891
	$new_cmd = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard";
5892
	if (!is_array($config['cron'])) {
5893
		$config['cron'] = array();
5894
	}
5895
	if (!is_array($config['cron']['item'])) {
5896
		$config['cron']['item'] = array();
5897
	}
5898
	if (is_array($config['cron']['item'])) {
5899
		foreach ($config['cron']['item'] as $idx => $entry) {
5900
			if ($entry['command'] == $old_cmd) {
5901
				$config['cron']['item'][$idx]['command'] = $new_cmd;
5902
				break;
5903
			}
5904
		}
5905
	}
5906
}
5907

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

    
5911
	/* Migrate ssh setting to new location */
5912
	if (isset($config['system']['enablesshd'])) {
5913
		init_config_arr(array('system', 'ssh'));
5914
		$config['system']['ssh']['enable'] = "enabled";
5915
		unset($config['system']['enablesshd']);
5916
	}
5917
	/* Remove accidentally duplicated ssh config
5918
	 * See https://redmine.pfsense.org/issues/8974 */
5919
	if (isset($config['system']['sshd'])) {
5920
		unset($config['system']['sshd']);
5921
	}
5922
}
5923

    
5924
/* Older pre-existing IPsec P1 entries may not have had the protocol explicitly
5925
 * defined. Fill in the default value of 'inet'.
5926
 * https://redmine.pfsense.org/issues/9207 */
5927
function upgrade_189_to_190() {
5928
	global $config;
5929
	init_config_arr(array('ipsec', 'phase1'));
5930
	foreach ($config['ipsec']['phase1'] as & $ph1ent) {
5931
		if (empty($ph1ent['protocol'])) {
5932
			$ph1ent['protocol'] = 'inet';
5933
		}
5934
	}
5935
}
5936

    
5937
/* sshguard cron jobs are not necessary.
5938
 * See https://redmine.pfsense.org/issues/9223 */
5939
function upgrade_190_to_191() {
5940
	global $config;
5941
	install_cron_job("/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 sshguard", false, null, null, null, null, null, null, false);
5942
	install_cron_job("/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 webConfiguratorlockout", false, null, null, null, null, null, null, false);
5943
}
5944

    
5945
/* Deprecate relayd Load Balancer
5946
 * See https://redmine.pfsense.org/issues/9386 */
5947
function upgrade_191_to_192() {
5948
	global $config;
5949

    
5950
	/* Backup LB config */
5951
	$backup_file = "/conf/deprecated_load_balancer.xml";
5952
	unlink_if_exists($backup_file);
5953
	file_put_contents($backup_file, backup_config_section('load_balancer'));
5954

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

    
5961
		if (!function_exists("file_notice")) {
5962
			require_once("notices.inc");
5963
		}
5964
		file_notice("Load Balancer", $deprecation_notice);
5965
	} else {
5966
		log_error("INFO: {$deprecation_notice}");
5967
	}
5968

    
5969
	/* Clear old config */
5970
	unset($config['load_balancer']);
5971

    
5972
	/* Remove LB HA Sync Config */
5973
	if (isset($config['hasync']) &&
5974
	    is_array($config['hasync']) &&
5975
	    isset($config['hasync']['synchronizelb'])) {
5976
		unset($config['hasync']['synchronizelb']);
5977
	}
5978
	
5979
	/* If the LB widget is present, remove it*/
5980
	if (isset($config['widgets']) &&
5981
	    isset($config['widgets']['sequence']) &&
5982
	    (strpos($config['widgets']['sequence'], 'load_balancer_status') !== false)) {
5983
		$widgets = explode(',', trim($config['widgets']['sequence']));
5984
		foreach ($widgets as $idx => &$widget) {
5985
			if (substr( $widget, 0, 20 ) === "load_balancer_status") {
5986
				unset($widgets[$idx]);
5987
			}
5988
		}
5989
		$config['widgets']['sequence'] = implode(',', $widgets);
5990
	}
5991

    
5992
	/* Per-log settings */
5993
	if (isset($config['syslog']) &&
5994
	    is_array($config['syslog']) &&
5995
	    isset($config['syslog']['relayd_settings'])) {
5996
		unset($config['syslog']['relayd_settings']);
5997
	}
5998
}
5999

    
6000
/* Deprecate growl notifications */
6001
function upgrade_192_to_193() {
6002
	global $config;
6003

    
6004
	if (isset($config['notifications']['growl'])) {
6005
		unset($config['notifications']['growl']);
6006
	}
6007
}
6008

    
6009
function upgrade_193_to_194() {
6010
	global $config, $g;
6011

    
6012
	if (is_array($config['captiveportal'])) {
6013
		foreach ($config['captiveportal'] as $cpzone => $cp) {
6014
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
6015
		}
6016
	}
6017
}
6018

    
6019
/*
6020
 * Reset all log files, including package logs, on upgrade since old logs are in
6021
 * binary clog format.
6022
 * Conversion is not possible since the clog binary will not be present.
6023
 * https://redmine.pfsense.org/issues/8350
6024
 */
6025
function upgrade_194_to_195() {
6026
	global $g;
6027

    
6028
	$logfiles = system_syslogd_get_all_logfilenames();
6029

    
6030
	foreach ($logfiles as $logfile) {
6031
		if (substr($logfile, -4) != '.log') {
6032
			$logfile .= ".log";
6033
		}
6034
		$logpath = "{$g['varlog_path']}/{$logfile}";
6035
		exec("/usr/bin/truncate -s 0 " . escapeshellarg($logpath));
6036
	}
6037
}
6038

    
6039
/* Skipped. See https://redmine.pfsense.org/issues/9730 */
6040
function upgrade_195_to_196() {
6041
}
6042

    
6043
/* Add newsyslog cron job */
6044
function upgrade_196_to_197() {
6045
	global $g, $config;
6046

    
6047
	install_cron_job('/usr/sbin/newsyslog', true, "*/1", '*', '*', '*', '*', 'root', false);
6048
}
6049

    
6050
/*
6051
 * Special function that is called independent of current config version. It's
6052
 * a workaround to have config_upgrade running on older versions after next
6053
 * config version was already taken by newer pfSense.
6054
 *
6055
 * XXX Change the way we handle config version to make it based on product
6056
 *     version
6057
 */
6058
function additional_config_upgrade() {
6059
}
6060

    
6061
?>
(51-51/59)