Project

General

Profile

Download (147 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-2016 Rubicon Communications, LLC (Netgate)
7
 * All rights reserved.
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions are met:
11
 *
12
 * 1. Redistributions of source code must retain the above copyright notice,
13
 *    this list of conditions and the following disclaimer.
14
 *
15
 * 2. Redistributions in binary form must reproduce the above copyright
16
 *    notice, this list of conditions and the following disclaimer in
17
 *    the documentation and/or other materials provided with the
18
 *    distribution.
19
 *
20
 * 3. All advertising materials mentioning features or use of this software
21
 *    must display the following acknowledgment:
22
 *    "This product includes software developed by the pfSense Project
23
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
24
 *
25
 * 4. The names "pfSense" and "pfSense Project" must not be used to
26
 *    endorse or promote products derived from this software without
27
 *    prior written permission. For written permission, please contact
28
 *    coreteam@pfsense.org.
29
 *
30
 * 5. Products derived from this software may not be called "pfSense"
31
 *    nor may "pfSense" appear in their names without prior written
32
 *    permission of the Electric Sheep Fencing, LLC.
33
 *
34
 * 6. Redistributions of any form whatsoever must retain the following
35
 *    acknowledgment:
36
 *
37
 * "This product includes software developed by the pfSense Project
38
 * for use in the pfSense software distribution (http://www.pfsense.org/).
39
 *
40
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
41
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
44
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51
 * OF THE POSSIBILITY OF SUCH DAMAGE.
52
 */
53

    
54
if (!function_exists("dump_rrd_to_xml")) {
55
	require_once("rrd.inc");
56
}
57
if (!function_exists("read_altq_config")) {
58
	require_once("shaper.inc");
59
}
60

    
61
/* Upgrade functions must be named:
62
*    upgrade_XXX_to_YYY
63
	* where XXX == previous version, zero padded, and YYY == next version, zero padded
64
	*/
65
function upgrade_010_to_011() {
66
	global $config;
67
	$opti = 1;
68
	$ifmap = array('lan' => 'lan', 'wan' => 'wan', 'pptp' => 'pptp');
69

    
70
	/* convert DMZ to optional, if necessary */
71
	if (isset($config['interfaces']['dmz'])) {
72

    
73
		$dmzcfg = &$config['interfaces']['dmz'];
74

    
75
		if ($dmzcfg['if']) {
76
			$config['interfaces']['opt' . $opti] = array();
77
			$optcfg = &$config['interfaces']['opt' . $opti];
78

    
79
			$optcfg['enable'] = $dmzcfg['enable'];
80
			$optcfg['descr'] = "DMZ";
81
			$optcfg['if'] = $dmzcfg['if'];
82
			$optcfg['ipaddr'] = $dmzcfg['ipaddr'];
83
			$optcfg['subnet'] = $dmzcfg['subnet'];
84

    
85
			$ifmap['dmz'] = "opt" . $opti;
86
			$opti++;
87
		}
88

    
89
		unset($config['interfaces']['dmz']);
90
	}
91

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

    
95
		if (!$config['interfaces']['wlan' . $i]['if']) {
96
			unset($config['interfaces']['wlan' . $i]);
97
			continue;
98
		}
99

    
100
		$wlancfg = &$config['interfaces']['wlan' . $i];
101
		$config['interfaces']['opt' . $opti] = array();
102
		$optcfg = &$config['interfaces']['opt' . $opti];
103

    
104
		$optcfg['enable'] = $wlancfg['enable'];
105
		$optcfg['descr'] = "WLAN" . $i;
106
		$optcfg['if'] = $wlancfg['if'];
107
		$optcfg['ipaddr'] = $wlancfg['ipaddr'];
108
		$optcfg['subnet'] = $wlancfg['subnet'];
109
		$optcfg['bridge'] = $wlancfg['bridge'];
110

    
111
		$optcfg['wireless'] = array();
112
		$optcfg['wireless']['mode'] = $wlancfg['mode'];
113
		$optcfg['wireless']['ssid'] = $wlancfg['ssid'];
114
		$optcfg['wireless']['channel'] = $wlancfg['channel'];
115
		$optcfg['wireless']['wep'] = $wlancfg['wep'];
116

    
117
		$ifmap['wlan' . $i] = "opt" . $opti;
118

    
119
		unset($config['interfaces']['wlan' . $i]);
120
		$opti++;
121
	}
122

    
123
	/* convert filter rules */
124
	$n = count($config['filter']['rule']);
125
	for ($i = 0; $i < $n; $i++) {
126

    
127
		$fr = &$config['filter']['rule'][$i];
128

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

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

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

    
167
	/* convert shaper rules */
168
	$n = count($config['pfqueueing']['rule']);
169
	if (is_array($config['pfqueueing']['rule'])) {
170
		for ($i = 0; $i < $n; $i++) {
171

    
172
			$fr = &$config['pfqueueing']['rule'][$i];
173

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

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

    
198
			/* remap destination network */
199
			if (isset($fr['destination']['network'])) {
200
				if (array_key_exists($fr['destination']['network'], $ifmap)) {
201
					$fr['destination']['network'] = $ifmap[$fr['destination']['network']];
202
				} else {
203
					/* remove the rule */
204
					printf(gettext("%sWarning: traffic shaper rule removed " .
205
						"(destination network '%s' does not exist anymore)."), "\n", $fr['destination']['network']);
206
					unset($config['pfqueueing']['rule'][$i]);
207
					continue;
208
				}
209
			}
210
		}
211
	}
212
}
213

    
214

    
215
function upgrade_011_to_012() {
216
	global $config;
217
	/* move LAN DHCP server config */
218
	$tmp = $config['dhcpd'];
219
	$config['dhcpd'] = array();
220
	$config['dhcpd']['lan'] = $tmp;
221

    
222
	/* encrypt password */
223
	$config['system']['password'] = crypt($config['system']['password']);
224
}
225

    
226

    
227
function upgrade_012_to_013() {
228
	global $config;
229
	/* convert advanced outbound NAT config */
230
	for ($i = 0; isset($config['nat']['advancedoutbound']['rule'][$i]); $i++) {
231
		$curent = &$config['nat']['advancedoutbound']['rule'][$i];
232
		$src = $curent['source'];
233
		$curent['source'] = array();
234
		$curent['source']['network'] = $src;
235
		$curent['destination'] = array();
236
		$curent['destination']['any'] = true;
237
	}
238

    
239
	/* add an explicit type="pass" to all filter rules to make things consistent */
240
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++) {
241
		$config['filter']['rule'][$i]['type'] = "pass";
242
	}
243
}
244

    
245

    
246
function upgrade_013_to_014() {
247
	global $config;
248
	/* convert shaper rules (make pipes) */
249
	if (is_array($config['pfqueueing']['rule'])) {
250
		$config['pfqueueing']['pipe'] = array();
251

    
252
		for ($i = 0; isset($config['pfqueueing']['rule'][$i]); $i++) {
253
			$curent = &$config['pfqueueing']['rule'][$i];
254

    
255
			/* make new pipe and associate with this rule */
256
			$newpipe = array();
257
			$newpipe['descr'] = $curent['descr'];
258
			$newpipe['bandwidth'] = $curent['bandwidth'];
259
			$newpipe['delay'] = $curent['delay'];
260
			$newpipe['mask'] = $curent['mask'];
261
			$config['pfqueueing']['pipe'][$i] = $newpipe;
262

    
263
			$curent['targetpipe'] = $i;
264

    
265
			unset($curent['bandwidth']);
266
			unset($curent['delay']);
267
			unset($curent['mask']);
268
		}
269
	}
270
}
271

    
272

    
273
function upgrade_014_to_015() {
274
	global $config;
275
	/* Default route moved */
276
	if (isset($config['interfaces']['wan']['gateway'])) {
277
		if ($config['interfaces']['wan']['gateway'] <> "") {
278
			$config['system']['gateway'] = $config['interfaces']['wan']['gateway'];
279
		}
280
		unset($config['interfaces']['wan']['gateway']);
281
	}
282

    
283
	/* Queues are no longer interface specific */
284
	if (isset($config['interfaces']['lan']['schedulertype'])) {
285
		unset($config['interfaces']['lan']['schedulertype']);
286
	}
287
	if (isset($config['interfaces']['wan']['schedulertype'])) {
288
		unset($config['interfaces']['wan']['schedulertype']);
289
	}
290

    
291
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) {
292
		if (isset($config['interfaces']['opt' . $i]['schedulertype'])) {
293
			unset($config['interfaces']['opt' . $i]['schedulertype']);
294
		}
295
	}
296
}
297

    
298

    
299
function upgrade_015_to_016() {
300
	global $config;
301
	/* Alternate firmware URL moved */
302
	if (isset($config['system']['firmwareurl']) && isset($config['system']['firmwarename'])) { // Only convert if *both* are defined.
303
		$config['system']['alt_firmware_url'] = array();
304
		$config['system']['alt_firmware_url']['enabled'] = "";
305
		$config['system']['alt_firmware_url']['firmware_base_url'] = $config['system']['firmwareurl'];
306
		$config['system']['alt_firmware_url']['firmware_filename'] = $config['system']['firmwarename'];
307
	}
308
	if (isset($config['system']['firmwareurl'])) {
309
		unset($config['system']['firmwareurl']);
310
	}
311
	if (isset($config['system']['firmwarename'])) {
312
		unset($config['system']['firmwarename']);
313
	}
314
}
315

    
316

    
317
function upgrade_016_to_017() {
318
	global $config;
319
	/* wipe previous shaper configuration */
320
	if (isset($config['shaper']['queue'])) {
321
		unset($config['shaper']['queue']);
322
	}
323
	if (isset($config['shaper']['rule'])) {
324
		unset($config['shaper']['rule']);
325
	}
326
	if (isset($config['interfaces']['wan']['bandwidth'])) {
327
		unset($config['interfaces']['wan']['bandwidth']);
328
	}
329
	if (isset($config['interfaces']['wan']['bandwidthtype'])) {
330
		unset($config['interfaces']['wan']['bandwidthtype']);
331
	}
332
	if (isset($config['interfaces']['lan']['bandwidth'])) {
333
		unset($config['interfaces']['lan']['bandwidth']);
334
	}
335
	if (isset($config['interfaces']['lan']['bandwidthtype'])) {
336
		unset($config['interfaces']['lan']['bandwidthtype']);
337
	}
338
	$config['shaper']['enable'] = FALSE;
339
}
340

    
341

    
342
function upgrade_017_to_018() {
343
	global $config;
344
	if (isset($config['proxyarp']) && is_array($config['proxyarp']['proxyarpnet'])) {
345
		$proxyarp = &$config['proxyarp']['proxyarpnet'];
346
		foreach ($proxyarp as $arpent) {
347
			$vip = array();
348
			$vip['mode'] = "proxyarp";
349
			$vip['interface'] = $arpent['interface'];
350
			$vip['descr'] = $arpent['descr'];
351
			if (isset($arpent['range'])) {
352
				$vip['range'] = $arpent['range'];
353
				$vip['type'] = "range";
354
			} else {
355
				$subnet = explode('/', $arpent['network']);
356
				$vip['subnet'] = $subnet[0];
357
				if (isset($subnet[1])) {
358
					$vip['subnet_bits'] = $subnet[1];
359
					$vip['type'] = "network";
360
				} else {
361
					$vip['subnet_bits'] = "32";
362
					$vip['type'] = "single";
363
				}
364
			}
365
			$config['virtualip']['vip'][] = $vip;
366
		}
367
		unset($config['proxyarp']);
368
	}
369
	if (isset($config['installedpackages']) && isset($config['installedpackages']['carp']) && is_array($config['installedpackages']['carp']['config'])) {
370
		$carp = &$config['installedpackages']['carp']['config'];
371
		foreach ($carp as $carpent) {
372
			$vip = array();
373
			$vip['mode'] = "carp";
374
			$vip['interface'] = "AUTO";
375
			$vip['descr'] = sprintf(gettext("CARP vhid %s"), $carpent['vhid']);
376
			$vip['type'] = "single";
377
			$vip['vhid'] = $carpent['vhid'];
378
			$vip['advskew'] = $carpent['advskew'];
379
			$vip['password'] = $carpent['password'];
380
			$vip['subnet'] = $carpent['ipaddress'];
381
			$vip['subnet_bits'] = $carpent['netmask'];
382
			$config['virtualip']['vip'][] = $vip;
383
		}
384
		unset($config['installedpackages']['carp']);
385
	}
386
	/* Server NAT is no longer needed */
387
	if (isset($config['nat']['servernat'])) {
388
		unset($config['nat']['servernat']);
389
	}
390

    
391
	/* enable SSH */
392
	if ($config['version'] == "1.8") {
393
		$config['system']['sshenabled'] = true;
394
	}
395
}
396

    
397

    
398
function upgrade_018_to_019() {
399
	global $config;
400
}
401

    
402

    
403
function upgrade_019_to_020() {
404
	global $config;
405
	if (is_array($config['ipsec']['tunnel'])) {
406
		reset($config['ipsec']['tunnel']);
407
		while (list($index, $tunnel) = each($config['ipsec']['tunnel'])) {
408
			/* Sanity check on required variables */
409
			/* This fixes bogus <tunnel> entries - remnant of bug #393 */
410
			if (!isset($tunnel['local-subnet']) && !isset($tunnel['remote-subnet'])) {
411
				unset($config['ipsec']['tunnel'][$tunnel]);
412
			}
413
		}
414
	}
415
}
416

    
417
function upgrade_020_to_021() {
418
	global $config;
419
	/* shaper scheduler moved */
420
	if (isset($config['system']['schedulertype'])) {
421
		$config['shaper']['schedulertype'] = $config['system']['schedulertype'];
422
		unset($config['system']['schedulertype']);
423
	}
424
}
425

    
426

    
427
function upgrade_021_to_022() {
428
	global $config;
429
	/* move gateway to wan interface */
430
	$config['interfaces']['wan']['gateway'] = $config['system']['gateway'];
431
}
432

    
433
function upgrade_022_to_023() {
434
	global $config;
435
	if (isset($config['shaper'])) {
436
		/* wipe previous shaper configuration */
437
		unset($config['shaper']);
438
	}
439
}
440

    
441

    
442
function upgrade_023_to_024() {
443
	global $config;
444
}
445

    
446

    
447
function upgrade_024_to_025() {
448
	global $config;
449
	$config['interfaces']['wan']['use_rrd_gateway'] = $config['system']['use_rrd_gateway'];
450
	if (isset($config['system']['use_rrd_gateway'])) {
451
		unset($config['system']['use_rrd_gateway']);
452
	}
453
}
454

    
455

    
456
function upgrade_025_to_026() {
457
	global $config;
458
	$cron_item = array();
459
	$cron_item['minute'] = "0";
460
	$cron_item['hour'] = "*";
461
	$cron_item['mday'] = "*";
462
	$cron_item['month'] = "*";
463
	$cron_item['wday'] = "*";
464
	$cron_item['who'] = "root";
465
	$cron_item['command'] = "/usr/bin/nice -n20 newsyslog";
466

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

    
469
	$cron_item = array();
470
	$cron_item['minute'] = "1,31";
471
	$cron_item['hour'] = "0-5";
472
	$cron_item['mday'] = "*";
473
	$cron_item['month'] = "*";
474
	$cron_item['wday'] = "*";
475
	$cron_item['who'] = "root";
476
	$cron_item['command'] = "/usr/bin/nice -n20 adjkerntz -a";
477

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

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

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

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

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

    
502
	$cron_item = array();
503
	$cron_item['minute'] = "1";
504
	$cron_item['hour'] = "1";
505
	$cron_item['mday'] = "*";
506
	$cron_item['month'] = "*";
507
	$cron_item['wday'] = "*";
508
	$cron_item['who'] = "root";
509
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.dyndns.update";
510

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

    
513
	$cron_item = array();
514
	$cron_item['minute'] = "*/60";
515
	$cron_item['hour'] = "*";
516
	$cron_item['mday'] = "*";
517
	$cron_item['month'] = "*";
518
	$cron_item['wday'] = "*";
519
	$cron_item['who'] = "root";
520
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 virusprot";
521

    
522
	$config['cron']['item'][] = $cron_item;
523

    
524
	$cron_item = array();
525
	$cron_item['minute'] = "*/60";
526
	$cron_item['hour'] = "*";
527
	$cron_item['mday'] = "*";
528
	$cron_item['month'] = "*";
529
	$cron_item['wday'] = "*";
530
	$cron_item['who'] = "root";
531
	$cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -t 1800 snort2c";
532

    
533
	$config['cron']['item'][] = $cron_item;
534
}
535

    
536

    
537
function upgrade_026_to_027() {
538
	global $config;
539
}
540

    
541

    
542
function upgrade_027_to_028() {
543
	global $config;
544
}
545

    
546

    
547
function upgrade_028_to_029() {
548
	global $config;
549
	$rule_item = array();
550
	$a_filter = &$config['filter']['rule'];
551
	$rule_item['interface'] = "enc0";
552
	$rule_item['type'] = "pass";
553
	$rule_item['source']['any'] = true;
554
	$rule_item['destination']['any'] = true;
555
	$rule_item['descr'] = gettext("Permit IPsec traffic.");
556
	$rule_item['statetype'] = "keep state";
557
	$a_filter[] = $rule_item;
558
}
559

    
560

    
561
function upgrade_029_to_030() {
562
	global $config;
563
	/* enable the rrd config setting by default */
564
	$config['rrd']['enable'] = true;
565
}
566

    
567

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

    
573

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

    
579

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

    
585

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

    
591

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

    
597

    
598
function upgrade_035_to_036() {
599
	global $config;
600
	/* Insert upgrade code here */
601
}
602

    
603

    
604
function upgrade_036_to_037() {
605
	global $config;
606
	/* Insert upgrade code here */
607
}
608

    
609

    
610
function upgrade_037_to_038() {
611
	global $config;
612
	/* Insert upgrade code here */
613
}
614

    
615

    
616
function upgrade_038_to_039() {
617
	global $config;
618
	/* Insert upgrade code here */
619
}
620

    
621

    
622
function upgrade_039_to_040() {
623
	global $config, $g;
624
	$config['system']['webgui']['auth_method'] = "session";
625
	$config['system']['webgui']['backing_method'] = "htpasswd";
626

    
627
	if (isset($config['system']['username'])) {
628
		$config['system']['group'] = array();
629
		$config['system']['group'][0]['name'] = "admins";
630
		$config['system']['group'][0]['description'] = gettext("System Administrators");
631
		$config['system']['group'][0]['scope'] = "system";
632
		$config['system']['group'][0]['priv'] = "page-all";
633
		$config['system']['group'][0]['home'] = "index.php";
634
		$config['system']['group'][0]['gid'] = "110";
635

    
636
		$config['system']['user'] = array();
637
		$config['system']['user'][0]['name'] = "{$config['system']['username']}";
638
		$config['system']['user'][0]['descr'] = "System Administrator";
639
		$config['system']['user'][0]['scope'] = "system";
640
		$config['system']['user'][0]['groupname'] = "admins";
641
		$config['system']['user'][0]['password'] = "{$config['system']['password']}";
642
		$config['system']['user'][0]['uid'] = "0";
643
		/* Ensure that we follow what this new "admin" username should be in the session. */
644
		$_SESSION["Username"] = "{$config['system']['username']}";
645

    
646
		$config['system']['user'][0]['priv'] = array();
647
		$config['system']['user'][0]['priv'][0]['id'] = "lockwc";
648
		$config['system']['user'][0]['priv'][0]['name'] = "Lock webConfigurator";
649
		$config['system']['user'][0]['priv'][0]['descr'] = gettext("Indicates whether this user will lock access to the webConfigurator for other users.");
650
		$config['system']['user'][0]['priv'][1]['id'] = "lock-ipages";
651
		$config['system']['user'][0]['priv'][1]['name'] = "Lock individual pages";
652
		$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).");
653
		$config['system']['user'][0]['priv'][2]['id'] = "hasshell";
654
		$config['system']['user'][0]['priv'][2]['name'] = "Has shell access";
655
		$config['system']['user'][0]['priv'][2]['descr'] = gettext("Indicates whether this user is able to login for example via SSH.");
656
		$config['system']['user'][0]['priv'][3]['id'] = "copyfiles";
657
		$config['system']['user'][0]['priv'][3]['name'] = "Is allowed to copy files";
658
		$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']);
659
		$config['system']['user'][0]['priv'][4]['id'] = "isroot";
660
		$config['system']['user'][0]['priv'][4]['name'] = "Is root user";
661
		$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).");
662

    
663
		$config['system']['nextuid'] = "111";
664
		$config['system']['nextgid'] = "111";
665

    
666
		/* wipe previous auth configuration */
667
		unset($config['system']['username']);
668
		if (isset($config['system']['password'])) {
669
			unset($config['system']['password']);
670
		}
671
	}
