Project

General

Profile

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

    
22
require_once("globals.inc");
23
require_once("filter.inc");
24
require_once("shaper.inc");
25
require_once("rrd.inc");
26
require_once("pfsense-utils.inc");
27

    
28
$GIT_PKG = "git"; // Either "git" or the full package URL
29
$GIT_BIN= "/usr/local/bin/git";
30
$GIT_REPO = "git://github.com/pfsense/pfsense.git";
31
$DEFAULT_BRANCH = "master";
32
$CODIR =  "/root/pfsense";
33
$GITSYNC_MERGE = "/root/.gitsync_merge";
34

    
35
/* NOTE: Set branches here */
36
$branches = array(
37
	"master" => "2.4.3 development branch",
38
	"build_commit" => "The commit originally used to build the image"
39
);
40

    
41
global $g;
42
global $argv;
43
global $command_split;
44

    
45
if (is_array($command_split)) {
46
	$temp_args = array_slice($command_split, 2);
47
} else {
48
	$temp_args = array_slice($argv, 3);
49
}
50

    
51
$valid_args = array(
52
	"--minimal" => "\tPerform a copy of only the updated files.\n" .
53
	    "\tNot recommended if the system has files modified by any method other\n" .
54
	    "\tthan gitsync.\n",
55
	"--diff" => "\tPerform a copy of only the different and missing files.\n" .
56
	    "\tRecommended for SSD if system has files modified by any method other\n" .
57
	    "\tthan gitsync.\n",
58
	"--show-files" => "\tShow the updated, different and missing files.\n" .
59
	    "\t(when used with --minimal and --diff options)\n",
60
	"--show-command" => "\tShow the constructed command.\n",
61
	"--dry-run" => "\tDry-run only.  No files copied.\n",
62
	"--help" => "\tDisplay this help list.\n"
63
	);
