-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.php
785 lines (721 loc) · 30.3 KB
/
update.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
<?php
// error_reporting(E_ALL);
require_once('classes/updateserverV2.class.php');
require_once 'scripting.class.php';
@include('config/scripting.class.php');
if (class_exists("CustomUpdateSnippet", false)) {
$scriptSnippet = new CustomUpdateSnippet();
} else {
$scriptSnippet = new UpdateSnippet();
}
$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";
$isHTTPS = false;
$isHTTPSport = null;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$url = str_replace("http://", "https://", $url);
$isHTTPS = true;
$isHTTPSport = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 443;
}
// get config
$baseurl = dirname($url);
$pi = new UpdateServerV2($baseurl);
function notify($msg, $die = false) {
global $pi;
print "# $msg\r\n";
if (isset($pi))
$pi->logDeviceState("msg", $msg, "msgs", "");
if ($die) {
$pi->cleanupDeviceStates();
exit;
}
return($msg);
}
function doQueries($pi, $classes, $envs) {
if (($queries = $pi->doQueries($classes, $envs)) !== null) {
foreach ($queries as $id => $q) {
print "# query '$id'\r\n";
print "$q\r\n";
}
return true;
} else {
print "# no queries defined for any of callers classes: " . implode("+", $classes) . "\r\n";
return false;
}
}
/*
* DEBUG
*/
function cb_ob($buffer, $phase) {
$i = -1;
if (isset($_REQUEST['sn'])) {
chdir(dirname($_SERVER['SCRIPT_FILENAME']));
$fn = "debug/debug-{$_REQUEST['sn']}-certs.txt";
$obfd = "\r\n";
$obfd .= "========\r\n";
$obfd .= "--" . implode(", ", $_REQUEST) . "\r\n";
$obfd .= "--\r\n";
$obfd .= $buffer;
$obfd .= "-- " . time() . "\r\n";
$i = file_put_contents($fn, $obfd, FILE_APPEND);
}
$cwd = getcwd();
return "\r\n# DEBUG $fn -- $i -- $cwd\r\n" . $buffer;
}
function dbgout($msg, $content) {
$dbg = str_replace("\r\n", "\n", $content);
print "# $msg >\r\n";
foreach (explode("\n", $dbg) as $dbgline) {
print "# $dbgline\r\n";
}
print "# > $msg \r\n\r\n";
}
$debugscript = false;
if (isset($_REQUEST['sn'])) {
$debugscript = LessSimpleXMLElement::getAttributeFromXML($pi->xmluserconfig, 'debugscript', "false") == "true";
if ($debugscript) {
ob_start("cb_ob");
}
}
/*
* END DEBUG
*/
if (isset($_REQUEST['show']))
$_GET['mode'] = 'show'; // upward compat
if (isset($_GET['mode'])) {
switch ($_GET['mode']) {
case 'show' :
case 'status';
case 'ui' :
die("for user interface functions, call admin/admin.php instead");
break;
case 'backup' :
if (!isset($_REQUEST['hwid']))
UpdateServerV2::bailout("need 'hwid' arg for mode=backup, use ?hwid=#h");
if ($stamp = $pi->saveBackup($_REQUEST['hwid'])) {
$pi->logDeviceState("backup", $stamp, 'device');
}
break;
case 'query' :
if (!isset($_REQUEST['sn']))
UpdateServerV2::bailout("need 'sn' arg for mode=query, use ?sn=#m");
if (!isset($_REQUEST['id']))
UpdateServerV2::bailout("need 'id' arg for mode=query, go fix update.php");
// get raw put data
if (($stream = fopen('php://input', "r")) !== FALSE) {
$content = (stream_get_contents($stream));
}
$pi->saveQuery($_REQUEST['sn'], $_REQUEST['id'], $content);
// DEBUG
dbgout("query {$_REQUEST['id']}", $content);
// DEBUG END
break;
case 'vardump' :
if (!isset($_REQUEST['sn']))
UpdateServerV2::bailout("need 'sn' arg for mode=vardump, use ?sn=#m");
if (!isset($_REQUEST['var']))
UpdateServerV2::bailout("need 'var' arg for mode=vardump, use ?var=varname");
if (!isset($_REQUEST['file']))
UpdateServerV2::bailout("need 'file' arg for mode=vardump, use ?file=filename");
if (!UpdateServerV2::isNameInSubfolder($_REQUEST['file']))
UpdateServerV2::bailout("?file: filename must not point to external directory");
if (in_array(strtolower(pathinfo($_REQUEST['file'], PATHINFO_EXTENSION)), array('php', 'sh', 'pl')))
UpdateServerV2::bailout("bad file name");
if (($stream = fopen('php://input', "r")) !== FALSE) {
$content = (stream_get_contents($stream));
} else
UpdateServerV2::bailout("cannot read PUT data for mode=vardump");
// DEBUG
dbgout("vardump (before proc) {$_REQUEST['var']}", $content);
// DEBUG END
if (($value = $pi->getVarDump($_REQUEST['var'], $content)) === false)
UpdateServerV2::bailout("failed to extract '{$_REQUEST['var']}' from PUT data for mode=vardump");
if (isset($_REQUEST['proc']) && method_exists($pi, $_REQUEST['proc'])) {
$member = $_REQUEST['proc'];
$value = UpdateServerV2::$member($value);
} else {
$member = "none";
}
print "# processed (with '$member') length: " . strlen($value) . "\r\n";
file_put_contents($_REQUEST['file'], $value);
if (isset($_REQUEST['postproc']) && method_exists($pi, $_REQUEST['postproc'])) {
$postproc = $_REQUEST['postproc'];
if (($msg = $pi->$postproc($value, $_REQUEST['file'])) === null) {
print "# sucessfully post-processed (with '$postproc')\r\n";
} else {
print "# failed to post-process (with '$postproc'): $msg\r\n";
}
} else {
$postproc = "none";
}
$pi->logDeviceState("var-" . UpdateServerV2::str2dnsname($_REQUEST['var']), time(), "device");
notify("uploaded {$_REQUEST['file']} with proc=$member/postproc=$postproc $msg");
break;
case 'upload' :
if (!isset($_REQUEST['sn']))
UpdateServerV2::bailout("need 'sn' arg for mode=upload, use ?sn=#m");
if (!isset($_REQUEST['file']))
UpdateServerV2::bailout("need 'file' arg for mode=upload, use ?file=filename");
if (!UpdateServerV2::isNameInSubfolder($_REQUEST['file']))
UpdateServerV2::bailout("?file: filename must not point to external directory");
if (empty($_FILES)) {
die("No File uploaded - use back button to continue");
}
if (in_array(strtolower(pathinfo($_REQUEST['file'], PATHINFO_EXTENSION)), array('php', 'sh', 'pl')))
UpdateServerV2::bailout("bad file name");
foreach ($_FILES as $id => $f) {
if (strtolower($id) == strtolower("cert-{$_REQUEST['sn']}")) {
if ($f['error'] == 0) {
if (!move_uploaded_file($f['tmp_name'], $_REQUEST['file'])) {
UpdateServerV2::bailout("could not upload '{$f['name']}'");
}
if (isset($_REQUEST['proceed'])) {
header("Location: {$_REQUEST['proceed']}", true, 303);
exit;
}
UpdateServerV2::bailout("file upload - ?proceed= missing");
} else {
UpdateServerV2::bailout("upload error {$f['error']} - use back button to continue");
}
}
}
UpdateServerV2::bailout("No File uploaded (2) - use back button to continue");
break;
default :
UpdateServerV2::bailout("unknown cmd={$_GET['mode']}");
}
$pi->cleanupDeviceStates();
exit;
}
notify("");
function rewriteUrl($usehttps = false, $usehttpsport = 443) {
global $pi;
global $missingArgs;
global $url;
global $phase;
global $polling;
global $nextphase;
global $isHTTPS;
$newurl = $url;
print "\r\n";
// rewrite poll url with state query args
if (($newargs = $pi->getChangedStateArgs()) !== false || count($missingArgs) || $usehttps) {
if (isset($newargs['polling']) && $polling != $newargs['polling']) {
// polling has changed
if ($newargs['polling'] == 0) {
// turn it off
notify("turn off fast polling");
print "mod cmd UP1 provision 0\r\n";
print "config rem UP1 /provision\r\n";
print "config add UP1 /poll " . $pi->getInterval() . "\r\n";
} else {
// turn it on
notify("turn on fast polling ({$newargs['polling']})");
print "mod cmd UP1 provision " . $pi->getPolling() . "\r\n";
echo "config add UP1 /poll 1\r\n";
}
}
// do not replicate update clients std query args
{
$args = array();
// set new args
if (is_array($newargs))
foreach ($newargs as $key => $val) {
$args[$key] = "$val";
}
// add missing args
if (is_array($missingArgs))
foreach ($missingArgs as $key => $val) {
if (!isset($args[$key]))
$args[$key] = "$val";
}
// inherit old args (if not set new)
foreach ($_REQUEST as $key => $val) {
if (!isset($args[$key]))
$args[$key] = "$val";
}
// map meta arguments (such as e.g. "#m")
$finalargs = array();
foreach ($args as $key => &$val) {
if (($newval = $pi->mapStdArg($key, $val)) !== null) {
$finalargs[] = "$key=$newval";
}
}
}
$newurl .= "?" . implode("&", $finalargs);
// https?
$httpsport = LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->times, "httpsport", "");
if ($usehttps && (!$isHTTPS || $usehttpsport != $httpsport)) {
notify("using HTTP and 'forcehttps' is set or wrong port ($usehttpsport) -> need to switch to HTTPS on port $httpsport");
if (preg_match('@https?(://[^:/]+)(:[\d]+)?(.*)@i', $newurl, $matches)) {
$newurl = "https" . $matches[1] . ($httpsport == "" ? "" : ":$httpsport") . $matches[3];
} else {
}
if (($httpsurlmod = LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->times, "httpsurlmod", null)) != "") {
// urlmod is something like a sed substitute expression, eg. s/mtls// without the s (that is, /mtls//)
$umparts = explode($umsep = $httpsurlmod[0], $httpsurlmod);
$pattern = "$umsep{$umparts[1]}$umsep{$umparts[3]}";
$replace = $umparts[2];
$newurl = preg_replace($pattern, $replace, $newurl);
// notify("umparts: pattern: $pattern, replace: $replace, newurl: " . $newurl);
}
}
print "\r\n";
#if ($newargs !== false && count($newargs)) notify("changed state query args: " . implode(", ", array_keys($newargs)));
if (is_array($missingArgs) && count($missingArgs)) notify("missing query args: " . implode(", ", array_keys($missingArgs)));
echo "config add UP1 /url " . rawurlencode($newurl) . "\r\n";
echo "config add UP1 /no-dhcp\r\n";
echo "config write\r\n";
echo "config activate\r\n";
$pi->logDeviceState("nextphase", $nextphase);
$pi->logDeviceState("phase", $phase);
return true;
} else {
return false;
}
}
// determine type
$requiredArgs = array(
"type",
"sn",
"hwid",
"ip"
);
// see if we miss required args, no use in continueing without this information
$missingArgs = array();
foreach ($requiredArgs as $key) {
if (!isset($_REQUEST[$key])) {
// $pi->setStateArg($key, "");
$missingArgs[$key] = null;
}
}
if (count($missingArgs) > 0) {
if (!isset($_REQUEST['phase']))
$pi->setStateArg("phase", $pi->firstPhase());
if (!isset($_REQUEST['polling']))
$pi->setStateArg("polling", $pi->getPolling());
rewriteUrl();
exit;
}
if (isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
// determine classes
$classes = $pi->getClasses($type);
$pi->logDeviceState("type", $type, "device");
$pi->logDeviceState("classes", implode(", ", $classes), "device");
} else {
$type = "generic";
$classes = array();
}
// determine IP address
$pi->logDeviceState("ip", UpdateServerV2::getRemoteIp($rp, $via), "device");
$pi->logDeviceState("rp", $rp ? "true" : "false", "device");
if ($rp) {
$pi->logDeviceState("proxy", $via, "device");
}
// determine phases
if (!isset($_REQUEST['phase']) || empty($_REQUEST['phase'])) {
// use first phase
$phase = $pi->firstPhase();
} else {
$phase = $_REQUEST['phase'];
if (!$pi->checkPhase($phase))
notify("invalid phase: '{$_REQUEST['phase']}'", true);
}
$nextphase = $pi->nextPhase($phase);
$pi->logDeviceState("phase", $phase, "device");
// determine polling
$polling = isset($_REQUEST['polling']) ? $_REQUEST['polling'] : null;
// determine environment
if (!isset($_REQUEST['env'])) {
$rawenvs = array($pi->firstEnvironment());
} else {
$rawenvs = explode(",", $_REQUEST['env']);
}
// compute implications
$envs = array();
foreach ($rawenvs as $env) {
if (!$pi->checkEnvironment($env))
notify("invalid environment: '$env' ({$_REQUEST['env']})", true);
$envs += $pi->expandEnvironment($env);
}
$pi->logDeviceState("environments", implode(", ", $envs), "device");
notify("phase: $phase, nextphase: $nextphase, environment: " . implode('+', $envs) . ", type: $type, classes: " . implode('+', $classes) . "");
if ($pi->doSkipNext()) {
print "# need up-to-date query state, skipping update script, doing queries only\r\n";
doQueries($pi, $classes, $envs);
// make sure we are in fast polling mode
$pi->setStateArg("polling", $pi->getPolling());
$pi->cleanupDeviceStates();
exit;
}
// determine valid files
print "\r\n";
print "# existing files (from " . $pi->scriptdir . "):\r\n";
$pfiles = $pi->getPossibleScripts($newestfiletime, $newestfile, isset($_REQUEST['sn']) ? $_REQUEST['sn'] : null, $classes, $phase, $envs);
$files = array();
$now = time();
foreach ($pfiles as $fn => $mtime) {
if (is_numeric($mtime)) {
print "# > $fn: ";
print UpdateServerV2::_since($mtime);
$files[] = $fn;
print "\r\n";
}
}
print "\r\n";
print "# possible further files (from " . $pi->scriptdir . "):\r\n";
foreach ($pfiles as $fn => $mtime) {
if (!is_numeric($mtime)) {
print "# $fn ";
// print $mtime;
print "\r\n";
}
}
print "\r\n";
$age = $now - $newestfiletime;
$grace = ($pi->getGrace());
// shall we do backups?
// must do this before times and check cmd
if (($scfg = $pi->doBackups()) !== null) {
if (LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->times, "forcehttps", "false") == "true" && !$isHTTPS) {
notify("backups enabled but forcehttps is true and not using HTTPS");
} else {
print "\r\n";
print "$scfg\r\n";
}
} else {
print "\r\n";
notify("Backups not enabled in config");
}
// see if we want to defer script execution cause someone is working on it
if ($newestfiletime) {
print "\r\n# newest script ($newestfile) {$age}s old\r\n";
if ($age < $grace) {
notify("files being updated ($newestfile {$age}s old, waiting for at least {$grace}s to expire)", true);
}
}
// do we need to do certificate renewal?
print "\r\n";
$certcmds = $pi->doCertificates($type, $certmsgs, $certificateIsOK);
if ($certmsgs !== null && count($certmsgs)) {
$ak = array_keys($certmsgs);
$pi->logDeviceState("certstat", $certmsgs[array_pop($ak)], "device");
}
// shall we gather more device data?
doQueries($pi, $classes, $envs);
// see if we have restricted times
$times = $pi->getTimes($nextphase != null);
if ($times != null) {
print "\r\n# Restricted times\r\n$times\r\n";
}
print "\r\n";
$reset = false;
// see if we need to update boot code or firmware
if (isset($pi->xmlconfig->master) && isset($pi->xmlconfig->master['info']) && $pi->xmlconfig->master['info'] != "") {
// see if we need to query the master device
$info = null;
if ($pi->xmlconfig->master['info'] != "none") {
// query pbx fw info
if ($pi->cacheIsCurrent()) {
print "# firmware build info cache is current\r\n";
$info = $pi->getCachedPbxInfo();
} else {
$info = new SimpleXMLElement("<result><error>cache not current</error></result>");
}
if (!isset($info->prot)) {
print "# failed to use cached data ({$info->error}), retrieving info online\r\n";
$info = $pi->getOnlinePbxInfo();
if (!isset($info->prot)) {
print("# cannot get PBX info: {$info->error}, reading cache\r\n");
$info = $pi->getCachedPbxInfo();
if (!isset($info->prot)) {
UpdateServerV2::bailout("cannot get cached PBX info: {$info->error}");
}
}
}
}
// determine firmware and bootcode version
if (empty($pi->xmlconfig->master['firmware'])) {
$pi->xmlconfig->master['firmware'] = "master";
}
if (empty($pi->xmlconfig->master['bootcode'])) {
$pi->xmlconfig->master['bootcode'] = "master";
}
$useFirmware = "unknown";
$useBootcode = "unknown";
if ($pi->xmlconfig->master['firmware'] == "master") {
if ($info == null)
UpdateServerV2::bailout("Cannot use firmware='master' with no info available");
$useFirmware = (string) $info->prot;
print "# firmware derived from master device\r\n";
} else if ($pi->xmlconfig->master['firmware'] == "none") {
print "# firmware update disabled\r\n";
$useFirmware = null;
} else if (is_numeric((string) $pi->xmlconfig->master['firmware'])) {
$useFirmware = (string) $pi->xmlconfig->master['firmware'];
print "# firmware fixed to $useFirmware\r\n";
} else {
UpdateServerV2::bailout("Invalid value '{$pi->xmlconfig->master['firmware']}' for firmware attribute in <master> tag");
}
if ($pi->xmlconfig->master['bootcode'] == "master") {
if ($info == null)
UpdateServerV2::bailout("Cannot use bootcode='master' with no info available");
$useBootcode = (string) $info->boot;
print "# bootcode derived from master device\r\n";
} else if ($pi->xmlconfig->master['bootcode'] == "firmware") {
print "# bootcode derived from firmware\r\n";
$useBootcode = $useFirmware;
} else if ($pi->xmlconfig->master['bootcode'] == "none") {
print "# bootcode update disabled\r\n";
$useBootcode = null;
} else if (is_numeric((string) $pi->xmlconfig->master['bootcode'])) {
$useBootcode = (string) $pi->xmlconfig->master['bootcode'];
print "# bootcode fixed to $useBootcode\r\n";
} else {
UpdateServerV2::bailout("Invalid value '{$pi->xmlconfig->master['bootcode']}' for 'bootcode' attribute in <master> tag");
} {
$nofirms = $noboots = array();
if (isset($pi->xmlconfig->nobootdev->model)) {
foreach ($pi->xmlconfig->nobootdev->model as $dev) {
$noboots[] = strtolower((string) $dev);
}
}
if (isset($pi->xmlconfig->nofirmdev->model)) {
foreach ($pi->xmlconfig->nofirmdev->model as $dev) {
$nofirms[] = strtolower((string) $dev);
}
}
print "# nofirm: " . implode(", ", $nofirms) . ". This device type=$type\r\n";
print "# noboot: " . implode(", ", $noboots) . "\r\n";
// applies tag that does not match?
$excludereason = array();
if (isset($pi->xmlconfig->master->applies)) {
foreach ($pi->xmlconfig->master->applies as $a) {
if (!(
(trim((string) $a) == "*") ||
in_array(
trim((string) $a), (isset($a['env']) ? $envs : $classes)
))
) {
$excludereason[] = trim((string) $a) . (isset($a['env']) ? " (env)" : " (class)");
}
}
}
if (count($excludereason)) {
print "# no firmware/bootcode update as device does not fit <applies>: " . implode(", ", $excludereason) . "\r\n";
} else {
if (($useFirmware !== null) && !in_array(strtolower($type), $nofirms)) {
if (!isset($_REQUEST['PROT']) || ($_REQUEST['PROT'] != (string) $useFirmware)) {
notify("current firmware (" . (isset($_REQUEST['PROT']) ? $_REQUEST['PROT'] : "unknown") . ") does not match required firmware ({$useFirmware})");
print "mod cmd UP0 prot " . $pi->getFWStorage((string) $useFirmware, $type, "prot") . " ser {$useFirmware}\r\n";
$pi->logDeviceState("requested", $useFirmware, "firmware");
$pi->logDeviceState("requested-at", time(), "firmware");
$reset = true;
} else {
print "# firmware {$useFirmware} good\r\n";
}
} else {
print "# no firmware update for device of type '$type'\r\n";
}
if (($useBootcode !== null) && !in_array(strtolower($type), $noboots)) {
if (!isset($_REQUEST['BOOT']) || ($_REQUEST['BOOT'] != (string) $useBootcode)) {
notify("current boot code (" . (isset($_REQUEST['BOOT']) ? $_REQUEST['BOOT'] : "unknown") . ") does not match required boot code ({$useBootcode})");
print "mod cmd UP0 boot " . $pi->getFWStorage((string) $useBootcode, $type, "boot") . " ser {$useBootcode}\r\n";
$pi->logDeviceState("requested", $useBootcode . "bootcode");
$pi->logDeviceState("requested-at", time(), "bootcode");
$reset = true;
} else {
print "# boot code {$useBootcode} good\r\n";
}
} else {
print "# no bootcode update for device of type '$type'\r\n";
}
}
}
}
if (isset($_REQUEST['PROT'])) {
$pi->logDeviceState("build", $_REQUEST['PROT'], "firmware");
}
if (isset($_REQUEST['BOOT'])) {
$pi->logDeviceState("build", $_REQUEST['BOOT'], "bootcode");
}
if (isset($_REQUEST['hwid'])) {
$pi->logDeviceState("hwid", $_REQUEST['hwid'], "device");
}
if (isset($_REQUEST['ip'])) {
$pi->logDeviceState("realip", $_REQUEST['ip'], "device");
}
if ($reset) {
print "# make sure remaining update scripts are executed with up-to-date firmware and update URL\r\n";
print "iresetn\r\n";
}
// shall we deploy certificates?
if ($certmsgs !== null) {
foreach ($certmsgs as $msg) {
notify("certificates: $msg ");
}
}
if ($certcmds !== null) {
foreach ($certcmds as $cmt => $c) {
notify("certificates: $cmt");
print "$c\r\n";
}
$pi->setStateArg("polling", $pi->getPolling());
if (!rewriteUrl()) {
echo "config write\r\n";
echo "config activate\r\n";
}
print "iresetn\r\n";
notify("certificate cmds need to process - no further cmds", true);
exit;
}
/*
* this is where we actually deliver update scripts
*/
print "# no certificate cmds required - processing normal updates\r\n";
// do we need to enforce HTTPS?
if (LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->times, "forcehttps", "false") == "true") {
$needhttpsport = LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->times, "httpsport", 443);
if (!$isHTTPS || $needhttpsport != $isHTTPSport) {
$pi->setStateArg("polling", $pi->getPolling());
rewriteUrl(true, $isHTTPSport);
notify("forcehttps - currently " . ($isHTTPS ? "" : "NOT ") . "using HTTPS on port $isHTTPSport, new polling: " . $pi->getPolling(), true);
// this notify never comes back
}
// CERT fiddling
$debugcerts = LessSimpleXMLElement::getAttributeFromXML($pi->xmluserconfig, 'debugcerts', "false") == "true";
if ($debugcerts) {
$fd = fopen("debug/Request-Certs.txt", "a");
foreach (
array(
"HTTPS", "SSL_CLIENT_S_DN", "SSL_CLIENT_S_DN_CN", "SSL_CLIENT_I_DN", "SSL_CLIENT_VERIFY", "SSL_SERVER_S_DN"
)
as $var) {
fwrite($fd, "# $var: '" . (empty($_SERVER[$var]) ? "<not-set>" : $_SERVER[$var]) . "'\n");
}
fwrite($fd, "-----\n");
fclose($fd);
}
if (LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->times, "forcetrust", "false") == "true") {
// see if we are using ligHTTPd and do some glitches
if (!isset($pi->xmlconfig->customcerts['CAname'])) {
UpdateServerV2::bailout("certificates: customcerts/@CAname must be defined for certificate trust enforcement");
}
$_sep = isset($pi->xmlconfig->customcerts['CAnamesep']) ? (string) $pi->xmlconfig->customcerts['CAnamesep'] : ",";
$goodCA = explode($_sep, (string) $pi->xmlconfig->customcerts['CAname']);
if (isset($_SERVER['SERVER_SOFTWARE']) && stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd/') !== false) {
// this is ligHTTPd
$isligHTTPd = true;
$_SERVER['SSL_CLIENT_S_DN'] = "/C={$_SERVER['SSL_CLIENT_S_DN_C']}/O={$_SERVER['SSL_CLIENT_S_DN_O']}/CN={$_SERVER['SSL_CLIENT_S_DN_CN']}";
$_SERVER['SSL_CLIENT_VERIFY'] = 'SUCCESS'; // make sure this is asserted in lighttpd.conf (using ssl.verifyclient.enforce);
$_SERVER['SSL_CLIENT_I_DN'] = $goodCA[count($goodCA) - 1];
} else {
$isligHTTPd = false;
}
if (!isset($_SERVER['SSL_CLIENT_S_DN_CN'])) {
notify("cannot verify CN with HTTPS: SSL_CLIENT_S_DN_CN not present - fix web server configuration or use MTLS-enabled port!", true);
} else {
$shownCN = $_SERVER['SSL_CLIENT_S_DN_CN'];
$requiredCN = $_REQUEST['hwid'];
$requiredAlternativeCN = str_replace("-", "", $_REQUEST['sn']);
$wildcardCN = LessSimpleXMLElement::getAttributeFromXML($pi->xmlconfig->customcerts, "CAwildcard", null);
// some early certificates where broken, fix here:
$brokenCN = array(
"IP222s" => "IP222",
"IP232s" => "IP232",
"IP240a" => "IP240",
"IP200a" => "IP200",
);
$cnparts = explode("-", $shownCN);
foreach ($brokenCN as $broken => $fix) {
if ($cnparts[0] == $broken) {
$cnparts[0] = $fix;
$shownCN = implode("-", $cnparts);
break;
}
}
if ($shownCN != $requiredCN && $shownCN != $requiredAlternativeCN &&
(($wildcardCN === null) || ($wildcardCN != $shownCN))) {
notify("Device claims to be '$requiredCN / $requiredAlternativeCN' but identifies as '$shownCN' by TLS", true);
}
if (empty($_SERVER['SSL_CLIENT_VERIFY']) || $_SERVER['SSL_CLIENT_VERIFY'] != 'SUCCESS') {
notify("TLS certificate ($shownCN) not trusted -- " . ( isset($_SERVER['SSL_CLIENT_VERIFY']) ? $_SERVER['SSL_CLIENT_VERIFY'] : "<undefined>"), true);
}
if (empty($_SERVER['SSL_CLIENT_I_DN']) || !in_array($_SERVER['SSL_CLIENT_I_DN'], $goodCA)) {
notify(
"TLS certificate issuer ({$_SERVER['SSL_CLIENT_I_DN']}) not trusted for TLS certificate ($shownCN) -- " .
( isset($_SERVER['SSL_CLIENT_VERIFY']) ?
$_SERVER['SSL_CLIENT_VERIFY'] :
"<undefined>"), true);
}
notify("good certificate(CN='$shownCN'" . ($isligHTTPd ? "" : ", ISSUER='{$_SERVER['SSL_CLIENT_I_DN']}'") . ")");
}
}
}
print "\r\n";
// see if we need to warp over to next phase
if ($nextphase !== null) {
$pi->setStateArg("phase", $nextphase);
$pi->setStateArg("polling", $pi->getPolling());
} else {
$pi->setStateArg("polling", 0);
}
// provide all info to custom snippet class
$scriptSnippet->statexml = $pi->statexml;
// $scriptSnippet->dump();
// guard against unchanged config files (only for the final phase, all others are repeated upon request)
$deliverSnippets = true;
$docheck = false;
$sendStandardSnippets = $scriptSnippet->sendStandardSnippets();
$custom1 = $scriptSnippet->getPreSnippet();
$custom2 = $scriptSnippet->getPostSnippet();
if (($nextphase === null) && ($sig = $pi->getFilesSignature($sendStandardSnippets ? $files : array(), $custom1, $custom2)) !== null) {
$docheck = true;
if (isset($_REQUEST['CHECK']) && $_REQUEST['CHECK'] == $sig) {
$deliverSnippets = false;
}
}
if ($deliverSnippets) {
// need to deliver snippets
foreach ($custom1 as $line) {
print "$line\r\n";
}
if ($sendStandardSnippets) {
foreach ($files as $file) {
notify(" $file");
print "# { \r\n# begin script '$file' \r\n";
$script = @file_get_contents("./$file");
if ($script === false)
notify("cannot read script '$file' in " . getcwd() . "");
else {
print "$script\r\n";
$pi->logDeviceState("delivered", time(), "config", array("filename", "$file"));
$pi->logDeviceState("version", filemtime($file), "config", array("filename", "$file"));
}
print "# end script '$file'\r\n# }\r\n";
}
} else {
print "# standard snippets suppressed by custom snippet\r\n";
}
foreach ($custom2 as $line) {
print "$line\r\n";
}
print "\r\n# end of all scripts \r\n";
if (!rewriteUrl()) {
print "config write\r\n";
print "config activate\r\n";
}
if ($docheck) {
// we do this just to set the CHECK var, we do not send snippets on our own if the CHECK serial ist good already (see a few lines below)
print "# set CHECK var\r\n";
print "mod cmd UP1 check ser $sig\r\n";
}
print "# trigger reset if required\r\n";
print "iresetn\r\n";
} else {
print "# not delivering any snippets - CHECK serial $sig is good\r\n";
rewriteUrl();
}
// better no extra newlines at end of script
// print "\r\n";
$pi->cleanupDeviceStates();