672
}
673

    
674
function upgrade_040_to_041() {
675
	global $config;
676
	if (!$config['sysctl']) {
677
		$config['sysctl']['item'] = array();
678

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

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

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

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

    
695
		$config['sysctl']['item'][4]['tunable'] = "net.inet.ip.redirect";
696
		$config['sysctl']['item'][4]['descr'] =    gettext("Sending of IPv4 ICMP redirects");
697
		$config['sysctl']['item'][4]['value'] =   "default";
698

    
699
		$config['sysctl']['item'][5]['tunable'] = "net.inet6.ip6.redirect";
700
		$config['sysctl']['item'][5]['descr'] =    gettext("Sending of IPv6 ICMP redirects");
701
		$config['sysctl']['item'][5]['value'] =   "default";
702

    
703
		$config['sysctl']['item'][6]['tunable'] = "net.inet.tcp.syncookies";
704
		$config['sysctl']['item'][6]['descr'] =    gettext("Generate SYN cookies for outbound SYN-ACK packets");
705
		$config['sysctl']['item'][6]['value'] =   "default";
706

    
707
		$config['sysctl']['item'][7]['tunable'] = "net.inet.tcp.recvspace";
708
		$config['sysctl']['item'][7]['descr'] =    gettext("Maximum incoming TCP datagram size");
709
		$config['sysctl']['item'][7]['value'] =   "default";
710

    
711
		$config['sysctl']['item'][8]['tunable'] = "net.inet.tcp.sendspace";
712
		$config['sysctl']['item'][8]['descr'] =    gettext("Maximum outgoing TCP datagram size");
713
		$config['sysctl']['item'][8]['value'] =   "default";
714

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

    
719
		$config['sysctl']['item'][10]['tunable'] = "net.inet.udp.maxdgram";
720
		$config['sysctl']['item'][10]['descr'] =    gettext("Maximum outgoing UDP datagram size");
721
		$config['sysctl']['item'][10]['value'] =   "default";
722

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

    
727
		$config['sysctl']['item'][12]['tunable'] = "net.link.tap.user_open";
728
		$config['sysctl']['item'][12]['descr'] =    gettext("Allow unprivileged access to tap(4) device nodes");
729
		$config['sysctl']['item'][12]['value'] =   "default";
730

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

    
735
		$config['sysctl']['item'][14]['tunable'] = "net.inet.tcp.inflight.enable";
736
		$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. ");
737
		$config['sysctl']['item'][14]['value'] =   "default";
738

    
739
		$config['sysctl']['item'][15]['tunable'] = "net.inet.icmp.icmplim";
740
		$config['sysctl']['item'][15]['descr'] =    gettext("Set ICMP Limits");
741
		$config['sysctl']['item'][15]['value'] =   "default";
742

    
743
		$config['sysctl']['item'][16]['tunable'] = "net.inet.tcp.tso";
744
		$config['sysctl']['item'][16]['descr'] =    gettext("TCP Offload engine");
745
		$config['sysctl']['item'][16]['value'] =   "default";
746

    
747
		$config['sysctl']['item'][17]['tunable'] = "net.inet.ip.portrange.first";
748
		$config['sysctl']['item'][17]['descr'] =    "Set the ephemeral port range starting port";
749
		$config['sysctl']['item'][17]['value'] =   "default";
750

    
751
		$config['sysctl']['item'][18]['tunable'] = "hw.syscons.kbd_reboot";
752
		$config['sysctl']['item'][18]['descr'] =    "Enables ctrl+alt+delete";
753
		$config['sysctl']['item'][18]['value'] =   "default";
754

    
755
		$config['sysctl']['item'][19]['tunable'] = "kern.ipc.maxsockbuf";
756
		$config['sysctl']['item'][19]['descr'] =    "Maximum socket buffer size";
757
		$config['sysctl']['item'][19]['value'] =   "default";
758

    
759
	}
760
}
761

    
762

    
763
function upgrade_041_to_042() {
764
	global $config;
765
	if (isset($config['shaper'])) {
766
		unset($config['shaper']);
767
	}
768
	if (isset($config['ezshaper'])) {
769
		unset($config['ezshaper']);
770
	}
771
}
772

    
773

    
774
function upgrade_042_to_043() {
775
	global $config;
776
	/* migrate old interface gateway to the new gateways config */
777
	$iflist = get_configured_interface_list(false, true);
778
	$gateways = array();
779
	$i = 0;
780
	foreach ($iflist as $ifname => $interface) {
781
		if (!interface_has_gateway($ifname)) {
782
			continue;
783
		}
784
		$config['gateways']['gateway_item'][$i] = array();
785
		if (is_ipaddr($config['interfaces'][$ifname]['gateway'])) {
786
			$config['gateways']['gateway_item'][$i]['gateway'] = $config['interfaces'][$ifname]['gateway'];
787
			$config['gateways']['gateway_item'][$i]['descr'] = sprintf(gettext("Interface %s Static Gateway"), $ifname);
788
		} else {
789
			$config['gateways']['gateway_item'][$i]['gateway'] = "dynamic";
790
			$config['gateways']['gateway_item'][$i]['descr'] = sprintf(gettext("Interface %s Dynamic Gateway"), $ifname);
791
		}
792
		$config['gateways']['gateway_item'][$i]['interface'] = $ifname;
793
		$config['gateways']['gateway_item'][$i]['name'] = "GW_" . strtoupper($ifname);
794
		/* add default gateway bit for wan on upgrade */
795
		if ($ifname == "wan") {
796
			$config['gateways']['gateway_item'][$i]['defaultgw'] = true;
797
		}
798
		if (is_ipaddr($config['interfaces'][$ifname]['use_rrd_gateway'])) {
799
			$config['gateways']['gateway_item'][$i]['monitor'] = $config['interfaces'][$ifname]['use_rrd_gateway'];
800
			unset($config['interfaces'][$ifname]['use_rrd_gateway']);
801
		}
802
		$config['interfaces'][$ifname]['gateway'] = $config['gateways']['gateway_item'][$i]['name'];
803

    
804
		/* Update all filter rules which might reference this gateway */
805
		$j = 0;
806
		foreach ($config['filter']['rule'] as $rule) {
807
			if (is_ipaddr($rule['gateway'])) {
808
				if ($rule['gateway'] == $config['gateways']['gateway_item'][$i]['gateway']) {
809
					$config['filter']['rule'][$j]['gateway'] = $config['gateways']['gateway_item'][$i]['name'];
810
				} else if ($rule['gateway'] == $ifname) {
811
					$config['filter']['rule'][$j]['gateway'] = $config['gateways']['gateway_item'][$i]['name'];
812
				}
813
			}
814
			$j++;
815
		}
816

    
817
		/* rename old Quality RRD files in the process */
818
		$rrddbpath = "/var/db/rrd";
819
		$gwname = "GW_" . strtoupper($ifname);
820
		if (is_readable("{$rrddbpath}/{$ifname}-quality.rrd")) {
821
			rename("{$rrddbpath}/{$ifname}-quality.rrd", "{$rrddbpath}/{$gwname}-quality.rrd");
822
		}
823
		$i++;
824
	}
825
}
826

    
827

    
828
function upgrade_043_to_044() {
829
	global $config;
830

    
831
	/* migrate static routes to the new gateways config */
832
	$gateways = return_gateways_array(true);
833
	$i = 0;
834
	if (is_array($config['staticroutes']['route'])) {
835
		$gwmap = array();
836
		foreach ($config['staticroutes']['route'] as $idx => $sroute) {
837
			$found = false;
838
			foreach ($gateways as $gwname => $gw) {
839
				if ($gw['gateway'] == $sroute['gateway']) {
840
					$config['staticroutes']['route'][$idx]['gateway'] = $gwname;
841
					$found = true;
842
					break;
843
				}
844
			}
845
			if ($gwmap[$sroute['gateway']]) {
846
				/* We already added a gateway name for this IP */
847
				$config['staticroutes']['route'][$idx]['gateway'] = "{$gwmap[$sroute['gateway']]}";
848
				$found = true;
849
			}
850

    
851
			if ($found == false) {
852
				$gateway = array();
853
				$gateway['name'] = "SROUTE{$i}";
854
				$gwmap[$sroute['gateway']] = $gateway['name'];
855
				$gateway['gateway'] = $sroute['gateway'];
856
				$gateway['interface'] = $sroute['interface'];
857
				$gateway['descr'] = sprintf(gettext("Upgraded static route for %s"), $sroute['network']);
858
				if (!is_array($config['gateways']['gateway_item'])) {
859
					$config['gateways']['gateway_item'] = array();
860
				}
861
				$config['gateways']['gateway_item'][] = $gateway;
862
				$config['staticroutes']['route'][$idx]['gateway'] = $gateway['name'];
863
				$i++;
864
			}
865
		}
866
	}
867
}
868

    
869

    
870
function upgrade_044_to_045() {
871
	global $config;
872
	$iflist = get_configured_interface_list(false, true);
873
	if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
874
		$i = 0;
875
		foreach ($config['vlans']['vlan'] as $id => $vlan) {
876
			/* Make sure to update the interfaces section with the right name */
877
			$vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}";
878
			foreach ($iflist as $ifname) {
879
				if ($config['interfaces'][$ifname]['if'] == "vlan{$i}") {
880
					$config['interfaces'][$ifname]['if'] = $vlan_name;
881
					continue;
882
				}
883
			}
884
			$config['vlans']['vlan'][$i]['vlanif'] = "{$vlan_name}";
885
			$i++;
886
		}
887
	}