64
$args = array();
65
$arg_count = 0;
66
while (!empty($temp_args)) {
67
	$arg = array_shift($temp_args);
68
	if ($arg[0] == '-') {
69
		switch ($arg) {
70
			case "--help":
71
				echo "Usage: playback gitsync [options] [[repository] <branch>]\nOptions:\n";
72
				foreach ($valid_args as $arg_name => $arg_desc) {
73
					echo $arg_name . "\n" . $arg_desc;
74
				}
75
				exit;
76
			case "--upgrading":
77
				// Disables all interactive functions and neither PHP
78
				// nor the web GUI will be killed or restarted.
79
				$upgrading = true;
80
			case (isset($valid_args[$arg])):
81
				$args[$arg] = true;
82
				break;
83
			default:
84
				echo "Invalid option: {$arg}\nUse --help for usage information.\n";
85
				exit;
86
		}
87
	} else {
88
		$args[$arg_count++] = $arg;
89
	}
90
}
91

    
92
if (!function_exists('post_cvssync_commands')) {
93
function post_cvssync_commands() {
94
	echo "===> Removing FAST-CGI temporary files...\n";
95
	exec("find /tmp -name \"php-fastcgi.socket*\" -exec rm -rf {} \;");
96
	exec("find /tmp -name \"*.tmp\" -exec rm -rf {} \;");
97

    
98
	exec("rm -rf /tmp/xcache/* 2>/dev/null");
99

    
100
	echo "===> Upgrading configuration (if needed)...\n";
101
	convert_config();
102

    
103
	echo "===> Configuring filter...";
104
	exec("/etc/rc.filter_configure_sync");
105
	exec("pfctl -f /tmp/rules.debug");
106
	echo "\n";
107

    
108
	if (file_exists("/etc/rc.php_ini_setup")) {
109
		echo "===> Running /etc/rc.php_ini_setup...";
110
		exec("/etc/rc.php_ini_setup >/dev/null 2>&1");
111
		echo "\n";
112
	}
113

    
114
	/* lock down console if necessary */
115
	echo "===> Locking down the console if needed...\n";
116
	reload_ttys();
117

    
118
	echo "===> Signaling PHP and nginx restart...";
119
	$fd = fopen("/tmp/restart_nginx", "w");
120
	fwrite($fd, "#!/bin/sh\n");
121
	fwrite($fd, "sleep 5\n");
122
	fwrite($fd, "/usr/local/sbin/pfSctl -c 'service restart webgui'\n");
123
	fclose($fd);
124
	mwexec_bg("sh /tmp/restart_nginx");
125
	echo "\n";
126
}
127
}
128

    
129
if (!function_exists('isUrl')) {
130
function isUrl($url = "") {
131
	if ($url) {
132
		if (strstr($url, "rcs.pfsense.org") or
133
			strstr($url, "mainline") or
134
			strstr($url, ".git") or
135
			strstr($url, "git://")) {
136
			return true;
137
		}
138
	}
139
	return false;
140
}
141
}
142

    
143
if (!function_exists('run_cmds')) {
144
function run_cmds($cmds) {
145
	global $debug;
146
	foreach ($cmds as $cmd) {
147
		if ($debug) {
148
			echo "Running $cmd";
149
		}
150
		exec($cmd);
151
	}
152
}
153
}
154

    
155
unlink_if_exists("/tmp/config.cache");
156

    
157
if (!file_exists($GIT_BIN)) {
158
	require_once("pkg-utils.inc");
159

    
160
	echo "Cannot find git, installing...\n";
161
	if (!pkg_call('install -y -q git')) {
162
		echo "\nERROR: Unable to install git pkg.\n";
163
		return;
164
	}
165
}
166

    
167
# Remove mainline if exists (older)
168
if (is_dir("/root/pfsense/mainline")) {
169
	exec("rm -rf /root/pfsense/mainline");
170
}
171

    
172
# Remove RELENG_1_2 if exists (older)
173
if (is_dir("/root/pfsense/RELENG_1_2")) {
174
	exec("rm -rf /root/pfsense/RELENG_1_2");
175
}
176

    
177
# Remove HEAD if exists (older)
178
if (is_dir("/root/pfsense/HEAD")) {
179
	exec("rm -rf /root/pfsense/HEAD");
180
}
181

    
182
if (file_exists("/root/cvssync_backup.tgz")) {
183
	$backup_date = `ls -lah /root/cvssync_backup.tgz | awk '{ print $6,$7,$8 }'`;
184
	$tmp = array("RESTORE" => "Restores prior CVSSync backup data performed at {$backup_date}");
185
	$branches = array_merge($branches, $tmp);
186
}
187

    
188
if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
189
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} config remote.origin.url", $output_str, $ret);
190
	if (is_array($output_str) && !empty($output_str[0])) {
191
		$GIT_REPO = $output_str[0];
192
	}
193
	unset($output_str);
194
}
195

    
196
if (!$args[0] && !$upgrading) {
197
	echo "\nCurrent repository is $GIT_REPO\n";
198
	echo "\nPlease select which branch you would like to sync against:\n\n";
199
	foreach ($branches as $branchname => $branchdesc) {
200
		echo "{$branchname} \t {$branchdesc}\n";
201
	}
202
	echo "\nOr alternatively you may enter a custom RCS branch URL (Git or HTTP).\n\n";
203
	$branch = readline("> ");
204
	echo "\n";
205
} else {
206
	$branch = $args[0];
207
}
208

    
209
if ($args[1] == "NOBACKUP") {
210
	$nobackup = true;
211
} else {
212
	$nobackup = false;
213
}
214

    
215
// If the repository has been fetched before, build a list of its branches.
216
if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
217
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch -r", $branch_list, $ret);
218
	if ($ret == 0 && is_array($branch_list)) {
219
		foreach ($branch_list as $branch_item) {
220
			$branch_item = substr(strrchr($branch_item, "/"), 1);
221
			if (!isset($branches[$branch_item])) {
222
				$branches[$branch_item] = " ";
223
			}
224
		}
225
	}