888
}
889

    
890

    
891
function upgrade_045_to_046() {
892
	global $config;
893
	/* Load up monitors that are in the default config for 2.0 but not in 1.2.3
894
		thus wouldn't be in an upgraded config. */
895
	$config['load_balancer']['monitor_type'] = array (
896
		array ('name' => 'ICMP',
897
			'type' => 'icmp',
898
			'descr' => 'ICMP',
899
			'options' => '',
900
		),
901
		array ('name' => 'TCP',
902
			'type' => 'tcp',
903
			'descr' => 'Generic TCP',
904
			'options' => '',
905
		),
906
		array ('name' => 'HTTP',
907
			'type' => 'http',
908
			'descr' => 'Generic HTTP',
909
			'options' =>
910
			array ('path' => '/',
911
				'host' => '',
912
				'code' => '200',
913
			),
914
		),
915
		array ('name' => 'HTTPS',
916
			'type' => 'https',
917
			'descr' => 'Generic HTTPS',
918
			'options' =>
919
			array ('path' => '/',
920
				'host' => '',
921
				'code' => '200',
922
			),
923
		),
924
		array ('name' => 'SMTP',
925
			'type' => 'send',
926
			'descr' => 'Generic SMTP',
927
			'options' =>
928
			array ('send' => '',
929
				'expect' => '220 *',
930
			),
931
		),
932
	);
933
	/* Upgrade load balancer from slb to relayd */
934
	if (is_array($config['load_balancer']['virtual_server']) && count($config['load_balancer']['virtual_server'])) {
935
		$vs_a = &$config['load_balancer']['virtual_server'];
936
		$pool_a = &$config['load_balancer']['lbpool'];
937
		$pools = array();
938
		/* Index pools by name */
939
		if (is_array($pool_a)) {
940
			for ($i = 0; isset($pool_a[$i]); $i++) {
941
				if ($pool_a[$i]['type'] == "server") {
942
					$pools[$pool_a[$i]['name']] = $pool_a[$i];
943
				}
944
			}
945
		}
946
		/* Convert sitedown entries to pools and re-attach */
947
		for ($i = 0; isset($vs_a[$i]); $i++) {
948
			/* Set mode while we're here. */
949
			$vs_a[$i]['mode'] = "redirect_mode";
950
			if (isset($vs_a[$i]['sitedown'])) {
951
				$pool = array();
952
				$pool['type'] = 'server';
953
				$pool['behaviour'] = 'balance';
954
				$pool['name'] = "{$vs_a[$i]['name']}-sitedown";
955
				$pool['descr'] = sprintf(gettext("Sitedown pool for VS: %s"), $vs_a[$i]['name']);
956
				if (is_array($vs_a[$i]['pool'])) {
957
					$vs_a[$i]['pool'] = $vs_a[$i]['pool'][0];
958
				}
959
				$pool['port'] = $pools[$vs_a[$i]['pool']]['port'];
960
				$pool['servers'] = array();
961
				$pool['servers'][] = $vs_a[$i]['sitedown'];
962
				$pool['monitor'] = $pools[$vs_a[$i]['pool']]['monitor'];
963
				$pool_a[] = $pool;
964
				$vs_a[$i]['sitedown'] = $pool['name'];
965
			}
966
		}
967
	}
968
	if (count($config['load_balancer']) == 0) {
969
		unset($config['load_balancer']);
970
	}
971
	mwexec('/usr/sbin/pw groupadd -n _relayd -g 913');
972
	mwexec('/usr/sbin/pw useradd -n _relayd -c "Relay Daemon" -d /var/empty -s /usr/sbin/nologin -u 913 -g 913');
973
}
974

    
975

    
976
function upgrade_046_to_047() {
977
	global $config;
978
	/* Upgrade IPsec from tunnel to phase1/phase2 */
979

    
980
	if (is_array($config['ipsec']['tunnel'])) {
981

    
982
		$a_phase1 = array();
983
		$a_phase2 = array();
984
		$ikeid = 0;
985

    
986
		foreach ($config['ipsec']['tunnel'] as $tunnel) {
987

    
988
			unset($ph1ent);
989
			unset($ph2ent);
990

    
991
			/*
992
				*  attempt to locate an enabled phase1
993
				*  entry that matches the peer gateway
994
				*/
995

    
996
			if (!isset($tunnel['disabled'])) {
997

    
998
				$remote_gateway = $tunnel['remote-gateway'];
999

    
1000
				foreach ($a_phase1 as $ph1tmp) {
1001
					if ($ph1tmp['remote-gateway'] == $remote_gateway) {
1002
						$ph1ent = $ph1tmp;
1003
						break;
1004
					}
1005
				}
1006
			}
1007

    
1008
			/* none found, create a new one */
1009

    
1010
			if (!isset($ph1ent)) {
1011

    
1012
				/* build new phase1 entry */
1013

    
1014
				$ph1ent = array();
1015

    
1016
				$ph1ent['ikeid'] = ++$ikeid;
1017

    
1018
				if (isset($tunnel['disabled'])) {
1019
					$ph1ent['disabled'] = $tunnel['disabled'];
1020
				}
1021

    
1022
				/* convert to the new vip[$vhid] name */
1023
				if (preg_match("/^carp/", $tunnel['interface'])) {
1024
					$carpid = str_replace("carp", "", $tunnel['interface']);
1025
					$tunnel['interface'] = "vip" . $config['virtualip']['vip'][$carpid]['vhid'];
1026
				}
1027
				$ph1ent['interface'] = $tunnel['interface'];
1028
				$ph1ent['remote-gateway'] = $tunnel['remote-gateway'];
1029
				$ph1ent['descr'] = $tunnel['descr'];
1030

    
1031
				$ph1ent['mode'] = $tunnel['p1']['mode'];
1032

    
1033
				if (isset($tunnel['p1']['myident']['myaddress'])) {
1034
					$ph1ent['myid_type'] = "myaddress";
1035
				}
1036
				if (isset($tunnel['p1']['myident']['address'])) {
1037
					$ph1ent['myid_type'] = "address";
1038
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['address'];
1039
				}
1040
				if (isset($tunnel['p1']['myident']['fqdn'])) {
1041
					$ph1ent['myid_type'] = "fqdn";
1042
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['fqdn'];
1043
				}
1044
				if (isset($tunnel['p1']['myident']['ufqdn'])) {
1045
					$ph1ent['myid_type'] = "user_fqdn";
1046
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['ufqdn'];
1047
				}
1048
				if (isset($tunnel['p1']['myident']['asn1dn'])) {
1049
					$ph1ent['myid_type'] = "asn1dn";
1050
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['asn1dn'];
1051
				}
1052
				if (isset($tunnel['p1']['myident']['dyn_dns'])) {
1053
					$ph1ent['myid_type'] = "dyn_dns";
1054
					$ph1ent['myid_data'] = $tunnel['p1']['myident']['dyn_dns'];
1055
				}
1056

    
1057
				$ph1ent['peerid_type'] = "peeraddress";
1058

    
1059
				switch ($tunnel['p1']['encryption-algorithm']) {
1060
					case "des":
1061
						$ph1alg = array('name' => 'des');
1062
						break;
1063
					case "3des":
1064
						$ph1alg = array('name' => '3des');
1065
						break;
1066
					case "blowfish":
1067
						$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1068
						break;
1069
					case "cast128":
1070
						$ph1alg = array('name' => 'cast128');
1071
						break;
1072
					case "rijndael":
1073
						$ph1alg = array('name' => 'aes', 'keylen' => '128');
1074
						break;
1075
					case "rijndael 256":
1076
					case "aes 256":
1077
						$ph1alg = array('name' => 'aes', 'keylen' => '256');
1078
						break;
1079
				}
1080

    
1081
				$ph1ent['encryption-algorithm'] = $ph1alg;
1082
				$ph1ent['hash-algorithm'] = $tunnel['p1']['hash-algorithm'];
1083
				$ph1ent['dhgroup'] = $tunnel['p1']['dhgroup'];
1084
				$ph1ent['lifetime'] = $tunnel['p1']['lifetime'];
1085
				$ph1ent['authentication_method'] = $tunnel['p1']['authentication_method'];
1086

    
1087
				if (isset($tunnel['p1']['pre-shared-key'])) {
1088
					$ph1ent['pre-shared-key'] = $tunnel['p1']['pre-shared-key'];
1089
				}
1090
				if (isset($tunnel['p1']['cert'])) {
1091
					$ph1ent['cert'] = $tunnel['p1']['cert'];
1092
				}
1093
				if (isset($tunnel['p1']['peercert'])) {
1094
					$ph1ent['peercert'] = $tunnel['p1']['peercert'];
1095
				}
1096
				if (isset($tunnel['p1']['private-key'])) {
1097
					$ph1ent['private-key'] = $tunnel['p1']['private-key'];
1098
				}
1099

    
1100
				$ph1ent['nat_traversal'] = "on";
1101
				$ph1ent['dpd_enable'] = 1;
1102
				$ph1ent['dpd_delay'] = 10;
1103
				$ph1ent['dpd_maxfail'] = 5;
1104

    
1105
				$a_phase1[] = $ph1ent;
1106
			}
1107

    
1108
			/* build new phase2 entry */
1109

    
1110
			$ph2ent = array();
1111

    
1112
			$ph2ent['ikeid'] = $ph1ent['ikeid'];
1113

    
1114
			if (isset($tunnel['disabled'])) {
1115
				$ph1ent['disabled'] = $tunnel['disabled'];
1116
			}
1117

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

    
1120
			$type = "lan";
1121
			if ($tunnel['local-subnet']['network']) {
1122
				$type = $tunnel['local-subnet']['network'];
1123
			}
1124
			if ($tunnel['local-subnet']['address']) {
1125
				list($address, $netbits) = explode("/", $tunnel['local-subnet']['address']);
1126
				if (is_null($netbits)) {
1127
					$type = "address";
1128
				} else {
1129
					$type = "network";
1130
				}
1131
			}
1132

    
1133
			switch ($type) {
1134
				case "address":
1135
					$ph2ent['localid'] = array('type' => $type, 'address' => $address);
1136
					break;
1137
				case "network":
1138
					$ph2ent['localid'] = array('type' => $type, 'address' => $address, 'netbits' => $netbits);
1139
					break;
1140
				default:
1141
					$ph2ent['localid'] = array('type' => $type);
1142
					break;
1143
			}
1144

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

    
1148
			$ph2ent['protocol'] = $tunnel['p2']['protocol'];
1149

    
1150
			$aes_count = 0;
1151
			foreach ($tunnel['p2']['encryption-algorithm-option'] as $tunalg) {
1152
				$aes_found = false;
1153
				switch ($tunalg) {
1154
					case "des":
1155
						$ph2alg = array('name' => 'des');
1156
						break;
1157
					case "3des":
1158
						$ph2alg = array('name' => '3des');
1159
						break;
1160
					case "blowfish":
1161
						$ph2alg = array('name' => 'blowfish', 'keylen' => 'auto');
1162
						break;
1163
					case "cast128":
1164
						$ph2alg = array('name' => 'cast128');
1165
						break;
1166
					case "rijndael":
1167
					case "rijndael 256":
1168
					case "aes 256":
1169
						$ph2alg = array('name' => 'aes', 'keylen' => 'auto');
1170
						$aes_found = true;
1171
						$aes_count++;
1172
						break;
1173
				}
1174

    
1175
				if (!$aes_found || ($aes_count < 2)) {
1176
					$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1177
				}
1178
			}
1179

    
1180
			$ph2ent['hash-algorithm-option'] = $tunnel['p2']['hash-algorithm-option'];
1181
			$ph2ent['pfsgroup'] = $tunnel['p2']['pfsgroup'];
1182
			$ph2ent['lifetime'] = $tunnel['p2']['lifetime'];
1183

    
1184
			if (isset($tunnel['pinghost']['pinghost'])) {
1185
				$ph2ent['pinghost'] = $tunnel['pinghost'];
1186
			}
1187

    
1188
			$a_phase2[] = $ph2ent;
1189
		}
1190

    
1191
		unset($config['ipsec']['tunnel']);
1192
		$config['ipsec']['phase1'] = $a_phase1;
1193
		$config['ipsec']['phase2'] = $a_phase2;
1194
	}
1195

    
1196
	/* Upgrade Mobile IPsec */
1197
	if (isset($config['ipsec']['mobileclients']) &&
1198
	    is_array($config['ipsec']['mobileclients']) &&
1199
	    is_array($config['ipsec']['mobileclients']['p1']) &&
1200
	    is_array($config['ipsec']['mobileclients']['p2'])) {
1201

    
1202
		if (isset($config['ipsec']['mobileclients']['enable'])) {
1203
			$config['ipsec']['client']['enable'] = true;
1204
			$config['ipsec']['client']['user_source'] = 'system';
1205
			$config['ipsec']['client']['group_source'] = 'system';
1206
		}
1207

    
1208
		$mobilecfg = $config['ipsec']['mobileclients'];
1209

    
1210
		$ph1ent = array();
1211
		$ph1ent['ikeid'] = ++$ikeid;
1212

    
1213
		if (!isset($mobilecfg['enable'])) {
1214
			$ph1ent['disabled'] = true;
1215
		}
1216

    
1217
		/* Assume WAN since mobile tunnels couldn't be on a separate interface on 1.2.x */
1218
		$ph1ent['interface'] = 'wan';
1219
		$ph1ent['descr'] = "Mobile Clients (upgraded)";
1220
		$ph1ent['mode'] = $mobilecfg['p1']['mode'];
1221

    
1222
		if (isset($mobilecfg['p1']['myident']['myaddress'])) {
1223
			$ph1ent['myid_type'] = "myaddress";
1224
		}
1225
		if (isset($mobilecfg['p1']['myident']['address'])) {
1226
			$ph1ent['myid_type'] = "address";
1227
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['address'];
1228
		}
1229
		if (isset($mobilecfg['p1']['myident']['fqdn'])) {
1230
			$ph1ent['myid_type'] = "fqdn";
1231
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['fqdn'];
1232
		}
1233
		if (isset($mobilecfg['p1']['myident']['ufqdn'])) {
1234
			$ph1ent['myid_type'] = "user_fqdn";
1235
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['ufqdn'];
1236
		}
1237
		if (isset($mobilecfg['p1']['myident']['asn1dn'])) {
1238
			$ph1ent['myid_type'] = "asn1dn";
1239
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['asn1dn'];
1240
		}
1241
		if (isset($mobilecfg['p1']['myident']['dyn_dns'])) {
1242
			$ph1ent['myid_type'] = "dyn_dns";
1243
			$ph1ent['myid_data'] = $mobilecfg['p1']['myident']['dyn_dns'];
1244
		}
1245
		$ph1ent['peerid_type'] = "fqdn";
1246
		$ph1ent['peerid_data'] = "";
1247

    
1248
		switch ($mobilecfg['p1']['encryption-algorithm']) {
1249
			case "des":
1250
				$ph1alg = array('name' => 'des');
1251
				break;
1252
			case "3des":
1253
				$ph1alg = array('name' => '3des');
1254
				break;
1255
			case "blowfish":
1256
				$ph1alg = array('name' => 'blowfish', 'keylen' => '128');
1257
				break;
1258
			case "cast128":
1259
				$ph1alg = array('name' => 'cast128');
1260
				break;
1261
			case "rijndael":
1262
				$ph1alg = array('name' => 'aes', 'keylen' => '128');
1263
				break;
1264
			case "rijndael 256":
1265
			case "aes 256":
1266
				$ph1alg = array('name' => 'aes', 'keylen' => '256');
1267
				break;
1268
		}
1269

    
1270
		$ph1ent['encryption-algorithm'] = $ph1alg;
1271
		$ph1ent['hash-algorithm'] = $mobilecfg['p1']['hash-algorithm'];
1272
		$ph1ent['dhgroup'] = $mobilecfg['p1']['dhgroup'];
1273
		$ph1ent['lifetime'] = $mobilecfg['p1']['lifetime'];
1274
		$ph1ent['authentication_method'] = $mobilecfg['p1']['authentication_method'];
1275

    
1276
		if (isset($mobilecfg['p1']['cert'])) {
1277
			$ph1ent['cert'] = $mobilecfg['p1']['cert'];
1278
		}
1279
		if (isset($mobilecfg['p1']['peercert'])) {
1280
			$ph1ent['peercert'] = $mobilecfg['p1']['peercert'];
1281
		}
1282
		if (isset($mobilecfg['p1']['private-key'])) {
1283
			$ph1ent['private-key'] = $mobilecfg['p1']['private-key'];
1284
		}
1285

    
1286
		$ph1ent['nat_traversal'] = "on";
1287
		$ph1ent['dpd_enable'] = 1;
1288
		$ph1ent['dpd_delay'] = 10;
1289
		$ph1ent['dpd_maxfail'] = 5;
1290
		$ph1ent['mobile'] = true;
1291

    
1292
		$ph2ent = array();
1293
		$ph2ent['ikeid'] = $ph1ent['ikeid'];
1294
		$ph2ent['descr'] = "phase2 for ".$mobilecfg['descr'];
1295
		$ph2ent['localid'] = array('type' => 'none');
1296
		$ph2ent['remoteid'] = array('type' => 'mobile');
1297
		$ph2ent['protocol'] = $mobilecfg['p2']['protocol'];
1298

    
1299
		$aes_count = 0;
1300
		foreach ($mobilecfg['p2']['encryption-algorithm-option'] as $tunalg) {
1301
			$aes_found = false;
1302
			switch ($tunalg) {
1303
				case "des":
1304
					$ph2alg = array('name' => 'des');
1305
					break;
1306
				case "3des":
1307
					$ph2alg = array('name' => '3des');
1308
					break;
1309
				case "blowfish":
1310
					$ph2alg = array('name' => 'blowfish', 'keylen' => 'auto');
1311
					break;
1312
				case "cast128":
1313
					$ph2alg = array('name' => 'cast128');
1314
					break;
1315
				case "rijndael":
1316
				case "rijndael 256":
1317
				case "aes 256":
1318
					$ph2alg = array('name' => 'aes', 'keylen' => 'auto');
1319
					$aes_found = true;
1320
					$aes_count++;
1321
					break;
1322
			}
1323

    
1324
			if (!$aes_found || ($aes_count < 2)) {
1325
				$ph2ent['encryption-algorithm-option'][] = $ph2alg;
1326
			}
1327
		}
1328
		$ph2ent['hash-algorithm-option'] = $mobilecfg['p2']['hash-algorithm-option'];
1329
		$ph2ent['pfsgroup'] = $mobilecfg['p2']['pfsgroup'];
1330
		$ph2ent['lifetime'] = $mobilecfg['p2']['lifetime'];
1331
		$ph2ent['mobile'] = true;
1332

    
1333
		$config['ipsec']['phase1'][] = $ph1ent;
1334
		$config['ipsec']['phase2'][] = $ph2ent;
1335
		unset($config['ipsec']['mobileclients']);
1336
	}
1337
}
1338

    
1339

    
1340
function upgrade_047_to_048() {
1341
	global $config;
1342
	if (!empty($config['dyndns'])) {
1343
		$config['dyndnses'] = array();
1344
		$config['dyndnses']['dyndns'] = array();
1345
		if (isset($config['dyndns'][0]['host'])) {
1346
			$tempdyn = array();
1347
			$tempdyn['enable'] = isset($config['dyndns'][0]['enable']);
1348
			$tempdyn['type'] = $config['dyndns'][0]['type'];
1349
			$tempdyn['wildcard'] = isset($config['dyndns'][0]['wildcard']);
1350
			$tempdyn['username'] = $config['dyndns'][0]['username'];
1351
			$tempdyn['password'] = $config['dyndns'][0]['password'];
1352
			$tempdyn['host'] = $config['dyndns'][0]['host'];
1353
			$tempdyn['mx'] = $config['dyndns'][0]['mx'];
1354
			$tempdyn['interface'] = "wan";
1355
			$tempdyn['descr'] = sprintf(gettext("Upgraded Dyndns %s"), $tempdyn['type']);
1356
			$config['dyndnses']['dyndns'][] = $tempdyn;
1357
		}
1358
		unset($config['dyndns']);
1359
	}
1360
	if (!empty($config['dnsupdate'])) {
1361
		$pconfig = $config['dnsupdate'][0];
1362
		if (!$pconfig['ttl']) {
1363
			$pconfig['ttl'] = 60;
1364
		}
1365
		if (!$pconfig['keytype']) {
1366
			$pconfig['keytype'] = "zone";
1367
		}
1368
		$pconfig['interface'] = "wan";
1369
		$config['dnsupdates']['dnsupdate'][] = $pconfig;
1370
		unset($config['dnsupdate']);
1371
	}
1372

    
1373
	if (is_array($config['pppoe']) && is_array($config['pppoe'][0])) {
1374
		$pconfig = array();
1375
		$pconfig['username'] = $config['pppoe'][0]['username'];
1376
		$pconfig['password'] = $config['pppoe'][0]['password'];
1377
		$pconfig['provider'] = $config['pppoe'][0]['provider'];
1378
		$pconfig['ondemand'] = isset($config['pppoe'][0]['ondemand']);
1379
		$pconfig['timeout'] = $config['pppoe'][0]['timeout'];
1380
		unset($config['pppoe']);
1381
		$config['interfaces']['wan']['pppoe_username'] = $pconfig['username'];
1382
		$config['interfaces']['wan']['pppoe_password'] = $pconfig['password'];
1383
		$config['interfaces']['wan']['provider'] = $pconfig['provider'];
1384
		$config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']);
1385
		$config['interfaces']['wan']['timeout'] = $pconfig['timeout'];
1386
	}
1387
	if (is_array($config['pptp'])) {
1388
		$pconfig = array();
1389
		$pconfig['username'] = $config['pptp']['username'];
1390
		$pconfig['password'] = $config['pptp']['password'];
1391
		$pconfig['provider'] = $config['pptp']['provider'];
1392
		$pconfig['ondemand'] = isset($config['pptp']['ondemand']);
1393
		$pconfig['timeout'] = $config['pptp']['timeout'];
1394
		unset($config['pptp']);
1395
		$config['interfaces']['wan']['pptp_username'] = $pconfig['username'];
1396
		$config['interfaces']['wan']['pptp_password'] = $pconfig['password'];
1397
		$config['interfaces']['wan']['provider'] = $pconfig['provider'];
1398
		$config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']);
1399
		$config['interfaces']['wan']['timeout'] = $pconfig['timeout'];
1400
	}
1401
}
1402

    
1403

    
1404
function upgrade_048_to_049() {
1405
	global $config;
1406
	/* setup new all users group */
1407
	$all = array();
1408
	$all['name'] = "all";
1409
	$all['description'] = gettext("All Users");
1410
	$all['scope'] = "system";
1411
	$all['gid'] = 1998;
1412
	$all['member'] = array();
1413

    
1414
	if (!is_array($config['system']['user'])) {
1415
		$config['system']['user'] = array();
1416
	}
1417
	if (!is_array($config['system']['group'])) {
1418
		$config['system']['group'] = array();
1419
	}
1420

    
1421
	/* work around broken uid assignments */
1422
	$config['system']['nextuid'] = 2000;
1423
	foreach ($config['system']['user'] as & $user) {
1424
		if (isset($user['uid']) && !$user['uid']) {
1425
			continue;
1426
		}
1427
		$user['uid'] = $config['system']['nextuid']++;
1428
	}
1429

    
1430
	/* work around broken gid assignments */
1431
	$config['system']['nextgid'] = 2000;
1432
	foreach ($config['system']['group'] as & $group) {
1433
		if ($group['name'] == $g['admin_group']) {
1434
			$group['gid'] = 1999;
1435
		} else {
1436
			$group['gid'] = $config['system']['nextgid']++;
1437
		}
1438
	}
1439

    
1440
	/* build group membership information */
1441
	foreach ($config['system']['group'] as & $group) {
1442
		$group['member'] = array();
1443
		foreach ($config['system']['user'] as & $user) {
1444
			$groupnames = explode(",", $user['groupname']);
1445
			if (in_array($group['name'], $groupnames)) {
1446
				$group['member'][] = $user['uid'];
1447
			}
1448
		}
1449
	}
1450

    
1451
	/* reset user group information */
1452
	foreach ($config['system']['user'] as & $user) {
1453
		unset($user['groupname']);
1454
		$all['member'][] = $user['uid'];
1455
	}
1456

    
1457
	/* reset group scope information */
1458
	foreach ($config['system']['group'] as & $group) {
1459
		if ($group['name'] != $g['admin_group']) {
1460
			$group['scope'] = "user";
1461
		}
1462
	}
1463

    
1464
	/* insert new all group */
1465
	$groups = Array();
1466
	$groups[] = $all;
1467
	$groups = array_merge($config['system']['group'], $groups);
1468
	$config['system']['group'] = $groups;
1469
}
1470

    
1471

    
1472
function upgrade_049_to_050() {
1473
	global $config;
1474

    
1475
	if (!is_array($config['system']['user'])) {
1476
		$config['system']['user'] = array();
1477
	}
1478
	/* update user privileges */
1479
	foreach ($config['system']['user'] as & $user) {
1480
		$privs = array();
1481
		if (!is_array($user['priv'])) {
1482
			unset($user['priv']);
1483
			continue;
1484
		}
1485
		foreach ($user['priv'] as $priv) {
1486
			switch ($priv['id']) {
1487
				case "hasshell":
1488
					$privs[] = "user-shell-access";
1489
					break;
1490
				case "copyfiles":
1491
					$privs[] = "user-copy-files";
1492
					break;
1493
			}
1494
		}
1495
		$user['priv'] = $privs;
1496
	}
1497

    
1498
	/* update group privileges */
1499
	foreach ($config['system']['group'] as & $group) {
1500
		$privs = array();
1501
		if (!is_array($group['pages'])) {
1502
			unset($group['pages']);
1503
			continue;
1504
		}
1505
		foreach ($group['pages'] as $page) {
1506
			$priv = map_page_privname($page);
1507
			if ($priv) {
1508
				$privs[] = $priv;
1509
			}
1510
		}
1511
		unset($group['pages']);
1512
		$group['priv'] = $privs;
1513
	}
1514

    
1515
	/* sync all local account information */
1516
	local_sync_accounts();
1517
}
1518

    
1519

    
1520
function upgrade_050_to_051() {
1521
	global $config;
1522
	$pconfig = array();
1523
	$pconfig['descr'] = "Set to 0 to disable filtering on the incoming and outgoing member interfaces.";
1524
	$pconfig['tunable'] = "net.link.bridge.pfil_member";
1525
	$pconfig['value'] = "1";
1526
	$config['sysctl']['item'][] = $pconfig;
1527
	$pconfig = array();
1528
	$pconfig['descr'] = "Set to 1 to enable filtering on the bridge interface";
1529
	$pconfig['tunable'] = "net.link.bridge.pfil_bridge";
1530
	$pconfig['value'] = "0";
1531
	$config['sysctl']['item'][] = $pconfig;
1532

    
1533
	if (isset($config['bridge'])) {
1534
		unset($config['bridge']);
1535
	}
1536

    
1537
	$convert_bridges = false;
1538
	foreach ($config['interfaces'] as $intf) {
1539
		if (isset($intf['bridge']) && $intf['bridge'] <> "") {
1540
			$config['bridges'] = array();
1541
			$config['bridges']['bridged'] = array();
1542
			$convert_bridges = true;
1543
			break;
1544
		}
1545
	}
1546
	if ($convert_bridges == true) {
1547
		$i = 0;
1548
		foreach ($config['interfaces'] as $ifr => &$intf) {
1549
			if (isset($intf['bridge']) && $intf['bridge'] <> "") {
1550
				$nbridge = array();
1551
				$nbridge['members'] = "{$ifr},{$intf['bridge']}";
1552
				$nbridge['descr'] = sprintf(gettext("Converted bridged %s"), $ifr);
1553
				$nbridge['bridgeif'] = "bridge{$i}";
1554
				$config['bridges']['bridged'][] = $nbridge;
1555
				unset($intf['bridge']);
1556
				$i++;
1557
			}
1558
		}
1559
	}
1560
}
1561

    
1562

    
1563
function upgrade_051_to_052() {
1564
	global $config;
1565
	$config['openvpn'] = array();
1566
	if (!is_array($config['ca'])) {
1567
		$config['ca'] = array();
1568
	}
1569
	if (!is_array($config['cert'])) {
1570
		$config['cert'] = array();
1571
	}
1572

    
1573
	$vpnid = 1;
1574

    
1575
	/* openvpn server configurations */
1576
	if (is_array($config['installedpackages']['openvpnserver'])) {
1577
		$config['openvpn']['openvpn-server'] = array();
1578

    
1579
		$index = 1;
1580
		foreach ($config['installedpackages']['openvpnserver']['config'] as $server) {
1581

    
1582
			if (!is_array($server)) {
1583
				continue;
1584
			}
1585

    
1586
			if ($server['auth_method'] == "pki") {
1587

    
1588
				/* create ca entry */
1589
				$ca = array();
1590
				$ca['refid'] = uniqid();
1591
				$ca['descr'] = "OpenVPN Server CA #{$index}";
1592
				$ca['crt'] = $server['ca_cert'];
1593
				$config['ca'][] = $ca;
1594

    
1595
				/* create ca reference */
1596
				unset($server['ca_cert']);
1597
				$server['caref'] = $ca['refid'];
1598

    
1599
				/* create a crl entry if needed */
1600
				if (!empty($server['crl'][0])) {
1601
					$crl = array();
1602
					$crl['refid'] = uniqid();
1603
					$crl['descr'] = "Imported OpenVPN CRL #{$index}";
1604
					$crl['caref'] = $ca['refid'];
1605
					$crl['text'] = $server['crl'][0];
1606
					if (!is_array($config['crl'])) {
1607
						$config['crl'] = array();
1608
					}
1609
					$config['crl'][] = $crl;
1610
					$server['crlref'] = $crl['refid'];
1611
				}
1612
				unset($server['crl']);
1613

    
1614
				/* create cert entry */
1615
				$cert = array();
1616
				$cert['refid'] = uniqid();
1617
				$cert['descr'] = "OpenVPN Server Certificate #{$index}";
1618
				$cert['crt'] = $server['server_cert'];
1619
				$cert['prv'] = $server['server_key'];
1620
				$config['cert'][] = $cert;
1621

    
1622
				/* create cert reference */
1623
				unset($server['server_cert']);
1624
				unset($server['server_key']);
1625
				$server['certref'] = $cert['refid'];
1626

    
1627
				$index++;
1628
			}
1629

    
1630
			/* determine operational mode */
1631
			if ($server['auth_method'] == 'pki') {
1632
				if ($server['nopool']) {
1633
					$server['mode'] = "p2p_tls";
1634
				} else {
1635
					$server['mode'] = "server_tls";
1636
				}
1637
			} else {
1638
				$server['mode'] = "p2p_shared_key";
1639
			}
1640
			unset($server['auth_method']);
1641

    
1642
			/* modify configuration values */
1643
			$server['dh_length'] = 1024;
1644
			unset($server['dh_params']);
1645
			if (!$server['interface']) {
1646
				$server['interface'] = 'any';
1647
			}
1648
			$server['tunnel_network'] = $server['addresspool'];
1649
			unset($server['addresspool']);
1650
			if (isset($server['use_lzo']) && ($server['use_lzo'] == "on")) {
1651
				$server['compression'] = "on";
1652
				unset($server['use_lzo']);
1653
			}
1654
			if ($server['nopool']) {
1655
				$server['pool_enable'] = false;
1656
			} else {
1657
				$server['pool_enable'] = "yes";
1658
			}
1659
			unset($server['nopool']);
1660
			$server['dns_domain'] = $server['dhcp_domainname'];
1661
			unset($server['dhcp_domainname']);
1662

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

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

    
1679
			if ($server['dhcp_nbtdisable']) {
1680
				$server['netbios_enable'] = false;
1681
			} else {
1682
				$server['netbios_enable'] = "yes";
1683
			}
1684
			unset($server['dhcp_nbtdisable']);
1685
			$server['netbios_ntype'] = $server['dhcp_nbttype'];
1686
			unset($server['dhcp_nbttype']);
1687
			$server['netbios_scope'] = $server['dhcp_nbtscope'];
1688
			unset($server['dhcp_nbtscope']);
1689

    
1690
			$tmparr = explode(";", $server['dhcp_nbdd'], 2);
1691
			$d=1;
1692
			foreach ($tmparr as $tmpa) {
1693
				$server["nbdd_server{$d}"] = $tmpa;
1694
				$d++;
1695
			}
1696
			unset($server['dhcp_nbdd']);
1697

    
1698
			$tmparr = explode(";", $server['dhcp_wins'], 2);
1699
			$d=1;
1700
			foreach ($tmparr as $tmpa) {
1701
				$server["wins_server{$d}"] = $tmpa;
1702
				$d++;
1703
			}
1704
			unset($server['dhcp_wins']);
1705

    
1706
			if (!empty($server['disable'])) {
1707
				$server['disable'] = true;
1708
			} else {
1709
				unset($server['disable']);
1710
			}
1711

    
1712
			/* allocate vpnid */
1713
			$server['vpnid'] = $vpnid++;
1714

    
1715
			if (!empty($server['custom_options'])) {
1716
				$cstmopts = array();
1717
				$tmpcstmopts = explode(";", $server['custom_options']);
1718
				$assigned_if = "";
1719
				$tmpstr = "";
1720
				foreach ($tmpcstmopts as $tmpcstmopt) {
1721
					$tmpstr = str_replace(" ", "", $tmpcstmopt);
1722
					if (substr($tmpstr, 0, 6) == "devtun") {
1723
						$assigned_if = substr($tmpstr, 3);
1724
						continue;
1725
					} else if (substr($tmpstr, 0, 5) == "local") {
1726
						$localip = substr($tmpstr, 5);
1727
						$server['ipaddr'] = str_replace("\n", "", $localip);
1728
					} else {
1729
						$cstmopts[] = $tmpcstmopt;
1730
					}
1731
				}
1732
				$server['custom_options'] = implode(";", $cstmopts);
1733
				if (!empty($assigned_if)) {
1734
					foreach ($config['interfaces'] as $iface => $cfgif) {
1735
						if ($cfgif['if'] == $assigned_if) {
1736
							$config['interfaces'][$iface]['if'] = "ovpns{$server['vpnid']}";
1737
							break;
1738
						}
1739
					}
1740
				}
1741
			}
1742

    
1743
			$config['openvpn']['openvpn-server'][] = $server;
1744
		}
1745
		unset($config['installedpackages']['openvpnserver']);
1746
	}
1747

    
1748
	/* openvpn client configurations */
1749
	if (is_array($config['installedpackages']['openvpnclient'])) {
1750
		$config['openvpn']['openvpn-client'] = array();
1751

    
1752
		$index = 1;
1753
		foreach ($config['installedpackages']['openvpnclient']['config'] as $client) {
1754

    
1755
			if (!is_array($client)) {
1756
				continue;
1757
			}
1758

    
1759
			if ($client['auth_method'] == "pki") {
1760

    
1761
				/* create ca entry */
1762
				$ca = array();
1763
				$ca['refid'] = uniqid();
1764
				$ca['descr'] = "OpenVPN Client CA #{$index}";
1765
				$ca['crt'] = $client['ca_cert'];
1766
				$ca['crl'] = $client['crl'];
1767
				$config['ca'][] = $ca;
1768

    
1769
				/* create ca reference */
1770
				unset($client['ca_cert']);
1771
				unset($client['crl']);
1772
				$client['caref'] = $ca['refid'];
1773

    
1774
				/* create cert entry */
1775
				$cert = array();
1776
				$cert['refid'] = uniqid();
1777
				$cert['descr'] = "OpenVPN Client Certificate #{$index}";
1778
				$cert['crt'] = $client['client_cert'];
1779
				$cert['prv'] = $client['client_key'];
1780
				$config['cert'][] = $cert;
1781

    
1782
				/* create cert reference */
1783
				unset($client['client_cert']);
1784
				unset($client['client_key']);
1785
				$client['certref'] = $cert['refid'];
1786

    
1787
				$index++;
1788
			}
1789

    
1790
			/* determine operational mode */
1791
			if ($client['auth_method'] == 'pki') {
1792
				$client['mode'] = "p2p_tls";
1793
			} else {
1794
				$client['mode'] = "p2p_shared_key";
1795
			}
1796
			unset($client['auth_method']);
1797

    
1798
			/* modify configuration values */
1799
			if (!$client['interface']) {
1800
				$client['interface'] = 'wan';
1801
			}
1802
			$client['tunnel_network'] = $client['interface_ip'];
1803
			unset($client['interface_ip']);
1804
			$client['server_addr'] = $client['serveraddr'];
1805
			unset($client['serveraddr']);
1806
			$client['server_port'] = $client['serverport'];
1807
			unset($client['serverport']);
1808
			$client['proxy_addr'] = $client['poxy_hostname'];
1809
			unset($client['proxy_addr']);
1810
			if (isset($client['use_lzo']) && ($client['use_lzo'] == "on")) {
1811
				$client['compression'] = "on";
1812
				unset($client['use_lzo']);
1813
			}
1814
			$client['resolve_retry'] = $client['infiniteresolvretry'];
1815
			unset($client['infiniteresolvretry']);
1816

    
1817
			/* allocate vpnid */
1818
			$client['vpnid'] = $vpnid++;
1819

    
1820
			if (!empty($client['custom_options'])) {
1821
				$cstmopts = array();
1822
				$tmpcstmopts = explode(";", $client['custom_options']);
1823
				$assigned_if = "";
1824
				$tmpstr = "";
1825
				foreach ($tmpcstmopts as $tmpcstmopt) {
1826
					$tmpstr = str_replace(" ", "", $tmpcstmopt);
1827
					if (substr($tmpstr, 0, 6) == "devtun") {
1828
						$assigned_if = substr($tmpstr, 3);
1829
						continue;
1830
					} else if (substr($tmpstr, 0, 5) == "local") {
1831
						$localip = substr($tmpstr, 5);
1832
						$client['ipaddr'] = str_replace("\n", "", $localip);
1833
					} else {
1834
						$cstmopts[] = $tmpcstmopt;
1835
					}
1836
				}
1837
				$client['custom_options'] = implode(";", $cstmopts);
1838
				if (!empty($assigned_if)) {
1839
					foreach ($config['interfaces'] as $iface => $cfgif) {
1840
						if ($cfgif['if'] == $assigned_if) {
1841
							$config['interfaces'][$iface]['if'] = "ovpnc{$client['vpnid']}";
1842
							break;
1843
						}
1844
					}
1845
				}
1846
			}
1847

    
1848
			if (!empty($client['disable'])) {
1849
				$client['disable'] = true;
1850
			} else {
1851
				unset($client['disable']);
1852
			}
1853

    
1854
			$config['openvpn']['openvpn-client'][] = $client;
1855
		}
1856

    
1857
		unset($config['installedpackages']['openvpnclient']);
1858
	}
1859

    
1860
	/* openvpn client specific configurations */
1861
	if (is_array($config['installedpackages']['openvpncsc'])) {
1862
		$config['openvpn']['openvpn-csc'] = array();
1863

    
1864
		foreach ($config['installedpackages']['openvpncsc']['config'] as $csc) {
1865

    
1866
			if (!is_array($csc)) {
1867
				continue;
1868
			}
1869

    
1870
			/* modify configuration values */
1871
			$csc['common_name'] = $csc['commonname'];
1872
			unset($csc['commonname']);
1873
			$csc['tunnel_network'] = $csc['ifconfig_push'];
1874
			unset($csc['ifconfig_push']);
1875
			$csc['dns_domain'] = $csc['dhcp_domainname'];
1876
			unset($csc['dhcp_domainname']);
1877

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

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

    
1894
			if ($csc['dhcp_nbtdisable']) {
1895
				$csc['netbios_enable'] = false;
1896
			} else {
1897
				$csc['netbios_enable'] = "yes";
1898
			}
1899
			unset($csc['dhcp_nbtdisable']);
1900
			$csc['netbios_ntype'] = $csc['dhcp_nbttype'];
1901
			unset($csc['dhcp_nbttype']);
1902
			$csc['netbios_scope'] = $csc['dhcp_nbtscope'];
1903
			unset($csc['dhcp_nbtscope']);
1904

    
1905
			$tmparr = explode(";", $csc['dhcp_nbdd'], 2);
1906
			$d=1;
1907
			foreach ($tmparr as $tmpa) {
1908
				$csc["nbdd_server{$d}"] = $tmpa;
1909
				$d++;
1910
			}
1911
			unset($csc['dhcp_nbdd']);
1912

    
1913
			$tmparr = explode(";", $csc['dhcp_wins'], 2);
1914
			$d=1;
1915
			foreach ($tmparr as $tmpa) {
1916
				$csc["wins_server{$d}"] = $tmpa;
1917
				$d++;
1918
			}
1919
			unset($csc['dhcp_wins']);
1920

    
1921
			if (!empty($csc['disable'])) {
1922
				$csc['disable'] = true;
1923
			} else {
1924
				unset($csc['disable']);
1925
			}
1926

    
1927
			$config['openvpn']['openvpn-csc'][] = $csc;
1928
		}
1929

    
1930
		unset($config['installedpackages']['openvpncsc']);
1931
	}
1932

    
1933
	if (count($config['openvpn']['openvpn-server']) > 0 ||
1934
	    count($config['openvpn']['openvpn-client']) > 0) {
1935
		$ovpnrule = array();
1936
		$ovpnrule['type'] = "pass";
1937
		$ovpnrule['interface'] = "openvpn";
1938
		$ovpnrule['statetype'] = "keep state";
1939
		$ovpnrule['source'] = array();
1940
		$ovpnrule['destination'] = array();
1941
		$ovpnrule['source']['any'] = true;
1942
		$ovpnrule['destination']['any'] = true;
1943
		$ovpnrule['descr'] = gettext("Auto added OpenVPN rule from config upgrade.");
1944
		$config['filter']['rule'][] = $ovpnrule;
1945
	}
1946

    
1947
	/*
1948
		* FIXME: hack to keep things working with no installedpackages
1949
		* or carp array in the configuration data.
1950
		*/
1951
	if (!is_array($config['installedpackages'])) {
1952
		$config['installedpackages'] = array();
1953
	}
1954
	if (!is_array($config['installedpackages']['carp'])) {
1955
		$config['installedpackages']['carp'] = array();
1956
	}
1957

    
1958
}
1959

    
1960

    
1961
function upgrade_052_to_053() {
1962
	global $config;
1963
	if (!is_array($config['ca'])) {
1964
		$config['ca'] = array();
1965
	}
1966
	if (!is_array($config['cert'])) {
1967
		$config['cert'] = array();
1968
	}
1969

    
1970
	/* migrate advanced admin page webui ssl to certificate manager */
1971
	if ($config['system']['webgui']['certificate'] &&
1972
	    $config['system']['webgui']['private-key']) {
1973

    
1974
		/* create cert entry */
1975
		$cert = array();
1976
		$cert['refid'] = uniqid();
1977
		$cert['descr'] = "webConfigurator SSL Certificate";
1978
		$cert['crt'] = $config['system']['webgui']['certificate'];
1979
		$cert['prv'] = $config['system']['webgui']['private-key'];
1980
		$config['cert'][] = $cert;
1981

    
1982
		/* create cert reference */
1983
		unset($config['system']['webgui']['certificate']);
1984
		unset($config['system']['webgui']['private-key']);
1985
		$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1986
	}
1987

    
1988
	/* migrate advanced admin page ssh keys to user manager */
1989
	if ($config['system']['ssh']['authorizedkeys']) {
1990
		$admin_user =& getUserEntryByUID(0);
1991
		$admin_user['authorizedkeys'] = $config['system']['ssh']['authorizedkeys'];
1992
		unset($config['system']['ssh']['authorizedkeys']);
1993
	}
1994
}
1995

    
1996

    
1997
function upgrade_053_to_054() {
1998
	global $config;
1999
	if (is_array($config['load_balancer']['lbpool'])) {
2000
		$lbpool_arr = $config['load_balancer']['lbpool'];
2001
		$lbpool_srv_arr = array();
2002
		$gateway_group_arr = array();
2003
		$gateways = return_gateways_array();
2004
		$group_name_changes = array();
2005
		if (!is_array($config['gateways']['gateway_item'])) {
2006
			$config['gateways']['gateway_item'] = array();
2007
		}
2008

    
2009
		$a_gateways =& $config['gateways']['gateway_item'];
2010
		foreach ($lbpool_arr as $lbpool) {
2011
			if ($lbpool['type'] == "gateway") {
2012
				// Gateway Groups have to have valid names in pf, old lb pools did not. Clean them up.
2013
				$group_name = preg_replace("/[^A-Za-z0-9]/", "", $lbpool['name']);
2014
				// If we made and changes, check for collisions and note the change.
2015
				if ($group_name != $lbpool['name']) {
2016
					// Make sure the name isn't already in use.
2017
					foreach ($gateway_group_arr as $gwg) {
2018
						// If the name is in use, add some random bits to avoid collision.
2019
						if ($gwg['name'] == $group_name) {
2020
							$group_name .= uniqid();
2021
						}
2022
					}
2023
					$group_name_changes[$lbpool['name']] = $group_name;
2024
				}
2025
				$gateway_group['name'] = $group_name;
2026
				$gateway_group['descr'] = $lbpool['descr'];
2027
				$gateway_group['trigger'] = "down";
2028
				$gateway_group['item'] = array();
2029
				$i = 0;
2030
				foreach ($lbpool['servers'] as $member) {
2031
					$split = explode("|", $member);
2032
					$interface = $split[0];
2033
					$monitor = $split[1];
2034
					/* on static upgraded configuration we automatically prepend GW_ */
2035
					$static_name = "GW_" . strtoupper($interface);
2036
					if (is_ipaddr($monitor)) {
2037
						foreach ($a_gateways as & $gw) {
2038
							if ($gw['name'] == $static_name) {
2039
								$gw['monitor'] = $monitor;
2040
							}
2041
						}
2042
					}
2043

    
2044
					/* on failover increment tier. Else always assign 1 */
2045
					if ($lbpool['behaviour'] == "failover") {
2046
						$i++;
2047
					} else {
2048
						$i = 1;
2049
					}
2050
					$gateway_group['item'][] = "$static_name|$i";
2051
				}
2052
				$gateway_group_arr[] = $gateway_group;
2053
			} else {
2054
				$lbpool_srv_arr[] = $lbpool;
2055
			}
2056
		}
2057
		$config['load_balancer']['lbpool'] = $lbpool_srv_arr;
2058
		$config['gateways']['gateway_group'] = $gateway_group_arr;
2059
	}
2060
	// Unset lbpool if we no longer have any server pools
2061
	if (count($lbpool_srv_arr) == 0) {
2062
		if (empty($config['load_balancer'])) {
2063
			unset($config['load_balancer']);
2064
		} else {
2065
			if (isset($config['load_balancer']['lbpool'])) {
2066
				unset($config['load_balancer']['lbpool']);
2067
			}
2068
		}
2069
	} else {
2070
		$config['load_balancer']['lbpool'] = $lbpool_srv_arr;
2071
	}
2072
	// Only set the gateway group array if we converted any
2073
	if (count($gateway_group_arr) != 0) {
2074
		$config['gateways']['gateway_group'] = $gateway_group_arr;
2075
		// Update any rules that had a gateway change, if any.
2076
		if (count($group_name_changes) > 0) {
2077
			foreach ($config['filter']['rule'] as & $rule) {
2078
				if (!empty($rule["gateway"]) && array_key_exists($rule["gateway"], $group_name_changes)) {
2079
					$rule["gateway"] = $group_name_changes[$rule["gateway"]];
2080
				}
2081
			}
2082
		}
2083
	}
2084
}
2085

    
2086

    
2087
function upgrade_054_to_055() {
2088
	global $config;
2089
	global $g;
2090

    
2091
	/* RRD files changed for quality, traffic and packets graphs */
2092
	//ini_set("max_execution_time", "1800");
2093
	/* convert traffic RRD file */
2094
	global $parsedcfg, $listtags;
2095
	$listtags = array("ds", "v", "rra", "row");
2096

    
2097
	$rrddbpath = "/var/db/rrd/";
2098
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2099
	if ($g['platform'] != $g['product_name']) {
2100
		/* restore the databases, if we have one */
2101
		if (restore_rrd()) {
2102
			/* Make sure to move the rrd backup out of the way. We will make a new one after converting. */
2103
			@rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/backup/rrd.tgz");
2104
		}
2105
	}
2106

    
2107
	$rrdinterval = 60;
2108
	$valid = $rrdinterval * 2;
2109

    
2110
	/* Asume GigE for now */
2111
	$downstream = 125000000;
2112
	$upstream = 125000000;
2113

    
2114
	/* build a list of quality databases */
2115
	/* roundtrip has become delay */
2116
	function divide_delay($delayval) {
2117
		$delayval = floatval($delayval);
2118
		$delayval = ($delayval / 1000);
2119
		$delayval = " ". sprintf("%1.10e", $delayval) ." ";
2120
		return $delayval;
2121
	}
2122
	/* the roundtrip times need to be divided by 1000 to get seconds, really */
2123
	$databases = array();
2124
	if (!file_exists($rrddbpath)) {
2125
		@mkdir($rrddbpath);
2126
	}
2127
	chdir($rrddbpath);
2128
	$databases = glob("*-quality.rrd");
2129
	rsort($databases);
2130
	foreach ($databases as $database) {
2131
		$xmldump = "{$database}.old.xml";
2132
		$xmldumpnew = "{$database}.new.xml";
2133

    
2134
		if (platform_booting()) {
2135
			echo "Migrate RRD database {$database} to new format for IPv6 \n";
2136
		}
2137
		mwexec("$rrdtool tune {$rrddbpath}{$database} -r roundtrip:delay 2>&1");
2138

    
2139
		dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}");
2140
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2141
		$rrdold = $rrdold['rrd'];
2142

    
2143
		$i = 0;
2144
		foreach ($rrdold['rra'] as $rra) {
2145
			$l = 0;
2146
			foreach ($rra['database']['row'] as $row) {
2147
				$vnew = divide_delay($row['v'][1]);
2148
				$rrdold['rra'][$i]['database']['row'][$l]['v'][1] = $vnew;
2149
				$l++;
2150
			}
2151
			$i++;
2152
		}
2153

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

    
2157
		unset($rrdold);
2158
		@unlink("{$g['tmp_path']}/{$xmldump}");
2159
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2160
	}
2161

    
2162
	/* build a list of traffic and packets databases */
2163
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
2164
	rsort($databases);
2165
	foreach ($databases as $database) {
2166
		$databasetmp = "{$database}.tmp";
2167
		$xmldump = "{$database}.old.xml";
2168
		$xmldumptmp = "{$database}.tmp.xml";
2169
		$xmldumpnew = "{$database}.new.xml";
2170

    
2171
		if (platform_booting()) {
2172
			echo "Migrate RRD database {$database} to new format \n";
2173
		}
2174
		/* rename DS source */
2175
		mwexec("$rrdtool tune {$rrddbpath}/{$database} -r in:inpass 2>&1");
2176
		mwexec("$rrdtool tune {$rrddbpath}/{$database} -r out:outpass 2>71");
2177

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

    
2181
		/* create new rrd database file */
2182
		$rrdcreate = "$rrdtool create {$g['tmp_path']}/{$databasetmp} --step $rrdinterval ";
2183
		$rrdcreate .= "DS:inpass:COUNTER:$valid:0:$downstream ";
2184
		$rrdcreate .= "DS:outpass:COUNTER:$valid:0:$upstream ";
2185
		$rrdcreate .= "DS:inblock:COUNTER:$valid:0:$downstream ";
2186
		$rrdcreate .= "DS:outblock:COUNTER:$valid:0:$upstream ";
2187
		$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
2188
		$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
2189
		$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
2190
		$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
2191

    
2192
		create_new_rrd("$rrdcreate");
2193
		/* create temporary xml from new RRD */
2194
		dump_rrd_to_xml("{$g['tmp_path']}/{$databasetmp}", "{$g['tmp_path']}/{$xmldumptmp}");
2195

    
2196
		$rrdold = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldump}"), 1, "tag");
2197
		$rrdold = $rrdold['rrd'];
2198

    
2199
		$rrdnew = xml2array(file_get_contents("{$g['tmp_path']}/{$xmldumptmp}"), 1, "tag");
2200
		$rrdnew = $rrdnew['rrd'];
2201

    
2202
		/* remove any MAX RRA's. Not needed for traffic. */
2203
		$i = 0;
2204
		foreach ($rrdold['rra'] as $rra) {
2205
			if (trim($rra['cf']) == "MAX") {
2206
				unset($rrdold['rra'][$i]);
2207
			}
2208
			$i++;
2209
		}
2210

    
2211
		file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", dump_xml_config_raw(migrate_rrd_format($rrdold, $rrdnew), "rrd"));
2212
		mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1");
2213
		/* we now have the rrd with the new fields, adjust the size now. */
2214
		/* RRA 2 is 60 minutes, RRA 3 is 720 minutes */
2215
		mwexec("/bin/sync");
2216
		mwexec("$rrdtool resize {$rrddbpath}/{$database} 2 GROW 2000;/bin/mv resize.rrd {$rrddbpath}/{$database} 2>&1");
2217
		mwexec("/bin/sync");
2218
		mwexec("$rrdtool resize {$rrddbpath}/{$database} 3 GROW 2000;/bin/mv resize.rrd {$rrddbpath}/{$database} 2>&1");
2219
		unset($rrdxmlarray);
2220
		@unlink("{$g['tmp_path']}/{$xmldump}");
2221
		@unlink("{$g['tmp_path']}/{$xmldumpnew}");
2222
	}
2223
	if (!platform_booting()) {
2224
		enable_rrd_graphing();
2225
	}
2226
	/* Let's save the RRD graphs after we run enable RRD graphing */
2227
	/* The function will restore the rrd.tgz so we will save it after */
2228
	exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
2229
	unlink_if_exists("{$g['vardb_path']}/rrd/*.xml");
2230
	if (platform_booting()) {
2231
		echo "Updating configuration...";
2232
	}
2233
}
2234

    
2235

    
2236
function upgrade_055_to_056() {
2237
	global $config;
2238

    
2239
	if (!is_array($config['ca'])) {
2240
		$config['ca'] = array();
2241
	}
2242
	if (!is_array($config['cert'])) {
2243
		$config['cert'] = array();
2244
	}
2245

    
2246
	/* migrate ipsec ca's to cert manager */
2247
	if (is_array($config['ipsec']['cacert'])) {
2248
		foreach ($config['ipsec']['cacert'] as & $cacert) {
2249
			$ca = array();
2250
			$ca['refid'] = uniqid();
2251
			if (is_array($cacert['cert'])) {
2252
				$ca['crt'] = $cacert['cert'][0];
2253
			} else {
2254
				$ca['crt'] = $cacert['cert'];
2255
			}
2256
			$ca['descr'] = $cacert['ident'];
2257
			$config['ca'][] = $ca;
2258
		}
2259
		unset($config['ipsec']['cacert']);
2260
	}
2261

    
2262
	/* migrate phase1 certificates to cert manager */
2263
	if (is_array($config['ipsec']['phase1'])) {
2264
		foreach ($config['ipsec']['phase1'] as & $ph1ent) {
2265
			$cert = array();
2266
			$cert['refid'] = uniqid();
2267
			$cert['descr'] = "IPsec Peer {$ph1ent['remote-gateway']} Certificate";
2268
			if (is_array($ph1ent['cert'])) {
2269
				$cert['crt'] = $ph1ent['cert'][0];
2270
			} else {
2271
				$cert['crt'] = $ph1ent['cert'];
2272
			}
2273
			$cert['prv'] = $ph1ent['private-key'];
2274
			$config['cert'][] = $cert;
2275
			$ph1ent['certref'] = $cert['refid'];
2276
			if ($ph1ent['cert']) {
2277
				unset($ph1ent['cert']);
2278
			}
2279
			if ($ph1ent['private-key']) {
2280
				unset($ph1ent['private-key']);
2281
			}
2282
			if ($ph1ent['peercert']) {
2283
				unset($ph1ent['peercert']);
2284
			}
2285
		}
2286
	}
2287
}
2288

    
2289

    
2290
function upgrade_056_to_057() {
2291
	global $config;
2292

    
2293
	if (!is_array($config['system']['user'])) {
2294
		$config['system']['user'] = array();
2295
	}
2296
	/* migrate captivate portal to user manager */
2297
	if (is_array($config['captiveportal']['user'])) {
2298
		foreach ($config['captiveportal']['user'] as $user) {
2299
			// avoid user conflicts
2300
			$found = false;
2301
			foreach ($config['system']['user'] as $userent) {
2302
				if ($userent['name'] == $user['name']) {
2303
					$found = true;
2304
					break;
2305
				}
2306
			}
2307
			if ($found) {
2308
				continue;
2309
			}
2310
			$user['scope'] = "user";
2311
			if (isset($user['expirationdate'])) {
2312
				$user['expires'] = $user['expirationdate'];
2313
				unset($user['expirationdate']);
2314
			}
2315
			if (isset($user['password'])) {
2316
				$user['md5-hash'] = $user['password'];
2317
				unset($user['password']);
2318
			}
2319
			$user['uid'] = $config['system']['nextuid']++;
2320
			$config['system']['user'][] = $user;
2321
		}
2322
		unset($config['captiveportal']['user']);
2323
	}
2324
}
2325

    
2326
function upgrade_057_to_058() {
2327
	global $config;
2328
	/* set all phase2 entries to tunnel mode */
2329
	if (is_array($config['ipsec']['phase2'])) {
2330
		foreach ($config['ipsec']['phase2'] as & $ph2ent) {
2331
			$ph2ent['mode'] = 'tunnel';
2332
		}
2333
	}
2334
}
2335

    
2336
function upgrade_058_to_059() {
2337
	global $config;
2338

    
2339
	if (is_array($config['schedules']['schedule'])) {
2340
		foreach ($config['schedules']['schedule'] as & $schedl) {
2341
			$schedl['schedlabel'] = uniqid();
2342
		}
2343
	}
2344
}
2345

    
2346
function upgrade_059_to_060() {
2347
	global $config;
2348
	require_once("/etc/inc/certs.inc");
2349
	if (is_array($config['ca'])) {
2350
		/* Locate issuer for all CAs */
2351
		foreach ($config['ca'] as & $ca) {
2352
			$subject = cert_get_subject($ca['crt']);
2353
			$issuer = cert_get_issuer($ca['crt']);
2354
			if ($issuer <> $subject) {
2355
				$issuer_crt =& lookup_ca_by_subject($issuer);
2356
				if ($issuer_crt) {
2357
					$ca['caref'] = $issuer_crt['refid'];
2358
				}
2359
			}
2360
		}
2361

    
2362
		/* Locate issuer for all certificates */
2363
		if (is_array($config['cert'])) {
2364
			foreach ($config['cert'] as & $cert) {
2365
				$subject = cert_get_subject($cert['crt']);
2366
				$issuer = cert_get_issuer($cert['crt']);
2367
				if ($issuer <> $subject) {
2368
					$issuer_crt =& lookup_ca_by_subject($issuer);
2369
					if ($issuer_crt) {
2370
						$cert['caref'] = $issuer_crt['refid'];
2371
					}
2372
				}
2373
			}
2374
		}
2375
	}
2376
}
2377

    
2378
function upgrade_060_to_061() {
2379
	global $config;
2380

    
2381
	if (is_array($config['interfaces']['wan'])) {
2382
		$config['interfaces']['wan']['enable'] = true;
2383
	}
2384
	if (is_array($config['interfaces']['lan'])) {
2385
		$config['interfaces']['lan']['enable'] = true;
2386
	}
2387

    
2388
	/* On 1.2.3 the "mtu" field adjusted MSS.
2389
	   On 2.x the "mtu" field is actually the MTU. Rename accordingly.
2390
	   See redmine ticket #1886
2391
	*/
2392
	foreach ($config['interfaces'] as $ifr => &$intf) {
2393
		if (isset($intf['mtu']) && is_numeric($intf['mtu'])) {
2394
			$intf['mss'] = $intf['mtu'];
2395
			unset($intf['mtu']);
2396
		}
2397
	}
2398
}
2399

    
2400
function upgrade_061_to_062() {
2401
	global $config;
2402

    
2403
	/* Convert NAT port forwarding rules */
2404
	if (is_array($config['nat']['rule'])) {
2405
		$a_nat = &$config['nat']['rule'];
2406

    
2407
		foreach ($a_nat as &$natent) {
2408
			$natent['disabled'] = false;
2409
			$natent['nordr']    = false;
2410

    
2411
			$natent['source'] = array(
2412
				"not"     => false,
2413
				"any"     => true,
2414
				"port"    => ""
2415
			);
2416

    
2417
			$natent['destination'] = array(
2418
				"not"     => false,
2419
				"address" => $natent['external-address'],
2420
				"port"    => $natent['external-port']
2421
			);
2422

    
2423
			if (empty($natent['destination']['address'])) {
2424
				unset($natent['destination']['address']);
2425
				$natent['destination']['network'] = $natent['interface'] . 'ip';
2426
			} else if ($natent['destination']['address'] == 'any') {
2427
				unset($natent['destination']['address']);
2428
				$natent['destination']['any'] = true;
2429
			}
2430

    
2431
			unset($natent['external-address']);
2432
			unset($natent['external-port']);
2433
		}
2434

    
2435
		unset($natent);
2436
	}
2437
}
2438

    
2439
function upgrade_062_to_063() {
2440
	/* Upgrade legacy Themes to the new pfsense_ng */
2441
	// Not supported in 2.3+
2442

    
2443
}
2444

    
2445
function upgrade_063_to_064() {
2446
	global $config;
2447
	$j = 0;
2448
	$ifcfg = &$config['interfaces'];
2449

    
2450
	if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
2451
		foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
2452
			$config['ppps']['ppp'][$pppid]['if'] = "ppp".$j;
2453
			$config['ppps']['ppp'][$pppid]['ptpid'] = $j;
2454
			$j++;
2455
			if (isset($ppp['port'])) {
2456
				$config['ppps']['ppp'][$pppid]['ports'] = $ppp['port'];
2457
				unset($config['ppps']['ppp'][$pppid]['port']);
2458
			}
2459
			if (!isset($ppp['type'])) {
2460
				$config['ppps']['ppp'][$pppid]['type'] = "ppp";
2461
			}
2462
			if (isset($ppp['defaultgw'])) {
2463
				unset($config['ppps']['ppp'][$pppid]['defaultgw']);
2464
			}
2465
		}
2466
	}
2467

    
2468
	if (!is_array($config['ppps']['ppp'])) {
2469
		$config['ppps']['ppp'] = array();
2470
	}
2471
	$a_ppps = &$config['ppps']['ppp'];
2472

    
2473
	foreach ($ifcfg as $ifname => $ifinfo) {
2474
		$ppp = array();
2475
		// For pppoe conversion
2476
		if ($ifinfo['ipaddr'] == "pppoe" || $ifinfo['ipaddr'] == "pptp") {
2477
			if (isset($ifinfo['ptpid'])) {
2478
				continue;
2479
			}
2480
			$ppp['ptpid'] = $j;
2481
			$ppp['type'] = $ifinfo['ipaddr'];
2482
			$ppp['if'] = $ifinfo['ipaddr'].$j;
2483
			$ppp['ports'] = $ifinfo['if'];
2484
			if ($ifinfo['ipaddr'] == "pppoe") {
2485
				$ppp['username'] = $ifinfo['pppoe_username'];
2486
				$ppp['password'] = base64_encode($ifinfo['pppoe_password']);
2487
			}
2488
			if ($ifinfo['ipaddr'] == "pptp") {
2489
				$ppp['username'] = $ifinfo['pptp_username'];
2490
				$ppp['password'] = base64_encode($ifinfo['pptp_password']);
2491
			}
2492

    
2493
			if (isset($ifinfo['provider'])) {
2494
				$ppp['provider'] = $ifinfo['provider'];
2495
			}
2496
			if (isset($ifinfo['ondemand'])) {
2497
				$ppp['ondemand'] = true;
2498
			}
2499
			if (isset($ifinfo['timeout'])) {
2500
				$ppp['idletimeout'] = $ifinfo['timeout'];
2501
			}
2502
			if (isset($ifinfo['pppoe']['pppoe-reset-type'])) {
2503
				$ppp['pppoe-reset-type'] = $ifinfo['pppoe']['pppoe-reset-type'];
2504
				if (is_array($config['cron']['item'])) {
2505
					for ($i = 0; $i < count($config['cron']['item']); $i++) {
2506
						$item = $config['cron']['item'][$i];
2507
						if (strpos($item['command'], "/conf/pppoe{$ifname}restart") !== false) {
2508
							$config['cron']['item'][$i]['command'] = "/var/etc/pppoe_restart_" . $ppp['if'];
2509
						}
2510
					}
2511
				}
2512
			}
2513
			if (isset($ifinfo['local'])) {
2514
				$ppp['localip'] = $ifinfo['local'];
2515
			}
2516
			if (isset($ifinfo['subnet'])) {
2517
				$ppp['subnet'] = $ifinfo['subnet'];
2518
			}
2519
			if (isset($ifinfo['remote'])) {
2520
				$ppp['gateway'] = $ifinfo['remote'];
2521
			}
2522

    
2523
			$ifcfg[$ifname]['if'] = $ifinfo['ipaddr'].$j;
2524
			$j++;
2525

    
2526
			unset($ifcfg[$ifname]['pppoe_username']);
2527
			unset($ifcfg[$ifname]['pppoe_password']);
2528
			unset($ifcfg[$ifname]['provider']);
2529
			unset($ifcfg[$ifname]['ondemand']);
2530
			unset($ifcfg[$ifname]['timeout']);
2531
			unset($ifcfg[$ifname]['pppoe_reset']);
2532
			unset($ifcfg[$ifname]['pppoe_preset']);
2533
			unset($ifcfg[$ifname]['pppoe']);
2534
			unset($ifcfg[$ifname]['pptp_username']);
2535
			unset($ifcfg[$ifname]['pptp_password']);
2536
			unset($ifcfg[$ifname]['local']);
2537
			unset($ifcfg[$ifname]['subnet']);
2538
			unset($ifcfg[$ifname]['remote']);
2539

    
2540
			$a_ppps[] = $ppp;
2541

    
2542
		}
2543
	}
2544
}
2545

    
2546
function upgrade_064_to_065() {
2547
	/* Disable TSO and LRO in upgraded configs */
2548
	global $config;
2549
	$config['system']['disablesegmentationoffloading'] = true;
2550
	$config['system']['disablelargereceiveoffloading'] = true;
2551
}
2552

    
2553
function upgrade_065_to_066() {
2554
	global $config;
2555

    
2556
	$dhcrelaycfg =& $config['dhcrelay'];
2557

    
2558
	if (is_array($dhcrelaycfg)) {
2559
		$dhcrelayifs = array();
2560
		$foundifs = false;
2561
		/* DHCPRelay enabled on any interfaces? */
2562
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
2563
			if (isset($dhcrelayifconf['enable'])) {
2564
				$dhcrelayifs[] = $dhcrelayif;
2565
				unset($dhcrelaycfg['dhcrelayif']);
2566
				$foundifs = true;
2567
			}
2568
		}
2569
		if ($foundifs == true) {
2570
			$dhcrelaycfg['interface'] = implode(",", $dhcrelayifs);
2571
		}
2572
	}