226
}
227

    
228
$found = false;
229
foreach ($branches as $branchname => $branchdesc) {
230
	if ($branchname == $branch) {
231
		$found = true;
232
		break;
233
	}
234
}
235
if (!$found) {
236
	if (isURL($branch) && !$upgrading) {
237
		if ($args[1]) {
238
			$GIT_REPO = $branch;
239
			$branch = $args[1];
240
			$found = true;
241
		} else {
242
			echo "\n";
243
			echo "NOTE: $branch was not found.\n\n";
244
			$command = readline("Is this a custom GIT URL? [y]? ");
245
			if (strtolower($command) == "y" or $command == "") {
246
				$GIT_REPO = $branch;
247
				$command = readline("Checkout which branch [${DEFAULT_BRANCH}]? ");
248
				if ($command == "") {
249
					$branch = $DEFAULT_BRANCH;
250
				}
251
				if ($command) {
252
					$branch = $command;
253
				}
254
				$found = true;
255
			}
256
		}
257
	}
258
	if (!$found) {
259
		echo "\nNo valid branch found.  Exiting.\n\n";
260
		exit;
261
	}
262
}
263

    
264
$merge_repos = array();
265
if (file_exists($GITSYNC_MERGE)) {
266
	$gitsync_merges = file($GITSYNC_MERGE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
267
	if (!empty($gitsync_merges) && is_array($gitsync_merges)) {
268
		echo "\n===> Automatic merge list read from ${GITSYNC_MERGE}\n";
269
		foreach ($gitsync_merges as $merge_line_num => $merge_line) {
270
			$merge_comments = explode("#", trim($merge_line));
271
			if (empty($merge_comments[0])) {
272
				continue;
273
			}
274

    
275
			$merge_line = explode(" ", trim($merge_comments[0]));
276
			if (count($merge_line) != 2 || empty($merge_line[0]) || empty($merge_line[1])) {
277
				echo "\nLine " . ($merge_line_num + 1) . " does not have the correct parameter count or has improper spacing.\n";
278
				echo "Expected parameters:  repository_url branch\n";
279
				echo "Line read:  " . implode(" ", $merge_line) . "\n\n";
280
				echo "Aborting automatic merge.\n\n";
281
				$merge_repos = array();
282
				break;
283
			}
284
			$merge_repos[] = array('repo' => $merge_line[0], 'branch' => $merge_line[1]);
285
		}
286
	}
287
}
288
if (!$args[0] && !$upgrading) {
289
	do {
290
		echo "\nAdd a custom RCS branch URL (Git or HTTP) to merge in or press enter if done.\n\n";
291
		$merge_repo = readline("> ");
292
		if (!empty($merge_repo)) {
293
			$merge_branch = readline("Merge which branch [${DEFAULT_BRANCH}]? ");
294
			if ($merge_branch == "") {
295
				$merge_repos[] = array('repo' => $merge_repo, 'branch' => $DEFAULT_BRANCH);
296
			} else if ($merge_branch) {
297
				$merge_repos[] = array('repo' => $merge_repo, 'branch' => $merge_branch);
298
			}
299
		}
300
	} while (!empty($merge_repo));
301
}
302

    
303
if ($branch == "RESTORE") {
304
	if (!file_exists("/root/cvssync_backup.tgz")) {
305
		echo "Sorry, we could not find a previous CVSSync backup file.\n";
306
		exit();
307
	}
308
	echo "===> Restoring previous CVSSync backup... Please wait...\n";
309
	exec("tar Uxpf /root/cvssync_backup.tgz -C /");
310
	post_cvssync_commands();
311
	exit();
312
} else {
313
	$nobackup = true; // do not backup embedded
314
}
315

    
316
if ($nobackup == false) {
317
	echo "===> Backing up current pfSense information...\n";
318
	echo "===> Please wait... ";
319
	exec("tar czPf /root/cvssync_backup.tgz --exclude /root --exclude /dev --exclude /tmp --exclude /var/run --exclude /var/empty /");
320
	$size = filesize("/root/cvssync_backup.tgz");
321
	echo "{$size} bytes.\n\n";
322
	sleep(5);
323
}
324

    
325
echo "===> Checking out $branch\n";
326

    
327
// Git commands for resetting to the specified branch
328
if ($branch == "build_commit") {
329
	$git_cmd = array(
330
		"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch " . escapeshellarg($branch) . " 2>/dev/null",
331
		"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} checkout -f " . escapeshellarg($branch) . " 2>/dev/null",
332
		"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} reset --hard " . escapeshellarg(trim(file_get_contents("/etc/version.lastcommit")))
333
	);
334
} else {
335
	$git_cmd = array(
336
		"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch " . escapeshellarg($branch) . " " . escapeshellarg("origin/{$branch}") . " 2>/dev/null",
337
		"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} checkout -f " . escapeshellarg($branch) . " 2>/dev/null",
338
		"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} reset --hard " . escapeshellarg("origin/{$branch}")
339
	);
340
}
341

    
342
// Git 'er done!
343
if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
344
	echo "===> Fetching updates...\n";
345
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} config remote.origin.url " . escapeshellarg($GIT_REPO));
346
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} fetch");
347
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} clean -f -x -d");
348
	run_cmds($git_cmd);