2573
}
2574

    
2575
function upgrade_066_to_067() {
2576
	global $config;
2577
	if (isset($config['system']['ca'])) {
2578
		$config['ca'] = $config['system']['ca'];
2579
		unset($config['system']['ca']);
2580
	}
2581
	if (isset($config['system']['cert'])) {
2582
		$config['cert'] = $config['system']['cert'];
2583
		unset($config['system']['cert']);
2584
	}
2585
}
2586

    
2587
function upgrade_067_to_068() {
2588
	global $config;
2589

    
2590
	if (!empty($config['pppoe'])) {
2591
		$config['pppoes'] = array();
2592
		$config['pppoes']['pppoe'] = array();
2593
		$config['pppoes']['pppoe'][] = $config['pppoe'][0];
2594

    
2595
		if (is_array($config['pppoe']['user'])) {
2596
			$username = array();
2597
			foreach ($config['pppoe']['user'] as $user) {
2598
				$usr = $user['name'] . ":" . base64_encode($user['password']);
2599
				if ($user['ip']) {
2600
					$usr .= ":{$user['ip']}";
2601
				}
2602
				$username[] = $usr;
2603
			}
2604
			$config['pppoes']['pppoe'][0]['username'] = implode(" ", $username);
2605
		}
2606
		unset($config['pppoe']);
2607
	}
2608
}
2609

    
2610
function upgrade_068_to_069() {
2611
	global $config;
2612
	if (!is_array($config['system']['user'])) {
2613
		return;
2614
	}
2615
	foreach ($config['system']['user'] as & $user) {
2616
		if (!is_array($user['cert'])) {
2617
			continue;
2618
		}
2619
		$rids = array();
2620
		foreach ($user['cert'] as $id => $cert) {
2621
			if (!isset($cert['descr'])) {
2622
				continue;
2623
			}
2624
			$tcert = $cert;
2625
			// Make sure each cert gets a refid
2626
			if (!isset($tcert['refid'])) {
2627
				$tcert['refid'] = uniqid();
2628
			}
2629
			// Keep the cert references for this user
2630
			$rids[] = $tcert['refid'];
2631
			$config['cert'][] = $tcert;
2632
		}
2633
		// Replace user certs with cert references instead.
2634
		if (count($rids) > 0) {
2635
			$user['cert'] = $rids;
2636
		}
2637
	}
2638
}
2639

    
2640
function upgrade_069_to_070() {
2641
	global $config;
2642

    
2643
	/* Convert NAT 1:1 rules */
2644
	if (is_array($config['nat']['onetoone'])) {
2645
		foreach ($config['nat']['onetoone'] as $nidx => $natent) {
2646
			if ($natent['subnet'] == 32) {
2647
				$config['nat']['onetoone'][$nidx]['source'] = array("address" => $natent['internal']);
2648
			} else {
2649
				$config['nat']['onetoone'][$nidx]['source'] = array("address" => $natent['internal'] . "/" . $natent['subnet']);
2650
			}
2651

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

    
2654
			unset($config['nat']['onetoone'][$nidx]['internal']);
2655
			unset($config['nat']['onetoone'][$nidx]['subnet']);
2656
		}
2657

    
2658
		unset($natent);
2659
	}
2660
}
2661

    
2662
function upgrade_070_to_071() {
2663
	global $config;
2664

    
2665
	if (is_array($config['cron']['item'])) {
2666
		foreach ($config['cron']['item'] as $idx => $cronitem) {
2667
			if (stristr($cronitem['command'], "checkreload.sh")) {
2668
				unset($config['cron']['item'][$idx]);
2669
				break;
2670
			}
2671
		}
2672
	}
2673
}
2674

    
2675
function rename_field(& $section, $oldname, $newname) {
2676
	if (is_array($section)) {
2677
		foreach ($section as & $item) {
2678
			if (is_array($item) && !empty($item[$oldname])) {
2679
				$item[$newname] = $item[$oldname];
2680
			}
2681
			if (is_array($item) && isset($item[$oldname])) {
2682
				unset($item[$oldname]);
2683
			}
2684
		}
2685
	}
2686
}
2687

    
2688
function upgrade_071_to_072() {
2689
	global $config;
2690
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
2691
		rename_field($config['sysctl']['item'], 'desc', 'descr');
2692
	}
2693
}
2694

    
2695
function upgrade_072_to_073() {
2696
	global $config;
2697
	if (!is_array($config['load_balancer'])) {
2698
		return;
2699
	}
2700
	if (is_array($config['load_balancer']['monitor_type'])) {
2701
		rename_field($config['load_balancer']['monitor_type'], 'desc', 'descr');
2702
	}
2703
	if (is_array($config['load_balancer']['lbpool'])) {
2704
		rename_field($config['load_balancer']['lbpool'], 'desc', 'descr');
2705
	}
2706
	if (is_array($config['load_balancer']['lbaction'])) {
2707
		rename_field($config['load_balancer']['lbaction'], 'desc', 'descr');
2708
	}
2709
	if (is_array($config['load_balancer']['lbprotocol'])) {
2710
		rename_field($config['load_balancer']['lbprotocol'], 'desc', 'descr');
2711
	}
2712
	if (is_array($config['load_balancer']['virtual_server'])) {
2713
		rename_field($config['load_balancer']['virtual_server'], 'desc', 'descr');
2714
	}
2715
}
2716

    
2717
function upgrade_073_to_074() {
2718
	global $config;
2719
	rename_field($config['system']['user'], 'fullname', 'descr');
2720
}
2721

    
2722
function upgrade_074_to_075() {
2723
	global $config;
2724
	if (is_array($config['ca'])) {
2725
		rename_field($config['ca'], 'name', 'descr');
2726
	}
2727
	if (is_array($config['cert'])) {
2728
		rename_field($config['cert'], 'name', 'descr');
2729
	}
2730
	if (is_array($config['crl'])) {
2731
		rename_field($config['crl'], 'name', 'descr');
2732
	}
2733
}
2734

    
2735
function upgrade_075_to_076() {
2736
	global $config;
2737
	$cron_item = array();
2738
	$cron_item['minute'] = "30";
2739
	$cron_item['hour'] = "12";
2740
	$cron_item['mday'] = "*";
2741
	$cron_item['month'] = "*";
2742
	$cron_item['wday'] = "*";
2743
	$cron_item['who'] = "root";
2744
	$cron_item['command'] = "/usr/bin/nice -n20 /etc/rc.update_urltables";
2745
	$config['cron']['item'][] = $cron_item;
2746
}
2747

    
2748
function upgrade_076_to_077() {
2749
	global $config;
2750
	foreach ($config['filter']['rule'] as & $rule) {
2751
		if (isset($rule['protocol']) && !empty($rule['protocol'])) {
2752
			$rule['protocol'] = strtolower($rule['protocol']);
2753
		}
2754
	}
2755
}
2756

    
2757
function upgrade_077_to_078() {
2758
	global $config;
2759
	if (is_array($config['pptpd']) && is_array($config['pptpd']['radius']) &&
2760
	    !is_array($config['pptpd']['radius']['server'])) {
2761
		$radarr = array();
2762
		$radsvr = array();
2763
		$radsvr['ip'] = $config['pptpd']['radius']['server'];
2764
		$radsvr['secret'] = $config['pptpd']['radius']['secret'];
2765
		$radsvr['port'] = 1812;
2766
		$radsvr['acctport'] = 1813;
2767
		$radsvr['enable'] = isset($config['pptpd']['radius']['enable']);
2768
		$radarr['accounting'] = isset($config['pptpd']['radius']['accounting']);
2769
		if ($radarr['accounting']) {
2770
			$radarr['acct_update'] = $radsvr['ip'];
2771
		}
2772
		$radarr['server'] = $radsvr;
2773
		$config['pptpd']['radius'] = $radarr;
2774
	}
2775
	if (is_array($config['pptpd'])) {
2776
		$config['pptpd']['n_pptp_units'] = empty($config['pptpd']['n_pptp_units']) ? 16 : $config['pptpd']['n_pptp_units'];
2777
	}
2778
}
2779
function upgrade_078_to_079() {
2780
	global $g;
2781
	/* Delete old and unused RRD file */
2782
	unlink_if_exists("{$g['vardb_path']}/rrd/captiveportal-totalusers.rrd");
2783
}
2784

    
2785
function upgrade_079_to_080() {
2786
	global $config;
2787

    
2788
	/* Upgrade config in 1.2.3 specifying a username other than admin for syncing. */
2789
	if (!empty($config['system']['username']) && is_array($config['installedpackages']['carpsettings']) &&
2790
	    is_array($config['installedpackages']['carpsettings']['config'])) {
2791
		$config['installedpackages']['carpsettings']['config'][0]['username'] = $config['system']['username'];
2792
		unset($config['system']['username']);
2793
	}
2794
}
2795

    
2796
function upgrade_080_to_081() {
2797
	global $config;
2798
	global $g;
2799
	/* Welcome to the 2.1 migration path */
2800

    
2801
	/* tag all the existing gateways as being IPv4 */
2802
	$i = 0;
2803
	if (is_array($config['gateways']['gateway_item'])) {
2804
		foreach ($config['gateways']['gateway_item'] as $gw) {
2805
			$config['gateways']['gateway_item'][$i]['ipprotocol'] = "inet";
2806
			$i++;
2807
		}
2808
	}
2809

    
2810
	/* RRD files changed for quality, traffic and packets graphs */
2811
	/* convert traffic RRD file */
2812
	global $parsedcfg, $listtags;
2813
	$listtags = array("ds", "v", "rra", "row");
2814

    
2815
	$rrddbpath = "/var/db/rrd/";
2816
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
2817

    
2818
	if ($g['platform'] != $g['product_name']) {
2819
		/* restore the databases, if we have one */
2820
		if (restore_rrd()) {
2821
			/* Make sure to move the rrd backup out of the way. We will make a new one after converting. */
2822
			@rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/backup/rrd.tgz");
2823
		}
2824
	}
2825

    
2826
	$rrdinterval = 60;
2827
	$valid = $rrdinterval * 2;
2828

    
2829
	/* Asume GigE for now */
2830
	$downstream = 125000000;
2831
	$upstream = 125000000;
2832

    
2833
	/* build a list of traffic and packets databases */
2834
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
2835
	rsort($databases);
2836
	foreach ($databases as $database) {
2837
		$xmldump = "{$database}.old.xml";
2838
		$xmldumpnew = "{$database}.new.xml";
2839

    
2840
		if (platform_booting()) {
2841
			echo "Migrate RRD database {$database} to new format for IPv6.\n";
2842
		}
2843

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

    
2847
		/* search and replace tags to add data sources */
2848
		$ds_search = "<!-- Round Robin Archives -->";
2849
		$ds_arr = array();
2850
		$ds_arr[] = "	<ds>
2851
				<name> inpass6 </name>
2852
				<type> COUNTER </type>
2853
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2854
				<min> 0.0000000000e+00 </min>
2855
				<max> 1.2500000000e+08 </max>
2856

    
2857
				<!-- PDP Status -->
2858
				<last_ds> 0 </last_ds>
2859
				<value> NaN </value>
2860
				<unknown_sec> 3 </unknown_sec>
2861
			</ds>
2862
			";
2863
		$ds_arr[] = "	<ds>
2864
				<name> outpass6 </name>
2865
				<type> COUNTER </type>
2866
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2867
				<min> 0.0000000000e+00 </min>
2868
				<max> 1.2500000000e+08 </max>
2869

    
2870
				<!-- PDP Status -->
2871
				<last_ds> 0 </last_ds>
2872
				<value> NaN </value>
2873
				<unknown_sec> 3 </unknown_sec>
2874
			</ds>
2875
			";
2876
		$ds_arr[] = "	<ds>
2877
				<name> inblock6 </name>
2878
				<type> COUNTER </type>
2879
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2880
				<min> 0.0000000000e+00 </min>
2881
				<max> 1.2500000000e+08 </max>
2882

    
2883
				<!-- PDP Status -->
2884
				<last_ds> 0 </last_ds>
2885
				<value> NaN </value>
2886
				<unknown_sec> 3 </unknown_sec>
2887
			</ds>
2888
			";
2889
		$ds_arr[] = "	<ds>
2890
				<name> outblock6 </name>
2891
				<type> COUNTER </type>
2892
				<minimal_heartbeat> {$valid} </minimal_heartbeat>
2893
				<min> 0.0000000000e+00 </min>
2894
				<max> 1.2500000000e+08 </max>
2895

    
2896
				<!-- PDP Status -->
2897
				<last_ds> 0 </last_ds>
2898
				<value> NaN </value>
2899
				<unknown_sec> 3 </unknown_sec>
2900
			</ds>
2901
			";
2902

    
2903
		$cdp_search = "<\/cdp_prep>";
2904
		$cdp_replace = "</cdp_prep>";
2905
		$cdp_arr = array();
2906
		$cdp_arr[] = "			<ds>
2907
					<primary_value> NaN </primary_value>
2908
					<secondary_value> 0.0000000000e+00 </secondary_value>
2909
					<value> NaN </value>
2910
					<unknown_datapoints> 0 </unknown_datapoints>
2911
					</ds>
2912
		";
2913
		$cdp_arr[] = "			<ds>
2914
					<primary_value> NaN </primary_value>
2915
					<secondary_value> 0.0000000000e+00 </secondary_value>
2916
					<value> NaN </value>
2917
					<unknown_datapoints> 0 </unknown_datapoints>
2918
					</ds>
2919
		";
2920
		$cdp_arr[] = "			<ds>
2921
					<primary_value> NaN </primary_value>
2922
					<secondary_value> 0.0000000000e+00 </secondary_value>
2923
					<value> NaN </value>
2924
					<unknown_datapoints> 0 </unknown_datapoints>
2925
					</ds>
2926
		";
2927
		$cdp_arr[] = "			<ds>
2928
					<primary_value> NaN </primary_value>
2929
					<secondary_value> 0.0000000000e+00 </secondary_value>
2930
					<value> NaN </value>
2931
					<unknown_datapoints> 0 </unknown_datapoints>
2932
					</ds>
2933
		";
2934

    
2935
		$value_search = "<\/row>";
2936
		$value_replace = "</row>";
2937
		$value = "<v> NaN </v>";
2938

    
2939
		$xml = file_get_contents("{$g['tmp_path']}/{$xmldump}");
2940
		foreach ($ds_arr as $ds) {
2941
			$xml = preg_replace("/$ds_search/s", "$ds{$ds_search}", $xml);
2942
		}
2943
		foreach ($cdp_arr as $cdp) {
2944
			$xml = preg_replace("/$cdp_search/s", "$cdp{$cdp_replace}", $xml);
2945
		}
2946
		foreach ($ds_arr as $ds) {
2947
			$xml = preg_replace("/$value_search/s", "$value{$value_replace}", $xml);
2948
		}
2949

    
2950
		file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", $xml);
2951
		mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1");
2952
		unset($xml);
2953
		# Default /tmp tmpfs is ~40mb, do not leave temp files around
2954
		unlink_if_exists("{$g['tmp_path']}/{$xmldump}");
2955
		unlink_if_exists("{$g['tmp_path']}/{$xmldumpnew}");
2956
	}
2957
	if (!platform_booting()) {
2958
		enable_rrd_graphing();
2959
	}
2960
	/* Let's save the RRD graphs after we run enable RRD graphing */
2961
	/* The function will restore the rrd.tgz so we will save it after */
2962
	exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
2963
	if (platform_booting()) {
2964
		echo "Updating configuration...";
2965
	}
2966
	foreach ($config['filter']['rule'] as & $rule) {
2967
		if (isset($rule['protocol']) && !empty($rule['protocol'])) {
2968
			$rule['protocol'] = strtolower($rule['protocol']);
2969
		}
2970
	}
2971
	unset($rule);
2972
}
2973

    
2974
function upgrade_081_to_082() {
2975
	/* don't enable the allow IPv6 toggle */
2976
}
2977

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

    
2981
	/* Upgrade captiveportal config */
2982
	if (!empty($config['captiveportal'])) {
2983
		$tmpcp = $config['captiveportal'];
2984
		$config['captiveportal'] = array();
2985
		$config['captiveportal']['cpzone'] = array();
2986
		$config['captiveportal']['cpzone'] = $tmpcp;
2987
		$config['captiveportal']['cpzone']['zoneid'] = 8000;
2988
		$config['captiveportal']['cpzone']['zone'] = "cpzone";
2989
		if ($config['captiveportal']['cpzone']['auth_method'] == "radius") {
2990
			$config['captiveportal']['cpzone']['radius_protocol'] = "PAP";
2991
		}
2992
	}
2993
	if (!empty($config['voucher'])) {
2994
		$tmpcp = $config['voucher'];
2995
		$config['voucher'] = array();
2996
		$config['voucher']['cpzone'] = array();
2997
		$config['voucher']['cpzone'] = $tmpcp;
2998
	}
2999
}
3000

    
3001
function upgrade_083_to_084() {
3002
	global $config;
3003
	if (!isset($config['hasync'])) {
3004
		if (!empty($config['installedpackages']) &&
3005
		    !empty($config['installedpackages']['carpsettings']) &&
3006
		    !empty($config['installedpackages']['carpsettings']['config'])) {
3007
			$config['hasync'] = $config['installedpackages']['carpsettings']['config'][0];
3008
			unset($config['installedpackages']['carpsettings']);
3009
		}
3010
		if (empty($config['installedpackages']['carpsettings']) && isset($config['installedpackages']['carpsettings'])) {
3011
			unset($config['installedpackages']['carpsettings']);
3012
		}
3013
		if (empty($config['installedpackages']) && isset($config['installedpackages'])) {
3014
			unset($config['installedpackages']);
3015
		}
3016
	}
3017
}
3018

    
3019
function upgrade_084_to_085() {
3020
	global $config;
3021

    
3022
	$gateway_group_arr = array();
3023
	$gateways = return_gateways_array();
3024
	$oldnames = array();
3025
	/* setup translation array */
3026
	foreach ($gateways as $name => $gw) {
3027
		if (isset($gw['dynamic'])) {
3028
			$oldname = strtoupper($config['interfaces'][$gw['friendlyiface']]['descr']);
3029
			$oldnames[$oldname] = $name;
3030
		} else {
3031
			$oldnames[$name] = $name;
3032
		}
3033
	}
3034

    
3035
	/* process the old array */
3036
	if (is_array($config['gateways']['gateway_group'])) {
3037
		$group_array_new = array();
3038
		foreach ($config['gateways']['gateway_group'] as $name => $group) {
3039
			if (is_array($group['item'])) {
3040
				$newlist = array();
3041
				foreach ($group['item'] as $entry) {
3042
					$elements = explode("|", $entry);
3043
					if ($oldnames[$elements[0]] <> "") {
3044
						$newlist[] = "{$oldnames[$elements[0]]}|{$elements[1]}";
3045
					} else {
3046
						$newlist[] = "{$elements[0]}|{$elements[1]}";
3047
					}
3048
				}
3049
				$group['item'] = $newlist;
3050
				$group_array_new[$name] = $group;
3051
			}
3052
		}
3053
		$config['gateways']['gateway_group'] = $group_array_new;
3054
	}
3055
	/* rename old Quality RRD files in the process */
3056
	$rrddbpath = "/var/db/rrd";
3057
	foreach ($oldnames as $old => $new) {
3058
		if (is_readable("{$rrddbpath}/{$old}-quality.rrd")) {
3059
			@rename("{$rrddbpath}/{$old}-quality.rrd", "{$rrddbpath}/{$new}-quality.rrd");
3060
		}
3061
	}
3062
	unset($gateways, $oldnames, $gateway_group_arr);
3063
}
3064

    
3065
function upgrade_085_to_086() {
3066
	global $config, $g;
3067

    
3068
	/* XXX: Gross hacks in sight */
3069
	if (is_array($config['virtualip']['vip'])) {
3070
		$vipchg = array();
3071
		foreach ($config['virtualip']['vip'] as $vip) {
3072
			if ($vip['mode'] != "carp") {
3073
				continue;
3074
			}
3075
			$config = array_replace_values_recursive(
3076
				$config,
3077
				'^vip' . $vip['vhid'] . '$',
3078
				"{$vip['interface']}_vip{$vip['vhid']}"
3079
			);
3080
		}
3081
	}
3082
}
3083

    
3084
function upgrade_086_to_087() {
3085
	global $config, $dummynet_pipe_list;
3086

    
3087
	if (!is_array($config['dnshaper']) || !is_array($config['dnshaper']['queue'])) {
3088
		return;
3089
	}
3090

    
3091
	$dnqueue_number = 1;
3092
	$dnpipe_number = 1;
3093

    
3094
	foreach ($config['dnshaper']['queue'] as $idx => $dnpipe) {
3095
		$config['dnshaper']['queue'][$idx]['number'] = $dnpipe_number;
3096
		$dnpipe_number++;
3097
		if (is_array($dnpipe['queue'])) {
3098
			foreach ($dnpipe['queue'] as $qidx => $dnqueue) {
3099
				$config['dnshaper']['queue'][$idx]['queue'][$qidx]['number'] = $dnqueue_number;
3100
				$dnqueue_number++;
3101
			}
3102
		}
3103
	}
3104

    
3105
	unset($dnqueue_number, $dnpipe_number, $qidx, $idx, $dnpipe, $dnqueue);
3106

    
3107
	if (!is_array($config['filter']) || !is_array($config['filter']['rule'])) {
3108
		return;
3109
	}
3110

    
3111
	require_once("shaper.inc");
3112
	read_dummynet_config();
3113

    
3114
	$dn_list = array();
3115
	if (is_array($dummynet_pipe_list)) {
3116
		foreach ($dummynet_pipe_list as $dn) {
3117
			$tmplist =& $dn->get_queue_list();
3118
			foreach ($tmplist as $qname => $link) {
3119
				$dn_list[$link] = $qname;
3120
			}
3121
		}
3122
		unset($dummynet_pipe_list);
3123
	}
3124

    
3125
	foreach ($config['filter']['rule'] as $idx => $rule) {
3126
		if (!empty($rule['dnpipe'])) {
3127
			if (!empty($dn_list[$rule['dnpipe']])) {
3128
				$config['filter']['rule'][$idx]['dnpipe'] = $dn_list[$rule['dnpipe']];
3129
			}
3130
		}
3131
		if (!empty($rule['pdnpipe'])) {
3132
			if (!empty($dn_list[$rule['pdnpipe']])) {
3133
				$config['filter']['rule'][$idx]['pdnpipe'] = $dn_list[$rule['pdnpipe']];
3134
			}
3135
		}
3136
	}
3137
}
3138
function upgrade_087_to_088() {
3139
	global $config;
3140
	if (isset($config['system']['glxsb_enable'])) {
3141
		unset($config['system']['glxsb_enable']);
3142
		$config['system']['crypto_hardware'] = "glxsb";
3143
	}
3144
}
3145

    
3146
function upgrade_088_to_089() {
3147
	global $config;
3148
	if (!is_array($config['ca'])) {
3149
		$config['ca'] = array();
3150
	}
3151
	if (!is_array($config['cert'])) {
3152
		$config['cert'] = array();
3153
	}
3154

    
3155
	/* migrate captive portal ssl to certificate manager */
3156
	if (is_array($config['captiveportal'])) {
3157
		foreach ($config['captiveportal'] as $id => &$setting) {
3158
			if (isset($setting['httpslogin'])) {
3159
				/* create cert entry */
3160
				$cert = array();
3161
				$cert['refid'] = uniqid();
3162
				$cert['descr'] = "Captive Portal Cert - {$setting['zone']}";
3163
				$cert['crt'] = $setting['certificate'];
3164
				$cert['prv'] = $setting['private-key'];
3165

    
3166
				if (!empty($setting['cacertificate'])) {
3167
					/* create ca entry */
3168
					$ca = array();
3169
					$ca['refid'] = uniqid();
3170
					$ca['descr'] = "Captive Portal CA - {$setting['zone']}";
3171
					$ca['crt'] = $setting['cacertificate'];
3172
					$config['ca'][] = $ca;
3173

    
3174
					/* add ca reference to certificate */
3175
					$cert['caref'] = $ca['refid'];
3176
				}
3177

    
3178
				$config['cert'][] = $cert;
3179

    
3180
				/* create cert reference */
3181
				$setting['certref'] = $cert['refid'];
3182

    
3183
				unset($setting['certificate']);
3184
				unset($setting['private-key']);
3185
				unset($setting['cacertificate']);
3186

    
3187
			}
3188
		}
3189
	}
3190
}
3191

    
3192
function upgrade_089_to_090() {
3193
	global $config;
3194
	if (is_array($config['load_balancer']['virtual_server']) && count($config['load_balancer']['virtual_server'])) {
3195
		$vs_a = &$config['load_balancer']['virtual_server'];
3196
		for ($i = 0; isset($vs_a[$i]); $i++) {
3197
			if (is_array($vs_a[$i]['pool'])) {
3198
				$vs_a[$i]['poolname'] = $vs_a[$i]['pool'][0];
3199
				unset($vs_a[$i]['pool']);
3200
			} elseif (!empty($vs_a[$i]['pool'])) {
3201
				$vs_a[$i]['poolname'] = $vs_a[$i]['pool'];
3202
				unset($vs_a[$i]['pool']);
3203
			}
3204
		}
3205
	}
3206
}
3207

    
3208
function upgrade_090_to_091() {
3209
	global $config;
3210

    
3211
	if (is_array($config['dnshaper']) && is_array($config['dnshaper']['queue'])) {
3212
		foreach ($config['dnshaper']['queue'] as $idx => $dnqueue) {
3213
			if (!empty($dnqueue['bandwidth'])) {
3214
				$bw = array();
3215
				$bw['bw'] = $dnqueue['bandwidth'];
3216
				$bw['bwscale'] = $dnqueue['bandwidthtype'];
3217
				$bw['bwsched'] = "none";
3218
				$config['dnshaper']['queue'][$idx]['bandwidth'] = array();
3219
				$config['dnshaper']['queue'][$idx]['bandwidth']['item'] = array();
3220
				$config['dnshaper']['queue'][$idx]['bandwidth']['item'][] = $bw;
3221
			}
3222
		}
3223
	}
3224
}
3225

    
3226
function upgrade_091_to_092() {
3227
	global $config;
3228

    
3229
	if (is_array($config['nat']['advancedoutbound']) && is_array($config['nat']['advancedoutbound']['rule'])) {
3230
		$nat_rules = &$config['nat']['advancedoutbound']['rule'];
3231
		for ($i = 0; isset($nat_rules[$i]); $i++) {
3232
			if (empty($nat_rules[$i]['interface'])) {
3233
				$nat_rules[$i]['interface'] = 'wan';
3234
			}
3235
		}
3236
	}
3237
}
3238

    
3239
function upgrade_092_to_093() {
3240
	global $g;
3241

    
3242
	$suffixes = array("concurrent", "loggedin");
3243

    
3244
	foreach ($suffixes as $suffix) {
3245
		if (file_exists("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd")) {
3246
			rename("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd",
3247
				"{$g['vardb_path']}/rrd/captiveportal-cpZone-{$suffix}.rrd");
3248
		}
3249
	}
3250

    
3251
	if (!platform_booting()) {
3252
		enable_rrd_graphing();
3253
	}
3254
}
3255

    
3256
function upgrade_093_to_094() {
3257
	global $config;
3258

    
3259
	if (isset($config['system']['powerd_mode'])) {
3260
		$config['system']['powerd_ac_mode'] = $config['system']['powerd_mode'];
3261
		$config['system']['powerd_battery_mode'] = $config['system']['powerd_mode'];
3262
		unset($config['system']['powerd_mode']);
3263
	}
3264
}
3265

    
3266
function upgrade_094_to_095() {
3267
	global $config;
3268

    
3269
	if (!isset($config['interfaces']) || !is_array($config['interfaces'])) {
3270
		return;
3271
	}
3272

    
3273
	foreach ($config['interfaces'] as $iface => $cfg) {
3274
		if (isset($cfg['ipaddrv6']) && ($cfg['ipaddrv6'] == "track6")) {
3275
			if (!isset($cfg['track6-prefix-id']) || ($cfg['track6-prefix-id'] == "")) {
3276
				$config['interfaces'][$iface]['track6-prefix-id'] = 0;
3277
			}
3278
		}
3279
	}
3280
}
3281

    
3282
function upgrade_095_to_096() {
3283
	global $config, $g;
3284

    
3285
	$names = array("inpass", "outpass", "inblock", "outblock",
3286
		"inpass6", "outpass6", "inblock6", "outblock6");
3287
	$rrddbpath = "/var/db/rrd";
3288
	$rrdtool = "/usr/local/bin/rrdtool";
3289

    
3290
	if ($g['platform'] != $g['product_name']) {
3291
		/* restore the databases, if we have one */
3292
		if (restore_rrd()) {
3293
			/* Make sure to move the rrd backup out of the way. We will make a new one after converting. */
3294
			@rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/backup/rrd.tgz");
3295
		}
3296
	}
3297

    
3298
	/* Assume 2*10GigE for now */
3299
	$stream = 2500000000;
3300

    
3301
	/* build a list of traffic and packets databases */
3302
	$databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/');
3303
	rsort($databases);
3304
	foreach ($databases as $database) {
3305
		if (platform_booting()) {
3306
			echo "Update RRD database {$database}.\n";
3307
		}
3308

    
3309
		$cmd = "{$rrdtool} tune {$rrddbpath}/{$database}";
3310
		foreach ($names as $name) {
3311
			$cmd .= " -a {$name}:{$stream}";
3312
		}
3313
		mwexec("{$cmd} 2>&1");
3314

    
3315
	}
3316
	if (!platform_booting()) {
3317
		enable_rrd_graphing();
3318
	}
3319
	/* Let's save the RRD graphs after we run enable RRD graphing */
3320
	/* The function will restore the rrd.tgz so we will save it after */
3321
	exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
3322
}
3323

    
3324
function upgrade_096_to_097() {
3325
	global $config, $g;
3326
	/* If the user had disabled default block rule logging before, then bogon/private network logging was already off, so respect their choice. */
3327
	if (isset($config['syslog']['nologdefaultblock'])) {
3328
		$config['syslog']['nologbogons'] = true;
3329
		$config['syslog']['nologprivatenets'] = true;
3330
	}
3331
}
3332

    
3333
function upgrade_097_to_098() {
3334
	// no longer used (used to set kill_states)
3335
	return;
3336
}
3337

    
3338
function upgrade_098_to_099() {
3339
	global $config;
3340

    
3341
	if (empty($config['dhcpd']) || !is_array($config['dhcpd'])) {
3342
		return;
3343
	}
3344

    
3345
	foreach ($config['dhcpd'] as & $dhcpifconf) {
3346
		if (isset($dhcpifconf['next-server'])) {
3347
			$dhcpifconf['nextserver'] = $dhcpifconf['next-server'];
3348
			unset($dhcpifconf['next-server']);
3349
		}
3350
	}
3351
}
3352

    
3353
function upgrade_099_to_100() {
3354
	require_once("/etc/inc/services.inc");
3355
	install_cron_job("/usr/bin/nice -n20 newsyslog", false);
3356
}
3357

    
3358
function upgrade_100_to_101() {
3359
	global $config, $g;
3360

    
3361
	if (!is_array($config['voucher'])) {
3362
		return;
3363
	}
3364

    
3365
	foreach ($config['voucher'] as $cpzone => $cp) {
3366
		if (!is_array($cp['roll'])) {
3367
			continue;
3368
		}
3369
		foreach ($cp['roll'] as $ridx => $rcfg) {
3370
			if (!empty($rcfg['comment'])) {
3371
				$config['voucher'][$cpzone]['roll'][$ridx]['descr'] = $rcfg['comment'];
3372
			}
3373
		}
3374
	}
3375
}
3376

    
3377
function upgrade_101_to_102() {
3378
	global $config, $g;
3379

    
3380
	if (is_array($config['captiveportal'])) {
3381
		foreach ($config['captiveportal'] as $cpzone => $cp) {
3382
			if (!is_array($cp['passthrumac'])) {
3383
				continue;
3384
			}
3385

    
3386
			foreach ($cp['passthrumac'] as $idx => $passthrumac) {
3387
				$config['captiveportal'][$cpzone]['passthrumac'][$idx]['action'] = 'pass';
3388
			}
3389
		}
3390
	}
3391

    
3392
	/* Convert OpenVPN Compression option to the new style */
3393
	// Nothing to do if there is no OpenVPN tag
3394
	if (isset($config['openvpn']) && is_array($config['openvpn'])) {
3395
		if (is_array($config['openvpn']['openvpn-server'])) {
3396
			foreach ($config['openvpn']['openvpn-server'] as &$vpn) {
3397
				if (!empty($vpn['compression'])) {
3398
					$vpn['compression'] = "adaptive";
3399
				}
3400
			}
3401
		}
3402
		if (is_array($config['openvpn']['openvpn-client'])) {
3403
			foreach ($config['openvpn']['openvpn-client'] as &$vpn) {
3404
				if (!empty($vpn['compression'])) {
3405
					$vpn['compression'] = "adaptive";
3406
				}
3407
			}
3408
		}
3409
	}
3410
}
3411

    
3412
function upgrade_102_to_103() {
3413
	global $config;
3414

    
3415
	if (isset($config['nat']['advancedoutbound']['enable'])) {
3416
		$config['nat']['advancedoutbound']['mode'] = "advanced";
3417
		unset($config['nat']['advancedoutbound']['enable']);
3418
	} else {
3419
		$config['nat']['advancedoutbound']['mode'] = "automatic";
3420
	}
3421

    
3422
	$config['nat']['outbound'] = $config['nat']['advancedoutbound'];
3423

    
3424
	if (isset($config['nat']['ipsecpassthru'])) {
3425
		unset($config['nat']['ipsecpassthru']);
3426
	}
3427
	if (isset($config['nat']['advancedoutbound'])) {
3428
		unset($config['nat']['advancedoutbound']);
3429
	}
3430
}
3431

    
3432
function upgrade_103_to_104() {
3433
	global $config;
3434

    
3435
	$changed_privs = array(
3436
		"page-diag-system-activity" => "page-diagnostics-system-activity",
3437
		"page-interfacess-groups" => "page-interfaces-groups",
3438
		"page-interfacess-lagg" => "page-interfaces-lagg",
3439
		"page-interfacess-qinq" => "page-interfaces-qinq"
3440
	);
3441

    
3442
	/* update user privileges */
3443
	foreach ($config['system']['user'] as & $user) {
3444
		if (!is_array($user['priv'])) {
3445
			continue;
3446
		}
3447
		foreach ($user['priv'] as & $priv) {
3448
			if (array_key_exists($priv, $changed_privs)) {
3449
				$priv = $changed_privs[$priv];
3450
			}
3451
		}
3452
	}
3453

    
3454
	/* update group privileges */
3455
	foreach ($config['system']['group'] as & $group) {
3456
		if (!is_array($group['priv'])) {
3457
			continue;
3458
		}
3459
		foreach ($group['priv'] as & $priv) {
3460
			if (array_key_exists($priv, $changed_privs)) {
3461
				$priv = $changed_privs[$priv];
3462
			}
3463
		}
3464
	}
3465

    
3466
	/* sync all local account information */
3467
	local_sync_accounts();
3468
}
3469

    
3470
function upgrade_104_to_105() {
3471
	global $config;
3472

    
3473
	if (is_array($config['captiveportal'])) {
3474
		$zoneid = 2;
3475
		foreach ($config['captiveportal'] as $cpzone => $cpcfg) {
3476
			if (empty($cpcfg['zoneid'])) {
3477
				$config['captiveportal'][$cpzone]['zoneid'] = $zoneid;
3478
				$zoneid += 2;
3479
			} else if ($cpcfg['zoneid'] > 4000) {
3480
				$config['captiveportal'][$cpzone]['zoneid'] = $zoneid;
3481
				$zoneid += 2;
3482
			}
3483
		}
3484
	}
3485
}
3486

    
3487
function upgrade_105_to_106() {
3488
	/* NOTE: This upgrade code was reverted. See redmine ticket #3967 and
3489
	   https://github.com/pfsense/pfsense/commit/6f55af1c25f5232ffe905a90f5f97aad4c87bdfa */
3490
}
3491

    
3492
function upgrade_106_to_107() {
3493
	global $config;
3494

    
3495
	if (is_array($config['filter']) && is_array($config['filter']['rule'])) {
3496
		$tracker = (int)microtime(true);
3497
		foreach ($config['filter']['rule'] as $ridx => $rule) {
3498
			if (empty($rule['tracker'])) {
3499
				$config['filter']['rule'][$ridx]['tracker'] = $tracker;
3500
				$tracker++;
3501
			}
3502
		}
3503
		unset($tracker, $ridx);
3504
	}
3505
	if (is_array($config['nat']) && is_array($config['nat']['rule'])) {
3506
		$tracker = (int)microtime(true);
3507
		foreach ($config['nat']['rule'] as $ridx => $rule) {
3508
			if (empty($rule['tracker'])) {
3509
				$config['nat']['rule'][$ridx]['tracker'] = $tracker;
3510
				$tracker++;
3511
			}
3512
		}
3513
		unset($tracker, $ridx);
3514
	}
3515
}
3516

    
3517
function upgrade_107_to_108() {
3518
	global $config;
3519

    
3520
	if (isset($config['system']['webgui']['noautocomplete'])) {
3521
		unset($config['system']['webgui']['noautocomplete']);
3522
	} else {
3523
		$config['system']['webgui']['loginautocomplete'] = true;
3524
	}
3525
}
3526

    
3527
function upgrade_108_to_109() {
3528
	global $config;
3529

    
3530
	if (!isset($config['filter']['rule']) || !is_array($config['filter']['rule'])) {
3531
		return;
3532
	}
3533

    
3534
	foreach ($config['filter']['rule'] as &$rule) {
3535
		if (!isset($rule['dscp']) || empty($rule['dscp'])) {
3536
			continue;
3537
		}
3538

    
3539
		$pos = strpos($rule['dscp'], ' ');
3540
		if ($pos !== false) {
3541
			$rule['dscp'] = substr($rule['dscp'], 0, $pos);
3542
		}
3543
		unset($pos);
3544
	}
3545
}
3546

    
3547
function upgrade_109_to_110() {
3548
	global $config;
3549

    
3550
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3551
		return;
3552
	}
3553

    
3554
	foreach ($config['ipsec']['phase2'] as &$rule) {
3555
		if (!empty($rule['uniqid'])) {
3556
			continue;
3557
		}
3558

    
3559
		$rule['uniqid'] = uniqid();
3560
	}
3561
}
3562

    
3563
function upgrade_110_to_111() {
3564
	global $config;
3565

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

    
3570
	/* cleanup old unbound package stuffs */
3571
	unlink_if_exists("/usr/local/pkg/unbound.xml");
3572
	unlink_if_exists("/usr/local/pkg/unbound.inc");
3573
	unlink_if_exists("/usr/local/pkg/unbound_advanced.xml");
3574
	unlink_if_exists("/usr/local/www/unbound_status.php");
3575
	unlink_if_exists("/usr/local/www/unbound_acls.php");
3576
	unlink_if_exists("/usr/local/bin/unbound_monitor.sh");
3577
	unlink_if_exists("/usr/local/etc/rc.d/unbound.sh");
3578

    
3579
	/* Remove old menu and service entries */
3580
	if (isset($config['installedpackages']['menu']) && is_array($config['installedpackages']['menu'])) {
3581
		foreach ($config['installedpackages']['menu'] as $idx => $menu) {
3582
			if ($menu['name'] != 'Unbound DNS') {
3583
				continue;
3584
			}
3585

    
3586
			unset($config['installedpackages']['menu'][$idx]);
3587
			break;
3588
		}
3589
	}
3590

    
3591
	if (isset($config['installedpackages']['service']) && is_array($config['installedpackages']['service'])) {
3592
		foreach ($config['installedpackages']['service'] as $idx => $service) {
3593
			if ($service['name'] != 'unbound') {
3594
				continue;
3595
			}
3596
			unset($config['installedpackages']['service'][$idx]);
3597
			break;
3598
		}
3599
	}
3600

    
3601
	if (!isset($config['installedpackages']['unbound']['config'][0])) {
3602
		return;
3603
	}
3604

    
3605
	$pkg = $config['installedpackages']['unbound']['config'][0];
3606

    
3607
	if (isset($config['installedpackages']['unboundadvanced']['config'][0])) {
3608
		$pkg = array_merge($pkg, $config['installedpackages']['unboundadvanced']['config'][0]);
3609
	}
3610

    
3611
	$new = array();
3612

    
3613
	/* deal first with boolean fields */
3614
	$fields = array(
3615
		"enable" => "enable",
3616
		"dnssec_status" => "dnssec",
3617
		"forwarding_mode" => "forwarding",
3618
		"regdhcp" => "regdhcp",
3619
		"regdhcpstatic" => "regdhcpstatic",
3620
		"txtsupport" => "txtsupport",
3621
		"hide_id" => "hideidentity",
3622
		"hide_version" => "hideversion",
3623
		"prefetch" => "prefetch",
3624
		"prefetch_key" => "prefetchkey",
3625
		"harden_glue" => "hardenglue",
3626
		"harden_dnssec_stripped" => "dnssec_stripped");
3627

    
3628
	foreach ($fields as $oldk => $newk) {
3629
		if (isset($pkg[$oldk])) {
3630
			if ($pkg[$oldk] == 'on') {
3631
				$new[$newk] = true;
3632
			}
3633
			unset($pkg[$oldk]);
3634
		}
3635
	}
3636

    
3637
	$fields = array(
3638
		"active_interface" => "network_interface",
3639
		"query_interface" => "outgoing_interface",
3640
		"unbound_verbosity" => "log_verbosity",
3641
		"msg_cache_size" => "msgcachesize",
3642
		"outgoing_num_tcp" => "outgoing_num_tcp",
3643
		"incoming_num_tcp" => "incoming_num_tcp",
3644
		"edns_buffer_size" => "edns_buffer_size",
3645
		"num_queries_per_thread" => "num_queries_per_thread",
3646
		"jostle_timeout" => "jostle_timeout",
3647
		"cache_max_ttl" => "cache_max_ttl",
3648
		"cache_min_ttl" => "cache_min_ttl",
3649
		"infra_host_ttl" => "infra_host_ttl",
3650
		"infra_cache_numhosts" => "infra_cache_numhosts",
3651
		"unwanted_reply_threshold" => "unwanted_reply_threshold",
3652
		"custom_options" => "custom_options");
3653

    
3654
	foreach ($fields as $oldk => $newk) {
3655
		if (isset($pkg[$oldk])) {
3656
			$new[$newk] = $pkg[$oldk];
3657
			unset($pkg[$oldk]);
3658
		}
3659
	}
3660

    
3661
	if (isset($new['custom_options']) && !empty($new['custom_options'])) {
3662
		$new['custom_options'] = str_replace("\r\n", "\n", $new['custom_options']);
3663
	}
3664

    
3665
	/* Following options were removed, bring them as custom_options */
3666
	if (isset($pkg['stats']) && $pkg['stats'] == "on") {
3667
		if (isset($pkg['stats_interval'])) {
3668
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "statistics-interval: {$pkg['stats_interval']}";
3669
		}
3670
		if (isset($pkg['cumulative_stats'])) {
3671
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "statistics-cumulative: {$pkg['cumulative_stats']}";
3672
		}
3673
		if (isset($pkg['extended_stats']) && $pkg['extended_stats'] == "on") {
3674
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "extended-statistics: yes";
3675
		} else {
3676
			$new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "extended-statistics: no";
3677
		}
3678
	}
3679

    
3680
	$new['acls'] = array();
3681
	if (isset($config['installedpackages']['unboundacls']['config']) &&
3682
	    is_array($config['installedpackages']['unboundacls']['config'])) {
3683
		foreach ($config['installedpackages']['unboundacls']['config'] as $acl) {
3684
			$new['acls'][] = $acl;
3685
		}
3686
	}
3687

    
3688
	$config['unbound'] = $new;
3689

    
3690
	if (isset($config['installedpackages']['unbound'])) {
3691
		unset($config['installedpackages']['unbound']);
3692
	}
3693
	if (isset($config['installedpackages']['unboundadvanced'])) {
3694
		unset($config['installedpackages']['unboundadvanced']);
3695
	}
3696
	if (isset($config['installedpackages']['unboundacls'])) {
3697
		unset($config['installedpackages']['unboundacls']);
3698
	}
3699

    
3700
	unset($pkg, $new);
3701
}
3702

    
3703
function upgrade_111_to_112() {
3704
	global $config;
3705

    
3706
	$config['cron']['item'][] = array(
3707
		'minute' => '*/60',
3708
		'hour' => '*',
3709
		'mday' => '*',
3710
		'month' => '*',
3711
		'wday' => '*',
3712
		'who' => 'root',
3713
		'command' => '/usr/bin/nice -n20 /usr/local/sbin/expiretable -v -t 3600 webConfiguratorlockout'
3714
	);
3715
}
3716

    
3717
function upgrade_112_to_113() {
3718
	global $config;
3719

    
3720
	if (isset($config['notifications']['smtp']['ssl'])) {
3721
		if ($config['notifications']['smtp']['ssl'] == "checked") {
3722
			$config['notifications']['smtp']['ssl'] = true;
3723
		} else {
3724
			unset($config['notifications']['smtp']['ssl']);
3725
		}
3726
	}
3727

    
3728
	if (isset($config['notifications']['smtp']['tls'])) {
3729
		if ($config['notifications']['smtp']['tls'] == "checked") {
3730
			$config['notifications']['smtp']['tls'] = true;
3731
		} else {
3732
			unset($config['notifications']['smtp']['tls']);
3733
		}
3734
	}
3735
}
3736

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

    
3740
	if (!isset($config['ipsec']['phase1']) ||
3741
	    !is_array($config['ipsec']['phase1'])) {
3742
		return;
3743
	}
3744

    
3745
	foreach ($config['ipsec']['phase1'] as &$ph1ent) {
3746
		if (!isset($ph1ent['iketype'])) {
3747
			$ph1ent['iketype'] = 'ikev1';
3748
		}
3749
	}
3750
}
3751

    
3752
function upgrade_114_to_115() {
3753
	global $config;
3754

    
3755
	if (isset($config['unbound']['custom_options'])) {
3756
		$config['unbound']['custom_options'] = base64_encode($config['unbound']['custom_options']);
3757
	}
3758
}
3759

    
3760
function upgrade_115_to_116() {
3761
	global $config;
3762

    
3763
	if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
3764
		return;
3765
	}
3766

    
3767
	$keyid = 1;
3768
	foreach ($config['ipsec']['phase2'] as $idx => $ph2) {
3769
		$config['ipsec']['phase2'][$idx]['reqid'] = $keyid;
3770
		$keyid++;
3771
	}
3772
}
3773

    
3774
function upgrade_116_to_117() {
3775
	global $config;
3776

    
3777
	if (!isset($config['ipsec']['client']) ||
3778
	    !isset($config['ipsec']['client']['dns_split']) ||
3779
	    empty($config['ipsec']['client']['dns_split'])) {
3780
		return;
3781
	}
3782

    
3783
	$config['ipsec']['client']['dns_split'] =
3784
		preg_replace('/\s*,\s*/', ' ', trim($config['ipsec']['client']['dns_split']));
3785

    
3786
}
3787

    
3788
function upgrade_117_to_118() {
3789
	global $config;
3790

    
3791
	// 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.
3792
	if (isset($config['system']['ca'])) {
3793
		unset($config['system']['ca']);
3794
	}
3795
	if (isset($config['system']['cert'])) {
3796
		unset($config['system']['cert']);
3797
	}
3798

    
3799
	if (!isset($config['ipsec']['phase1'])) {
3800
		return;
3801
	}
3802

    
3803
	$a_phase1 =& $config['ipsec']['phase1'];
3804

    
3805
	foreach ($a_phase1 as &$ph1_entry) {
3806
		// update asn1dn strings from racoon's format to strongswan's
3807
		if (isset($ph1_entry['myid_type']) && $ph1_entry['myid_type'] == 'asn1dn') {
3808
			$ph1_entry['myid_data'] =
3809
			    preg_replace('/\/\s*emailAddress\s*=\s*/', ', E=', $ph1_entry['myid_data']);
3810
		}
3811
		if (isset($ph1_entry['peerid_type']) && $ph1_entry['peerid_type'] == 'asn1dn') {
3812
			$ph1_entry['peerid_data'] =
3813
			    preg_replace('/\/\s*emailAddress\s*=\s*/', ', E=', $ph1_entry['peerid_data']);
3814
		}
3815
	}
3816
}
3817

    
3818
function upgrade_118_to_119() {
3819
	global $config;
3820

    
3821
	if (!isset($config['ipsec']['phase1'])) {
3822
		return;
3823
	}
3824

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

    
3828
	foreach ($a_phase1 as &$ph1_entry) {
3829
		if (strstr($ph1_entry['authentication_method'], 'eap')) {
3830
			$ph1_entry['peerid_type'] = "any";
3831
		}
3832
	}
3833
}
3834

    
3835
function upgrade_119_to_120() {
3836
	require_once("ipsec.inc");
3837
	global $config, $ipsec_log_cats;
3838

    
3839
	if (!is_array($config['ipsec'])) {
3840
		return;
3841
	}
3842

    
3843
	// add 1 to configured log levels as part of redmine #5340
3844
	foreach ($ipsec_log_cats as $lkey => $ldescr) {
3845
		if (isset($config['ipsec']["ipsec_{$lkey}"])) {
3846
			$config['ipsec']["ipsec_{$lkey}"] = $config['ipsec']["ipsec_{$lkey}"] + 1;
3847
		}
3848
	}
3849

    
3850
}
3851

    
3852

    
3853
function upgrade_120_to_121() {
3854
	global $config;
3855

    
3856
	if (!isset($config['installedpackages']['miniupnpd']['config'][0])) {
3857
		return;
3858
	}
3859

    
3860
	$miniupnpd =& $config['installedpackages']['miniupnpd']['config'][0];
3861

    
3862
	$miniupnpd['row'] = array();
3863

    
3864
	for ($i = 1; $i <= 4; $i++) {
3865
		if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) {
3866
			$miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]);