349
} else {
350
	exec("mkdir -p $CODIR/pfSenseGITREPO");
351
	echo "Executing cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone $GIT_REPO pfSenseGITREPO\n";
352
	exec("cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone " . escapeshellarg($GIT_REPO) . " pfSenseGITREPO");
353
	if (is_dir("$CODIR/pfSenseGITREPO/pfSense")) {
354
		exec("mv $CODIR/pfSenseGITREPO/pfSense $CODIR/pfSenseGITREPO/pfSenseGITREPO");
355
	}
356
	if (is_dir("$CODIR/pfSenseGITREPO/mainline")) {
357
		exec("mv $CODIR/pfSenseGITREPO/mainline $CODIR/pfSenseGITREPO/pfSenseGITREPO");
358
	}
359
	run_cmds($git_cmd);
360
}
361

    
362
foreach ($merge_repos as $merge_repo) {
363
	echo "===> Merging branch {$merge_repo['branch']} from {$merge_repo['repo']}\n";
364
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} pull " . escapeshellarg($merge_repo['repo']) . " " . escapeshellarg($merge_repo['branch']), $output_str, $ret);
365
	unset($output_str);
366
	if ($ret <> 0) {
367
		echo "\nMerge failed.  Aborting sync.\n\n";
368
		run_cmds($git_cmd);
369
		exit;
370
	}
371
}
372

    
373
$updated_files_array[1] = array();
374
if (isset($args["--minimal"])) {
375
	if (file_exists("/etc/version.gitsync")) {
376
		$old_revision = trim(file_get_contents("/etc/version.gitsync"));
377
	} else if (file_exists("/etc/version.lastcommit")) {
378
		$old_revision = trim(file_get_contents("/etc/version.lastcommit"));
379
	}
380

    
381
	# Find updated files.
382
	$updated_files = shell_exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} diff --name-only --relative=src " . escapeshellarg($old_revision));
383

    
384
	# Get the path of each updated file.
385
	preg_match_all('@(?:^(.+?)$)@sim', $updated_files, $updated_files_array, PREG_PATTERN_ORDER);
386

    
387
	if(isset($args["--show-files"])) {
388
		echo "===> Updated Files: \n";
389
		print_r($updated_files_array[1]);
390
	}
391
}
392

    
393
// Save new commit ID for later minimal file copies
394
if(!isset($args["--dry-run"])) {
395
	exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} rev-parse -q --verify HEAD > /etc/version.gitsync");