3867
		}
3868
		unset($miniupnpd["permuser{$i}"]);
3869
	}
3870
}
3871

    
3872
function upgrade_121_to_122() {
3873
	global $config;
3874
	foreach ($config['system']['user'] as &$user) {
3875
		if (isset($user['nt-hash'])) {
3876
			unset($user['nt-hash']);
3877
		}
3878
	}
3879
}
3880

    
3881
function upgrade_122_to_123() {
3882
	global $config;
3883

    
3884
	// PPTP server was removed
3885
	if (isset($config['pptpd'])) {
3886
		unset($config['pptpd']);
3887
	}
3888

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

    
3910
	// Cleanup 1:1 NAT rules
3911
	if (isset($config['nat']['onetoone']) && is_array($config['nat']['onetoone'])) {
3912
		$onetoone =& $config['nat']['onetoone'];
3913
		$last_rule = count($onetoone) - 1;
3914
		// Process in reverse order to be able to unset items
3915
		for ($i = $last_rule; $i >= 0; $i--) {
3916
			if (isset($onetoone[$i]['interface']) && $onetoone[$i]['interface'] == 'pptp') {
3917
				unset($config['nat']['onetoone'][$i]);
3918
				continue;
3919
			}
3920
			if (isset($onetoone[$i]['source']['network']) && $onetoone[$i]['source']['network'] == 'pptp') {
3921
				unset($config['nat']['onetoone'][$i]);
3922
				continue;
3923
			}
3924
			if (isset($onetoone[$i]['destination']['network']) && $onetoone[$i]['destination']['network'] == 'pptp') {
3925
				unset($config['nat']['onetoone'][$i]);
3926
				continue;
3927
			}
3928
		}
3929
	}
3930

    
3931
	// Cleanup npt NAT rules
3932
	if (isset($config['nat']['npt']) && is_array($config['nat']['npt'])) {
3933
		$npt =& $config['nat']['npt'];
3934
		$last_rule = count($npt) - 1;
3935
		// Process in reverse order to be able to unset items
3936
		for ($i = $last_rule; $i >= 0; $i--) {
3937
			if (isset($npt[$i]['interface']) && $npt[$i]['interface'] == 'pptp') {
3938
				unset($config['nat']['npt'][$i]);
3939
				continue;
3940
			}
3941
		}
3942
	}
3943

    
3944
	// Cleanup Port-forward NAT rules
3945
	if (isset($config['nat']['rule']) && is_array($config['nat']['rule'])) {
3946
		$nat_rules =& $config['nat']['rule'];
3947
		$last_rule = count($nat_rules) - 1;
3948
		// Process in reverse order to be able to unset items
3949
		for ($i = $last_rule; $i >= 0; $i--) {
3950
			if (isset($nat_rules[$i]['interface']) && $nat_rules[$i]['interface'] == 'pptp') {
3951
				unset($config['nat']['rule'][$i]);
3952
				continue;
3953
			}
3954
			if (isset($nat_rules[$i]['source']['network']) && $nat_rules[$i]['source']['network'] == 'pptp') {
3955
				unset($config['nat']['rule'][$i]);
3956
				continue;
3957
			}
3958
			if (isset($nat_rules[$i]['destination']['network']) && $nat_rules[$i]['destination']['network'] == 'pptp') {
3959
				unset($config['nat']['rule'][$i]);
3960
				continue;
3961
			}
3962
		}
3963
	}
3964

    
3965
	// Cleanup Port-forward NAT rules
3966
	if (isset($config['nat']['outbound']['rule']) && is_array($config['nat']['outbound']['rule'])) {
3967
		$out_rules =& $config['nat']['outbound']['rule'];
3968
		$last_rule = count($out_rules) - 1;
3969
		// Process in reverse order to be able to unset items
3970
		for ($i = $last_rule; $i >= 0; $i--) {
3971
			if (isset($out_rules[$i]['interface']) && $out_rules[$i]['interface'] == 'pptp') {
3972
				unset($config['nat']['outbound']['rule'][$i]);
3973
				continue;
3974
			}
3975
		}
3976
	}
3977
}
3978

    
3979
function upgrade_123_to_124() {
3980
	if (isset($config['system']['altpkgrepo'])) {
3981
		unset($config['system']['altpkgrepo']);
3982
	}
3983

    
3984
	if (isset($config['theme'])) {
3985
		unset($config['theme']);
3986
	}
3987
}
3988

    
3989
function upgrade_124_to_125() {
3990
	global $config;
3991

    
3992
	/* Find interfaces with WEP configured. */
3993
	foreach ($config['interfaces'] as $ifname => $intf) {
3994
		if (!is_array($intf['wireless'])) {
3995
			continue;
3996
		}
3997

    
3998
		/* Generate a notice, disable interface, remove WEP settings */
3999
		if (isset($intf['wireless']['wep']['enable'])) {
4000
			if (!function_exists("file_notice")) {
4001
				require_once("notices.inc");
4002
			}
4003
			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));
4004
			unset($config['interfaces'][$ifname]['wireless']['wep']);
4005
			if (isset($intf['enable'])) {
4006
				unset($config['interfaces'][$ifname]['enable']);
4007
			}
4008
		}
4009
	}
4010
}
4011

    
4012
function upgrade_125_to_126() {
4013
	require_once("ipsec.inc");
4014
	global $config, $ipsec_log_cats, $ipsec_log_sevs;
4015

    
4016
	$def_loglevel = 1;
4017
	if (!is_array($config['ipsec'])) {
4018
		return;
4019
	}
4020

    
4021
	if (!isset($config['ipsec']['logging']) || !is_array($config['ipsec']['logging'])) {
4022
		$config['ipsec']['logging'] = array();
4023
	}
4024

    
4025
	/* subtract 2 from ipsec log levels. the value stored in the config.xml
4026
	 * will now match the strongswan level exactly.
4027
	 */
4028
	foreach (array_keys($ipsec_log_cats) as $cat) {
4029
		if (!isset($config['ipsec']["ipsec_{$cat}"])) {
4030
			$new_level = $def_loglevel;
4031
		} else {
4032
			$new_level = intval($config['ipsec']["ipsec_{$cat}"]) - 2;
4033
		}
4034

    
4035
		if (in_array($new_level, array_keys($ipsec_log_sevs))) {
4036
			$config['ipsec']['logging'][$cat] = $new_level;
4037
		} else {
4038
			$config['ipsec']['logging'][$cat] = $def_loglevel;
4039
		}
4040
		unset($config['ipsec']["ipsec_{$cat}"]);
4041
	}
4042
}
4043

    
4044
// prior to v2.3 <widgets><sequence> contains a list of widgets with display types:
4045
//		none, close, hide, & show
4046
// v2.3 & later uses:
4047
//		close & open
4048
// widgets not in use are simply not in the list
4049
function upgrade_126_to_127() {
4050
	global $config;
4051

    
4052
	if (!isset($config['widgets']['sequence'])) {
4053
		return;
4054
	}
4055

    
4056
	$cur_widgets = explode(',', trim($config['widgets']['sequence']));
4057
	$new_widgets = array();
4058

    
4059
	foreach ($cur_widgets as $widget) {
4060
		list($file, $col, $display) = explode(':', $widget);
4061

    
4062
		switch ($display) {
4063
			case 'hide':
4064
				$display = 'close';
4065
				break;
4066
			case 'show':
4067
				$display = 'open';
4068
				break;
4069
			case 'open':
4070
				break;
4071
			default:
4072
				continue 2;
4073
		}
4074

    
4075
		/* Remove '-container' from widget name */
4076
		$file = preg_replace('/-container$/', '', $file);
4077

    
4078
		$new_widgets[] = "{$file}:{$col}:{$display}";
4079
	}
4080

    
4081
	$config['widgets']['sequence'] = implode(',', $new_widgets);
4082

    
4083
}
4084

    
4085
function upgrade_127_to_128() {
4086
	global $config;
4087

    
4088
	// If bindip is not already specified then migrate the old SNMP bindlan flag to a bindip setting
4089
	if (isset($config['snmpd']['bindlan'])) {
4090
		if (!isset($config['snmpd']['bindip'])) {
4091
			$config['snmpd']['bindip'] = 'lan';
4092
		}
4093
		unset($config['snmpd']['bindlan']);
4094
	}
4095
}
4096

    
4097
function upgrade_128_to_129() {
4098
	global $config;
4099

    
4100
	/* net.inet.ip.fastforwarding does not exist in 2.3. */
4101
	if (!isset($config['sysctl']['item']) ||
4102
	    !is_array($config['sysctl']['item'])) {
4103
		return;
4104
	}
4105

    
4106
	foreach ($config['sysctl']['item'] as $idx => $sysctl) {
4107
		if ($sysctl['tunable'] == "net.inet.ip.fastforwarding") {
4108
			unset($config['sysctl']['item'][$idx]);
4109
		}
4110
		if ($sysctl['tunable'] == "net.inet.ipsec.debug") {
4111
			$config['sysctl']['item'][$idx]['value'] = "0";
4112
		}
4113
	}
4114

    
4115
	/* IPSEC is always on in 2.3. */
4116
	if (isset($config['ipsec']['enable'])) {
4117
		unset($config['ipsec']['enable']);
4118
	} else if (is_array($config['ipsec']['phase1'])) {
4119
		/*
4120
		 * If IPsec was globally disabled, disable all
4121
		 * phase1 entries
4122
		 */
4123
		foreach ($config['ipsec']['phase1'] as $idx => $p1) {
4124
			$config['ipsec']['phase1'][$idx]['disabled'] = true;
4125
		}
4126
	}
4127
}
4128

    
4129
function upgrade_129_to_130() {
4130
	global $config;
4131

    
4132
	/* Change OpenVPN topology_subnet checkbox into topology multi-select #5526 */
4133
	if (is_array($config['openvpn']) && is_array($config['openvpn']['openvpn-server'])) {
4134
		foreach ($config['openvpn']['openvpn-server'] as & $serversettings) {
4135
			if (strtolower($serversettings['topology_subnet']) == "yes") {
4136
				unset($serversettings['topology_subnet']);
4137
				$serversettings['topology'] = "subnet";
4138
			} else {
4139
				$serversettings['topology'] = "net30";
4140
			}
4141
		}
4142
	}
4143
}
4144

    
4145
function upgrade_130_to_131() {
4146
	global $config;
4147

    
4148
	// Default dpinger parameters at time of this upgrade (2.3)
4149
	$default_interval = 500;
4150
	$default_alert_interval = 1000;
4151
	$default_loss_interval = 2000;
4152
	$default_time_period = 60000;
4153

    
4154
	if (isset($config['syslog']['apinger'])) {
4155
		$config['syslog']['dpinger'] = true;
4156
		unset($config['syslog']['apinger']);
4157
	}
4158

    
4159
	if (isset($config['system']['apinger_debug'])) {
4160
		unset($config['system']['apinger_debug']);
4161
	}
4162

    
4163
	if (!isset($config['gateways']['gateway_item']) ||
4164
	    !is_array($config['gateways']['gateway_item'])) {
4165
		return;
4166
	}
4167

    
4168
	if (is_array($config['gateways']['gateway_item'])) {
4169
		foreach ($config['gateways']['gateway_item'] as &$gw) {
4170
			// dpinger uses milliseconds
4171
			if (isset($gw['interval']) &&
4172
				is_numeric($gw['interval'])) {
4173
				$gw['interval'] = $gw['interval'] * 1000;
4174
			}
4175

    
4176
			if (isset($gw['interval'])) {
4177
				$effective_interval = $gw['interval'];
4178
			} else {
4179
				$effective_interval = $default_interval;
4180
			}
4181

    
4182
			if (isset($gw['down']) &&
4183
				is_numeric($gw['down'])) {
4184
				$gw['time_period'] = $gw['down'] * 1000;
4185
				unset($gw['down']);
4186
			}
4187

    
4188
			if (isset($gw['time_period'])) {
4189
				$effective_time_period = $gw['time_period'];
4190
			} else {
4191
				$effective_time_period = $default_time_period;
4192
			}
4193

    
4194
			if (isset($gw['latencyhigh'])) {
4195
				// Default loss_interval is 2000, but must be set
4196
				// higher if latencyhigh is higher.
4197
				if ($gw['latencyhigh'] > $default_loss_interval) {
4198
					$gw['loss_interval'] = $gw['latencyhigh'];
4199
				}
4200
			}
4201

    
4202
			if (isset($gw['loss_interval'])) {
4203
				$effective_loss_interval = $gw['loss_interval'];
4204
			} else {
4205
				$effective_loss_interval = $default_loss_interval;
4206
			}
4207

    
4208
			if (isset($gw['interval'])) {
4209
				// Default alert_interval is 1000, but must be set
4210
				// higher if interval is higher.
4211
				if ($gw['interval'] > $default_alert_interval) {
4212
					$gw['alert_interval'] = $gw['interval'];
4213
				}
4214
			}
4215

    
4216
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4217
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4218
			}
4219

    
4220
			if (isset($gw['avg_delay_samples'])) {
4221
				unset($gw['avg_delay_samples']);
4222
			}
4223
			if (isset($gw['avg_delay_samples_calculated'])) {
4224
				unset($gw['avg_delay_samples_calculated']);
4225
			}
4226
			if (isset($gw['avg_loss_samples'])) {
4227
				unset($gw['avg_loss_samples']);
4228
			}
4229
			if (isset($gw['avg_loss_samples_calculated'])) {
4230
				unset($gw['avg_loss_samples_calculated']);
4231
			}
4232
			if (isset($gw['avg_loss_delay_samples'])) {
4233
				unset($gw['avg_loss_delay_samples']);
4234
			}
4235
			if (isset($gw['avg_loss_delay_samples_calculated'])) {
4236
				unset($gw['avg_loss_delay_samples_calculated']);
4237
			}
4238
		}
4239
	}
4240
}
4241

    
4242
function upgrade_131_to_132() {
4243
	global $config;
4244
	if (isset($config['system']['usefifolog'])) {
4245
		unset($config['system']['usefifolog']);
4246
		clear_all_log_files(false);
4247
	}
4248
}
4249

    
4250
function upgrade_132_to_133() {
4251
	global $config;
4252

    
4253
	if (isset($config['ipsec']['phase1']) &&
4254
	    is_array($config['ipsec']['phase1'])) {
4255
		foreach ($config['ipsec']['phase1'] as &$p1) {
4256
			if (isset($p1['encryption-algorithm']['name']) &&
4257
			    $p1['encryption-algorithm']['name'] == 'des') {
4258
				$p1['disabled'] = true;
4259
				file_notice("IPsec",
4260
				    sprintf(gettext("DES is no longer supported, IPsec phase 1 item '%s' is being disabled."), $p1['descr']));
4261
			}
4262
		}
4263
	}
4264

    
4265
	if (isset($config['ipsec']['phase2']) &&
4266
	    is_array($config['ipsec']['phase2'])) {
4267
		foreach ($config['ipsec']['phase2'] as &$p2) {
4268
			if (!isset($p2['encryption-algorithm-option']) ||
4269
			    !is_array($p2['encryption-algorithm-option'])) {
4270
				continue;
4271
			}
4272

    
4273
			foreach ($p2['encryption-algorithm-option'] as $ealgo) {
4274
				if ($ealgo['name'] == 'des') {
4275
					$p2['disabled'] = true;
4276
					file_notice("IPsec",
4277
					    sprintf(gettext("DES is no longer supported, IPsec phase 2 item '%s' is being disabled."), $p2['descr']));
4278
				}
4279
			}
4280
		}
4281
	}
4282
}
4283

    
4284
// Determine the highest column number in use and set dashboardcolumns accordingly
4285
function upgrade_133_to_134() {
4286
	global $config;
4287

    
4288
	if (!isset($config['widgets']['sequence']) || isset($config['system']['webgui']['dashboardcolumns'])) {
4289
		return;
4290
	}
4291

    
4292
	$cur_widgets = explode(',', trim($config['widgets']['sequence']));
4293
	$maxcols = 2;
4294

    
4295
	foreach ($cur_widgets as $widget) {
4296
		list($file, $col, $display) = explode(':', $widget);
4297

    
4298
		if (($display != 'none') && ($display != 'hide')) {
4299
			preg_match('#[0-9]+$#', $col, $column);
4300
			if ($column[0] > $maxcols) {
4301
				$maxcols = $column[0];
4302
			}
4303
		}
4304
	}
4305

    
4306
	$config['system']['webgui']['dashboardcolumns'] = $maxcols % 10;
4307
}
4308

    
4309
function upgrade_134_to_135() {
4310
	global $config;
4311

    
4312
	if (isset($config['syslog']['nologlighttpd'])) {
4313
		unset($config['syslog']['nologlighttpd']);
4314
		$config['syslog']['nolognginx'] = true;
4315
	}
4316
}
4317

    
4318
function upgrade_135_to_136() {
4319
	global $config;
4320

    
4321
	$l7_active = false;
4322
	if (isset($config['l7shaper'])) {
4323
		unset($config['l7shaper']);
4324
		if (is_array($config['filter']['rule'])) {
4325
			foreach ($config['filter']['rule'] as $idx => $rule) {
4326
				if (isset($rule['l7container'])) {
4327
					unset($config['filter']['rule'][$idx]['l7container']);
4328
					$l7_active = true;
4329
				}
4330
			}
4331
		}
4332
		if ($l7_active) {
4333
			file_notice("L7shaper", gettext("Layer 7 shaping is no longer supported. Its configuration has been removed."));
4334
		}
4335
	}
4336
}
4337

    
4338
function upgrade_136_to_137() {
4339
	global $config;
4340

    
4341
	if (is_array($config['dhcpd'])) {
4342
		foreach ($config['dhcpd'] as &$dhcpd) {
4343
			if (!is_array($dhcpd['numberoptions']['item'])) {
4344
				continue;
4345
			}
4346

    
4347
			foreach ($dhcpd['numberoptions']['item'] as &$item) {
4348
				$item['value'] = base64_encode($item['value']);
4349
			}
4350
		}
4351
	}
4352

    
4353
	if (is_array($config['dhcpdv6'])) {
4354
		foreach ($config['dhcpdv6'] as &$dhcpdv6) {
4355
			if (!is_array($dhcpdv6['numberoptions']['item'])) {
4356
				continue;
4357
			}
4358

    
4359
			foreach ($dhcpdv6['numberoptions']['item'] as &$item) {
4360
				$item['value'] = base64_encode($item['value']);
4361
			}
4362
		}
4363
	}
4364
}
4365

    
4366
function upgrade_137_to_138() {
4367
	global $config;
4368

    
4369
	// the presence of unityplugin tag used to disable loading of unity plugin
4370
	// it's now disabled by default, and config tag is to enable. Unset accordingly.
4371
	if (is_array($config['ipsec'])) {
4372
		if (isset($config['ipsec']['unityplugin'])) {
4373
			unset($config['ipsec']['unityplugin']);
4374
		}
4375
	}
4376
}
4377

    
4378
function upgrade_138_to_139() {
4379
	global $config;
4380

    
4381
	// clean up state killing on gateway failure. having kill_states set used to mean it was disabled
4382
	// now set gw_down_kill_states if enabled.
4383
	if (!isset($config['system']['kill_states'])) {
4384
		$config['system']['gw_down_kill_states'] = true;
4385
	} else {
4386
		unset($config['system']['kill_states']);
4387
	}
4388
}
4389

    
4390
function upgrade_139_to_140() {
4391
	global $config;
4392

    
4393
	if (is_array($config['virtualip']['vip'])) {
4394
		foreach ($config['virtualip']['vip'] as $idx => $vip) {
4395
			if ($vip['mode'] == "carp") {
4396
				if (!isset($vip['uniqid'])) {
4397
					$config['virtualip']['vip'][$idx]['uniqid'] = uniqid();
4398
				}
4399
			}
4400
		}
4401
	}
4402
}
4403

    
4404
function upgrade_140_to_141() {
4405
	global $config;
4406

    
4407
	// retain OpenVPN's net30 default topology for upgraded client configs so they still work
4408
	// This is for 2.3 ALPHA to a later 2.3, not 2.2.x upgrades, which had no topology setting on clients
4409
	if (is_array($config['openvpn']) && is_array($config['openvpn']['openvpn-client'])) {
4410
		foreach ($config['openvpn']['openvpn-client'] as $idx => $ovpnclient) {
4411
			if (!isset($ovpnclient['topology'])) {
4412
				$config['openvpn']['openvpn-client'][$idx]['topology'] = "net30";
4413
			}
4414
		}
4415
	}
4416

    
4417
	// repeat addition of filter tracker IDs from 106_to_107 where missing since associated filter rules were missing them
4418
	if (is_array($config['filter']) && is_array($config['filter']['rule'])) {
4419
		$tracker = (int)microtime(true);
4420
		foreach ($config['filter']['rule'] as $ridx => $rule) {
4421
			if (empty($rule['tracker'])) {
4422
				$config['filter']['rule'][$ridx]['tracker'] = $tracker;
4423
				$tracker++;
4424
			}
4425
		}
4426
		unset($tracker, $ridx);
4427
	}
4428

    
4429
}
4430

    
4431
function upgrade_141_to_142() {
4432
	global $config;
4433
	/* Convert Namecheap type DynDNS entries to the new split hostname and domain format */
4434

    
4435
	if (!is_array($config['dyndnses'])) {
4436
		$config['dyndnses'] = array();
4437
	}
4438
	if (!is_array($config['dyndnses']['dyndns'])) {
4439
		$config['dyndnses']['dyndns'] = array();
4440
	}
4441
	$a_dyndns = &$config['dyndnses']['dyndns'];
4442

    
4443
	foreach ($a_dyndns as &$dyndns) {
4444
		if ($dyndns['type'] == "namecheap") {
4445
			/* Use the old style logic to split the host and domain one last time. */
4446
			$dparts = explode(".", trim($dyndns['host']));
4447
			$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
4448
			$domain_offset = count($dparts) - $domain_part_count;
4449
			$dyndns['host'] = implode(".", array_slice($dparts, 0, $domain_offset));
4450
			$dyndns['domainname'] = implode(".", array_slice($dparts, $domain_offset));
4451
		}
4452
	}
4453

    
4454
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
4455
	if (is_array($config['cron']['item'])) {
4456
		foreach ($config['cron']['item'] as $idx => $cronitem) {
4457
			if ($cronitem['command'] == "/etc/pppoerestart") {
4458
				unset($config['cron']['item'][$idx]);
4459
			}
4460
		}
4461
	}
4462
}
4463

    
4464
// Updated to check for empty separator definitions via is_array()
4465
function upgrade_142_to_143() {
4466
	global $config;
4467

    
4468
	/* Re-index firewall rule separators per interface */
4469
	if (is_array($config['filter']['separator'])) {
4470
		foreach ($config['filter']['separator'] as $interface => $separators) {
4471

    
4472
			if (is_array($separators)) {
4473
				foreach ($separators as $sepn => $separator) {
4474

    
4475
					$seprow = substr($separator['row']['0'], 2);
4476
					$sepif  = $separator['if'];
4477

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

    
4482
						if ($i == $seprow) {
4483
							// Set separator row to it's position within the interface rules.
4484
							$config['filter']['separator'][$sepif][$sepn]['row'] = 'fr' . $j;
4485
							continue 2;	// Advance to next separator
4486
						}
4487

    
4488
						// Position within the interface rules.
4489
						if (($filterent['interface'] == $sepif && !isset($filterent['floating'])) || (isset($filterent['floating']) && "floatingrules" == $sepif)) {
4490
							$j++;
4491
						}
4492
						$i++;
4493
					}
4494
				}
4495
			}
4496
		}
4497
	}