396
}
397

    
398
// Remove files that we do not want to overwrite the system with
399
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/crontab");
400
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/master.passwd");
401
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/passwd");
402
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/fstab");
403
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/ttys");
404
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/group");
405
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/fstab");
406
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/platform");
407
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/boot/device.hints");
408
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/boot/loader.conf");
409
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/boot/loader.rc");
410
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/etc/syslog.conf");
411
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/root/.shrc");
412
@unlink("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/root/.tcshrc");
413
exec("rm -rf {$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/conf*");
414
exec("rm -rf {$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/cf 2>/dev/null");
415
@chmod("{$CODIR}/pfSenseGITREPO/pfSenseGITREPO/src/tmp", 01777);
416

    
417
$different_files_array[1] = array();
418
$missing_files_array[1] = array();
419
if(isset($args["--diff"])) {
420
	# Find different and missing files.
421
	$different_missing_files = shell_exec("/usr/bin/diff -qr / $CODIR/pfSenseGITREPO/pfSenseGITREPO/src/ | /usr/bin/grep -E '^(Files .*? and $CODIR/pfSenseGITREPO/pfSenseGITREPO/src/.*? differ)|(Only in $CODIR/pfSenseGITREPO/pfSenseGITREPO/src/)'");
422

    
423
	# Get the path of each different or missing file.
424
	preg_match_all('@(?:^Files .*? and '.$CODIR.'/pfSenseGITREPO/pfSenseGITREPO/src/(.+?) differ.*?$)@sim', $different_missing_files, $different_files_array, PREG_PATTERN_ORDER);
425
	preg_match_all('@(?:^Only in '.$CODIR.'/pfSenseGITREPO/pfSenseGITREPO/src/(.+?)$)@sim', $different_missing_files, $missing_files_array, PREG_PATTERN_ORDER);
426

    
427
	# Deal with diff's output format of missing files (path: missing_file).
428
	foreach ($missing_files_array[1] as $key => $file) {
429

    
430
		# Most of the time there will be only the one ': ' injected by diff output.  So global replace with dir delimiter (/) is fine.
431
		$tmp = str_replace(": ", "/", $file, $count);
432
		if ($count == 1)
433
			$file = ltrim($tmp, "/");
434

    
435
		# For the very rare case a path component (dir or file) contains ': ' as well, then need to find and replace only the ': ' injected by diff output.
436
		else {
437
			$tmp = $file;
438
			do {
439
				$pos = strrpos($tmp, ": ");
440
				if ($pos) {
441
					$tmp = substr($tmp, 0, $pos);
442
					$res = is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO/src/$tmp/");
443
				}
444
			} while (!$res && $pos);
445

    
446
			if ($res)
447
				$file = ltrim($tmp . "/" . substr($file, $pos+2), "/");
448
		}
449

    
450
		$missing_files_array[1][$key] = $file;
451
	}
452

    
453
	if(isset($args["--show-files"])) {
454
		echo "===> Different Files: \n";
455
		print_r($different_files_array[1]);
456
		echo "===> Missing Files: \n";
457
		print_r($missing_files_array[1]);
458
	}
459
}
460

    
461
# Files to be copied.
462
if(isset($args["--minimal"]) || isset($args["--diff"])) {
463
	$files_to_copy_array = array_merge($updated_files_array[1], $different_files_array[1], $missing_files_array[1]);
464
	$files_to_copy_array = array_unique($files_to_copy_array);
465

    
466
	unset($updated_files_array, $different_files_array, $missing_files_array);
467

    
468
	# Convert the list from an array to a space separated quoted string.  Quoted for white space file name support.
469
	if (count($files_to_copy_array) > 0) {	# Leave the string empty/unset if there is nothing to copy.
470
		$files_to_copy = '"' . implode('" "', $files_to_copy_array) . '"';
471
	}
472
	$qty_files_to_copy = count($files_to_copy_array);
473
	unset($files_to_copy_array);
474
} else {
475
	$files_to_copy = '.';
476
	$qty_files_to_copy = chr(8);
477
}
478

    
479
$tar_options = '-C ./src';
480

    
481
echo "===> Installing $qty_files_to_copy new files...\n";
482

    
483
$command = "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO ; tar -cpf - {$tar_options} {$files_to_copy} | (cd / ; tar -Uxpf -)";
484

    
485
if (!empty($files_to_copy)) {
486
	if(isset($args["--show-command"])) {
487
		echo "===> Command: \n$command\n";
488
	}
489
	if(!isset($args["--dry-run"])) {
490
		exec($command);
491
	}
492
} else {
493
	echo "Already up-to-date.\n";
494
	$upgrading = true;
495
}
496

    
497
// Reset the repository to restore the deleted files
498
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} reset --hard >/dev/null 2>/dev/null");
499

    
500
// Remove obsolete files
501
$files_to_remove = file("/etc/pfSense.obsoletedfiles");
502
foreach ($files_to_remove as $file_to_remove) {
503
	if (file_exists($file_to_remove)) {
504
		exec("/bin/rm -f $file_to_remove");
505
	}
506
}
507

    
508
if (!$upgrading) {
509
	post_cvssync_commands();
510
}
511

    
512
echo "===> Checkout complete.\n";
513
echo "\n";
514
if (!$upgrading) {
515
	echo "The system is now sync'd and PHP and nginx will be restarted in 5 seconds.\n\n";
516
} else {
517
	echo "The system is now sync'd.\n\n";
518
}
(13-13/24)