4498

    
4499
	/* Re-index nat rule separators */
4500
	if (is_array($config['nat']['separator'])) {
4501
		foreach ($config['nat']['separator'] as $sepn => $separator) {
4502
			if (is_array($separator)) {
4503
				$seprow = substr($separator['row']['0'], 2);
4504
				$config['nat']['separator'][$sepn]['row'] = 'fr' . ($seprow + 1);
4505
			}
4506
		}
4507
	}
4508
}
4509

    
4510
function get_vip_from_ip_alias($ipalias) {
4511
	global $config;
4512

    
4513
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4514
		if ($vip['mode'] != "ipalias") {
4515
			continue;
4516
		}
4517
		if ($ipalias == $vip['subnet']) {
4518
			return ("_vip{$vip['uniqid']}");
4519
		}
4520
	}
4521

    
4522
	return ($ipalias);
4523
}
4524

    
4525
function get_vip_from_oldcarp($carp) {
4526
	global $config;
4527

    
4528
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4529
		if ($vip['mode'] != "carp") {
4530
			continue;
4531
		}
4532
		if ($carp == "{$vip['interface']}_vip{$vip['vhid']}") {
4533
			return ("_vip{$vip['uniqid']}");
4534
		}
4535
	}
4536

    
4537
	return ($carp);
4538
}
4539

    
4540
function upgrade_143_to_144() {
4541
	global $config;
4542

    
4543
	if (is_array($config['virtualip']['vip'])) {
4544
		foreach ($config['virtualip']['vip'] as $idx => $vip) {
4545
			if ($vip['mode'] == "ipalias") {
4546
				if (!isset($vip['uniqid'])) {
4547
					$config['virtualip']['vip'][$idx]['uniqid'] = uniqid();
4548
				}
4549
			}
4550
		}
4551
	}
4552

    
4553
	/* Convert IPsec phase 1 entries. */
4554
	if (is_array($config['ipsec']['phase1'])) {
4555
		foreach ($config['ipsec']['phase1'] as $idx => $ph1ent) {
4556
			if (is_ipaddr($ph1ent['interface']) || is_ipaddrv6($ph1ent['interface'])) {
4557
				$config['ipsec']['phase1'][$idx]['interface'] = get_vip_from_ip_alias($ph1ent['interface']);
4558
			} else if (strpos($ph1ent['interface'], "_vip")) {
4559
				$config['ipsec']['phase1'][$idx]['interface'] = get_vip_from_oldcarp($ph1ent['interface']);
4560
			}
4561
		}
4562
	}
4563

    
4564
	/* Convert openvpn. */
4565
	if (is_array($config['openvpn']['openvpn-server'])) {
4566
		foreach ($config['openvpn']['openvpn-server'] as $idx => $ovpn) {
4567
			if (empty($ovpn['interface'])) {
4568
				continue;
4569
			}
4570
			if (is_ipaddr($ovpn['interface']) || is_ipaddrv6($ovpn['interface'])) {
4571
				$config['openvpn']['openvpn-server'][$idx]['interface'] = get_vip_from_ip_alias($ovpn['interface']);
4572
			} else if (strpos($ovpn['interface'], "_vip")) {
4573
				$config['openvpn']['openvpn-server'][$idx]['interface'] = get_vip_from_oldcarp($ovpn['interface']);
4574
			}
4575
		}
4576
	}
4577
	if (is_array($config['openvpn']['openvpn-client'])) {
4578
		foreach ($config['openvpn']['openvpn-client'] as $idx => $ovpn) {
4579
			if (empty($ovpn['interface'])) {
4580
				continue;
4581
			}
4582
			if (is_ipaddr($ovpn['interface']) || is_ipaddrv6($ovpn['interface'])) {
4583
				$config['openvpn']['openvpn-client'][$idx]['interface'] = get_vip_from_ip_alias($ovpn['interface']);
4584
			} else if (strpos($ovpn['interface'], "_vip")) {
4585
				$config['openvpn']['openvpn-client'][$idx]['interface'] = get_vip_from_oldcarp($ovpn['interface']);
4586
			}
4587
		}
4588
	}
4589

    
4590
	/* Convert unbound. */
4591
	if (is_array($config['unbound']) && !empty($config['unbound']['active_interface'])) {
4592
		$active_ifs = explode(",", $config['unbound']['active_interface']);
4593
		$ifs = array();
4594
		foreach ($active_ifs as $if) {
4595
			if (is_ipaddr($if) || is_ipaddrv6($if)) {
4596
				$ifs[] = get_vip_from_ip_alias($if);
4597
			} else if (strpos($if, "_vip")) {
4598
				$ifs[] = get_vip_from_oldcarp($if);
4599
			} else {
4600
				$ifs[] = $if;
4601
			}
4602
		}
4603
		$config['unbound']['active_interface'] = implode(",", $ifs);
4604
	}
4605

    
4606
	/* Convert dnsmasq. */
4607
	if (is_array($config['dnsmasq']) && !empty($config['dnsmasq']['interface'])) {
4608
		$active_ifs = explode(",", $config['dnsmasq']['interface']);
4609
		$ifs = array();
4610
		foreach ($active_ifs as $if) {
4611
			if (is_ipaddr($if) || is_ipaddrv6($if)) {
4612
				$ifs[] = get_vip_from_ip_alias($if);
4613
			} else if (strpos($if, "_vip")) {
4614
				$ifs[] = get_vip_from_oldcarp($if);
4615
			} else {
4616
				$ifs[] = $if;
4617
			}
4618
		}
4619
		$config['dnsmasq']['interface'] = implode(",", $ifs);
4620
	}
4621
}
4622

    
4623
function upgrade_144_to_145() {
4624
	global $config;
4625

    
4626
	// Enable DHCPv6 server and radvd config for track6 interfaces,
4627
	// matching what used to be automatically enabled with no user
4628
	// configurability.
4629
	if (is_array($config['interfaces'])) {
4630
		foreach ($config['interfaces'] as $ifname => $ifcfg) {
4631
			if (isset($ifcfg['enable'])) {
4632
				if ($ifcfg['ipaddrv6'] == "track6") {
4633
					$config['dhcpdv6'][$ifname]['enable'] = true;
4634
					$config['dhcpdv6'][$ifname]['range']['from'] = "::1000";
4635
					$config['dhcpdv6'][$ifname]['range']['to'] = "::2000";
4636
					$config['dhcpdv6'][$ifname]['ramode'] = "assist";
4637
					$config['dhcpdv6'][$ifname]['rapriority'] = "medium";
4638
				}
4639
			}
4640
		}
4641
	}
4642
}
4643

    
4644
function upgrade_145_to_146() {
4645
	// Add standard deviation to the quality rrds
4646
	global $config, $g;
4647

    
4648
	$rrddbpath = "/var/db/rrd";
4649
	$rrdtool = "/usr/local/bin/rrdtool";
4650

    
4651
	$awkcmd = "/usr/bin/awk '";
4652
	$awkcmd .= "{\n";
4653
	$awkcmd .= "    if (sub(/<\\/v><\\/row>/, \"</v><v>NaN</v></row>\") == 0)\n";
4654
	$awkcmd .= "    {\n";
4655
	$awkcmd .= "        if (/<\\/cdp_prep>/)\n";
4656
	$awkcmd .= "        {\n";
4657
	$awkcmd .= "            print \"			<ds>\"\n";
4658
	$awkcmd .= "            print \"			<primary_value> 0.0000000000e+00 </primary_value>\"\n";
4659
	$awkcmd .= "            print \"			<secondary_value> 0.0000000000e+00 </secondary_value>\"\n";
4660
	$awkcmd .= "            print \"			<value> NaN </value>\"\n";
4661
	$awkcmd .= "            print \"			<unknown_datapoints> 0 </unknown_datapoints>\"\n";
4662
	$awkcmd .= "            print \"			</ds>\"\n";
4663
	$awkcmd .= "        }\n";
4664
	$awkcmd .= "        else if (/<!-- Round Robin Archives -->/)\n";
4665
	$awkcmd .= "        {\n";
4666
	$awkcmd .= "            print \"	<ds>\"\n";
4667
	$awkcmd .= "            print \"		<name> stddev </name>\"\n";
4668
	$awkcmd .= "            print \"		<type> GAUGE </type>\"\n";
4669
	$awkcmd .= "            print \"		<minimal_heartbeat> 120 </minimal_heartbeat>\"\n";
4670
	$awkcmd .= "            print \"		<min> 0.0000000000e+00 </min>\"\n";
4671
	$awkcmd .= "            print \"		<max> 1.0000000000e+05 </max>\\n\"\n";
4672
	$awkcmd .= "            print \"		<!-- PDP Status -->\"\n";
4673
	$awkcmd .= "            print \"		<last_ds> 0 </last_ds>\"\n";
4674
	$awkcmd .= "            print \"		<value> 0.0000000000e+00 </value>\"\n";
4675
	$awkcmd .= "            print \"		<unknown_sec> 0 </unknown_sec>\"\n";
4676
	$awkcmd .= "            print \"	</ds>\\n\"\n";
4677
	$awkcmd .= "        }\n";
4678
	$awkcmd .= "    }\n";
4679
	$awkcmd .= "    print;\n";
4680
	$awkcmd .= "}'";
4681

    
4682
	if ($g['platform'] != $g['product_name']) {
4683
		/* restore the databases, if we have one */
4684
		if (restore_rrd()) {
4685
			/* Make sure to move the rrd backup out of the way. We will make a new one after converting. */
4686
			@rename("{$g['cf_conf_path']}/rrd.tgz", "{$g['cf_conf_path']}/backup/rrd.tgz");
4687
		}
4688
	}
4689

    
4690
	$databases = return_dir_as_array($rrddbpath, '/-quality\.rrd$/');
4691
	foreach ($databases as $database) {
4692
		$xmldump = "{$g['tmp_path']}/{$database}.xml";
4693

    
4694
		if (platform_booting()) {
4695
			echo "Update RRD database {$database}.\n";
4696
		}
4697

    
4698
		exec("$rrdtool dump {$rrddbpath}/{$database} | {$awkcmd} > {$xmldump}");
4699
		exec("$rrdtool restore -f {$xmldump} {$rrddbpath}/{$database}");
4700
		@unlink("{$xmldump}");
4701
	}
4702

    
4703
	if (!platform_booting()) {
4704
		enable_rrd_graphing();
4705
	}
4706
	/* Let's save the RRD graphs after we run enable RRD graphing */
4707
	/* The function will restore the rrd.tgz so we will save it after */
4708
	exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh");
4709
}
4710

    
4711
function upgrade_bgpd_146_to_147() {
4712
	global $config;
4713

    
4714
	if (!isset($config['installedpackages']['openbgpd']['config']) ||
4715
	    !is_array($config['installedpackages']['openbgpd']['config'])) {
4716
		return;
4717
	}
4718
	$openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0];
4719
	if (!isset($openbgpd_conf['carpstatusip']) &&
4720
	    !is_ipaddr($openbgpd_conf['carpstatusip'])) {
4721
		return;
4722
	}
4723

    
4724
	if (!is_array($config['virtualip']['vip']))
4725
		return;
4726
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4727
		if ($vip['subnet'] == $openbgpd_conf['carpstatusip']) {
4728
			$openbgpd_conf['carpstatusvid'] = "_vip{$vip['uniqid']}";
4729
			unset($openbgpd_conf['carpstatusip']);
4730
			return;
4731
		}
4732
	}
4733
}
4734

    
4735
function upgrade_quagga_146_to_147() {
4736
	global $config;
4737

    
4738
	if (!isset($config['installedpackages']['quaggaospfd']['config']) ||
4739
	    !is_array($config['installedpackages']['quaggaospfd']['config'])) {
4740
		return;
4741
	}
4742
	$ospfd_conf = &$config['installedpackages']['quaggaospfd']['config'][0];
4743
	if (!isset($ospfd_conf['carpstatusip']) &&
4744
	    !is_ipaddr($ospfd_conf['carpstatusip'])) {
4745
		return;
4746
	}
4747

    
4748
	if (!is_array($config['virtualip']['vip']))
4749
		return;
4750
	foreach ($config['virtualip']['vip'] as $idx => $vip) {
4751
		if ($vip['subnet'] == $ospfd_conf['carpstatusip']) {
4752
			$ospfd_conf['carpstatusvid'] = "_vip{$vip['uniqid']}";
4753
			unset($ospfd_conf['carpstatusip']);
4754
			return;
4755
		}
4756
	}
4757
}
4758

    
4759
function upgrade_146_to_147() {
4760

    
4761
	upgrade_bgpd_146_to_147();
4762
	upgrade_quagga_146_to_147();
4763
}
4764

    
4765
function upgrade_147_to_148() {
4766
	global $config;
4767

    
4768
	// Ensure there are no spaces in group names by
4769
	// replacing spaces with underscores
4770
	if (is_array($config['system']['group'])) {
4771
		$cleargroups = false;
4772
		foreach ($config['system']['group'] as $idx => $grp) {
4773
			if (strstr($grp['name'], " ")) {
4774
				$cleargroups = true;
4775
				$config['system']['group'][$idx]['scope'] = "remote";
4776
			}
4777
		}
4778

    
4779
		// if there was a space in a group name, there may be multiple
4780
		// groups with the same name in the group file. To prevent pw 
4781
		// from getting into a neverending loop, delete all user-defined
4782
		// groups here. local_sync_accounts will run shortly after this
4783
		// and add them back. redmine #6012
4784
		if ($cleargroups) {
4785
			foreach ($config['system']['group'] as $grp) {
4786
				mwexec("/usr/sbin/pw groupdel -g {$grp['gid']}");
4787
			}
4788
		}
4789
	}
4790
}
4791

    
4792
function upgrade_148_to_149() {
4793
	global $config;
4794
	global $altq_list_queues;
4795

    
4796
        if (!isset($config['shaper']['queue']) || !is_array($config['shaper']['queue']))
4797
                return;
4798

    
4799
	read_altq_config();
4800

    
4801
	/* Set root queue bandwidth. */
4802
	foreach ($altq_list_queues as $altq) {
4803
		$sum = $altq->GetTotalBw();
4804
		while ($sum > get_queue_bandwidth($altq)) {
4805
			if (intval(($sum / 1000) * 1.2) < (1024 * 1024)) {
4806
				/* 1Gb where possible. */
4807
				$bw = 1024 * 1024;
4808
			} else {
4809
				/* Increase by 20% until it fits. */
4810
				$bw = intval(($sum / 1000) * 1.2);
4811
			}
4812
			$altq->SetBandwidth($bw);
4813
			$altq->SetBwscale("Kb");
4814
			$altq->wconfig();
4815
			$sum = $altq->GetTotalBw();
4816
		}
4817
	}
4818
}
4819

    
4820
function upgrade_149_to_150() {
4821
	global $config;
4822

    
4823
	if (is_array($config['dhcpdv6'])) {
4824
                foreach ($config['dhcpdv6'] as &$dhcpdv6) {
4825
			if (isset($dhcpdv6['rainterface'])) {
4826
				if (strstr($dhcpdv6['rainterface'], "_vip")) {
4827
					$dhcpdv6['rainterface'] = get_vip_from_oldcarp($dhcpdv6['rainterface']);
4828
				}
4829
			}
4830
		}
4831
	}
4832
}
4833

    
4834
function upgrade_150_to_151() {
4835
	global $config;
4836

    
4837
	// Default dpinger parameters at time of this upgrade (2.3.1)
4838
	$default_interval = 500;
4839
	$default_alert_interval = 1000;
4840
	$default_loss_interval = 2000;
4841
	$default_time_period = 60000;
4842
	$default_latencyhigh = 500;
4843

    
4844
	// Check advanced gateway parameter relationships in case they are incorrect
4845
	if (is_array($config['gateways']['gateway_item'])) {
4846
		foreach ($config['gateways']['gateway_item'] as &$gw) {
4847
			if (isset($gw['interval'])) {
4848
				$effective_interval = $gw['interval'];
4849
			} else {
4850
				$effective_interval = $default_interval;
4851
			}
4852

    
4853
			if (isset($gw['alert_interval'])) {
4854
				$effective_alert_interval = $gw['alert_interval'];
4855
			} else {
4856
				$effective_alert_interval = $default_alert_interval;
4857
			}
4858

    
4859
			if (isset($gw['loss_interval'])) {
4860
				$effective_loss_interval = $gw['loss_interval'];
4861
			} else {
4862
				$effective_loss_interval = $default_loss_interval;
4863
			}
4864

    
4865
			if (isset($gw['time_period'])) {
4866
				$effective_time_period = $gw['time_period'];
4867
			} else {
4868
				$effective_time_period = $default_time_period;
4869
			}
4870

    
4871
			if (isset($gw['latencyhigh'])) {
4872
				$effective_latencyhigh = $gw['latencyhigh'];
4873
			} else {
4874
				$effective_latencyhigh = $default_latencyhigh;
4875
			}
4876

    
4877
			// Loss interval has to be at least as big as high latency.
4878
			if ($effective_latencyhigh > $effective_loss_interval) {
4879
				$effective_loss_interval = $gw['loss_interval'] = $effective_latencyhigh;
4880
			}
4881

    
4882
			// Alert interval has to be at least as big as probe interval.
4883
			if ($effective_interval > $effective_alert_interval) {
4884
				$gw['alert_interval'] = $effective_interval;
4885
			}
4886

    
4887
			// The time period for averaging has to be more than 2 probes plus the loss interval.
4888
			if ((($effective_interval * 2) + $effective_loss_interval) >= $effective_time_period) {
4889
				$gw['time_period'] = ($effective_interval * 2) + $effective_loss_interval + 1;
4890
			}
4891
		}
4892
	}
4893
}
4894

    
4895
function upgrade_151_to_152() {
4896
	global $g, $config;
4897

    
4898
	require_once("/etc/inc/services.inc");
4899

    
4900
	// Remove these cron jobs on full install if not using ramdisk.
4901
	if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
4902
		install_cron_job("/etc/rc.backup_rrd.sh", false);
4903
		install_cron_job("/etc/rc.backup_dhcpleases.sh", false);
4904
	}
4905
}
4906

    
4907
function upgrade_152_to_153() {
4908
	global $config;
4909

    
4910
	if (is_array($config['virtualip']['vip'])) {
4911
		foreach ($config['virtualip']['vip'] as $idx => $vip) {
4912
			if (substr($vip['interface'], 0, 4) == "_vip") {
4913
				// using new VIP format
4914
				continue;
4915
			} else if (strstr($vip['interface'], "_vip")) {
4916
				// using old VIP format, update
4917
				$config['virtualip']['vip'][$idx]['interface'] = get_vip_from_oldcarp($vip['interface']);
4918
			}
4919
		}
4920
	}
4921

    
4922
	// upgrade GIFs using VIP to new format
4923
	if (is_array($config['gifs']['gif'])) {
4924
		foreach ($config['gifs']['gif'] as $idx => $gif) {
4925
			if (substr($gif['if'], 0, 4) == "_vip") {
4926
				// using new VIP format
4927
				continue;
4928
			} else if (strstr($gif['if'], "_vip")) {
4929
				// using old VIP format, update
4930
				$config['gifs']['gif'][$idx]['if'] = get_vip_from_oldcarp($gif['if']);
4931
			}
4932
		}
4933
	}
4934

    
4935
	// upgrade GREs using VIP to new format
4936
	if (is_array($config['gres']['gre'])) {
4937
		foreach ($config['gres']['gre'] as $idx => $gre) {
4938
			if (substr($gre['if'], 0, 4) == "_vip") {
4939
				// using new VIP format
4940
				continue;
4941
			} else if (strstr($gre['if'], "_vip")) {
4942
				// using old VIP format, update
4943
				$config['gres']['gre'][$idx]['if'] = get_vip_from_oldcarp($gre['if']);
4944
			}
4945
		}
4946
	}
4947

    
4948
	// upgrade gateway groups using VIPs
4949
	if (is_array($config['gateways']['gateway_group'])) {
4950
		foreach ($config['gateways']['gateway_group'] as $idx => $gw) {
4951
			if (is_array($gw['item'])) {
4952
				$newitems = array();
4953
				$gwvipchange = false;
4954
				foreach ($gw['item'] as $item) {
4955
					if (strstr($item, "|_vip")) {
4956
						// using new VIP format
4957
						$newitems[] = $item;
4958
						continue;
4959
					} else if (strstr($item, "_vip")) {
4960
						// using old VIP format, update
4961
						$gwitemarr = explode("|", $item);
4962
						$gwitemarr[2] = get_vip_from_oldcarp($gwitemarr[2]);
4963
						$newitems[] = implode("|", $gwitemarr);
4964
						$gwvipchange = true;
4965
					} else {
4966
						$newitems[] = $item;
4967
					}
4968
				}
4969
				if ($gwvipchange) {
4970
					$config['gateways']['gateway_group'][$idx]['item'] = $newitems;
4971
				}
4972
			}
4973
		}
4974
	}
4975
}
4976

    
4977
function upgrade_153_to_154() {
4978
	/* NOTE: This upgrade code was reverted. See redmine ticket #6118 and
4979
	   https://github.com/pfsense/pfsense/commit/538a3c04a6b6671151e913b06b2f340b6f8ee222 */
4980
}
4981

    
4982
/* Clean up old GRE/GIF options. See Redmine tickets #6586 and #6587 */
4983
function upgrade_154_to_155() {
4984
	global $config;
4985

    
4986
	if (is_array($config['gifs']['gif'])) {
4987
		foreach ($config['gifs']['gif'] as $idx => $gif) {
4988
			if (isset($gif['link0'])) {
4989
				unset($config['gifs']['gif'][$idx]['link0']);
4990
			}
4991
		}
4992
	}
4993

    
4994
	if (is_array($config['gres']['gre'])) {
4995
		foreach ($config['gres']['gre'] as $idx => $gre) {
4996
			if (isset($gre['link0'])) {
4997
				unset($config['gres']['gre'][$idx]['link0']);
4998
			}
4999
			if (isset($gre['link2'])) {
5000
				unset($config['gres']['gre'][$idx]['link2']);
5001
			}
5002
		}
5003
	}
5004
}
5005

    
5006
function upgrade_155_to_156() {
5007
	// Unused
5008
}
5009

    
5010
function upgrade_156_to_157() {
5011
	global $config;
5012
	/* Convert Cloudflare and GratisDNS type DynDNS entries to the new split hostname and domain format */
5013

    
5014
	if (!is_array($config['dyndnses'])) {
5015
		$config['dyndnses'] = array();
5016
	}
5017
	if (!is_array($config['dyndnses']['dyndns'])) {
5018
		$config['dyndnses']['dyndns'] = array();
5019
	}
5020
	$a_dyndns = &$config['dyndnses']['dyndns'];
5021

    
5022
	foreach ($a_dyndns as &$dyndns) {
5023
		if (($dyndns['type'] == "cloudflare") || ($dyndns['type'] == "cloudflare-v6") || ($dyndns['type'] == "gratisdns")) {
5024
			/* Use the old style logic to split the host and domain one last time. */
5025
			$dparts = explode(".", trim($dyndns['host']));
5026
			$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
5027
			$domain_offset = count($dparts) - $domain_part_count;
5028
			$dyndns['host'] = implode(".", array_slice($dparts, 0, $domain_offset));
5029
			$dyndns['domainname'] = implode(".", array_slice($dparts, $domain_offset));
5030
		}
5031
	}
5032

    
5033
	/* unset old pppoerestart cron job if it exists. redmine 1905 */
5034
	if (is_array($config['cron']['item'])) {
5035
		foreach ($config['cron']['item'] as $idx => $cronitem) {
5036
			if ($cronitem['command'] == "/etc/pppoerestart") {
5037
				unset($config['cron']['item'][$idx]);
5038
			}
5039
		}
5040
	}
5041
}
5042

    
5043
function upgrade_157_to_158() {
5044
	global $config;
5045
	/* Convert Dynamic DNS passwords to base64 encoding. Redmine #6688 */
5046

    
5047
	if (!is_array($config['dyndnses'])) {
5048
		$config['dyndnses'] = array();
5049
	}
5050
	if (!is_array($config['dyndnses']['dyndns'])) {
5051
		$config['dyndnses']['dyndns'] = array();
5052
	}
5053
	$a_dyndns = &$config['dyndnses']['dyndns'];
5054

    
5055
	foreach ($a_dyndns as &$dyndns) {
5056
		$dyndns['password'] = base64_encode($dyndns['password']);
5057
	}
5058
}
5059

    
5060
?>
(56-56/67)