-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsyslog-forwarder.php
More file actions
1203 lines (1021 loc) · 34.3 KB
/
syslog-forwarder.php
File metadata and controls
1203 lines (1021 loc) · 34.3 KB
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env php
<?php
declare(strict_types=1);
setupErrorHandler();
loadEnvVariables();
setupTimezone(env('SYSLOG_TIMEZONE'));
/************************************************************************
* CONFIGURATION OPTIONS *
************************************************************************/
/**
* Optional - Syslog server endpoint URL
*
* URL must include:
* - Protocol (udp/tcp)
* - Host (IP or hostname)
* - Port (default: 514)
*
* Format: protocol://host:port
* Example: udp://127.0.0.1:514
*
* If not provided, will be prompted during script execution.
*/
define('SYSLOG_SERVER', env('SYSLOG_SERVER'));
/**
* Optional - Message identifier prefix for syslog entries.
*
* This string will be prepended to each message sent to the syslog server.
* Useful for filtering logs using syslog rules (e.g. $msg contains 'FRITZ!Box')
*
* Format: string
* Example: 'FRITZ!Box'
*/
define('SYSLOG_MESSAGE_IDENTIFIER', env('SYSLOG_MESSAGE_IDENTIFIER'));
/**
* Optional - FRITZ!Box URL endpoint
*
* The HTTP URL where your FRITZ!Box web interface is accessible.
* Do not include a trailing slash.
*
* Format: http://host
* Example: http://192.168.1.1
*
* If not provided, will be prompted during script execution.
*/
define('FRITZBOX_ENDPOINT', env('FRITZBOX_ENDPOINT'));
/**
* Optional - FRITZ!Box administrator username
*
* The username used to authenticate with the FRITZ!Box web interface.
*
* Format: string
* Example: 'fritz1234'
*
* If not provided, will be prompted during script execution.
*/
define('FRITZBOX_USERNAME', env('FRITZBOX_USERNAME'));
/**
* Optional - FRITZ!Box administrator password
*
* The password used to authenticate with the FRITZ!Box web interface.
* For security reasons, consider leaving this empty to be prompted at runtime.
*
* Format: string
* Example: 'abcdef012345'
*
* If not provided, will be prompted securely during script execution.
*/
define('FRITZBOX_PASSWORD', env('FRITZBOX_PASSWORD'));
/**
* Required - Refresh interval in seconds
*
* The script will poll the FRITZ!Box for new log entries at this interval.
* Lower values mean more frequent checks but higher system load.
*
* Format: integer
* Example: 5 (checks every 5 seconds)
* Recommended range: 1-60 seconds
*/
define('REFRESH_INTERVAL_SECONDS', (int)env('REFRESH_INTERVAL_SECONDS', '5'));
/**
* Required - Maximum number of retry attempts
*
* The number of times the script will retry an operation before giving up.
* Applies to authentication, log fetching, and syslog sending operations.
*
* Format: integer
* Example: 3 (will try 4 times total - initial attempt plus 3 retries)
* Minimum value: 0
*/
define('MAX_RETRIES_ALLOWED', (int)env('MAX_RETRIES_ALLOWED', '3'));
/************************************************************************
* PROGRAM START *
************************************************************************/
// Collect input data
$syslogServerEndpoint = getConfigOrPromptValue('Syslog Server (ex: udp://127.0.0.1:514): ', SYSLOG_SERVER);
$fritzBoxEndpoint = getConfigOrPromptValue('FRITZ!Box URL (ex: http://192.168.1.1): ', FRITZBOX_ENDPOINT);
$fritzBoxUsername = getConfigOrPromptValue('FRITZ!Box Username: ', FRITZBOX_USERNAME);
$fritzBoxPassword = getConfigOrPromptSecure('FRITZ!Box Password: ', FRITZBOX_PASSWORD);
// State variables
$fritzBoxSessionId = null;
$lastLogsTimestamp = time();
$lastRefreshTime = 0;
/************************************************************************
* MAIN LOOP *
************************************************************************/
while (true) {
if (time() - $lastRefreshTime < REFRESH_INTERVAL_SECONDS) {
usleep(500000);
continue;
}
$lastRefreshTime = time();
// Authentication routine
if (!isset($fritzBoxSessionId)) {
try {
$fritzBoxSessionId = authenticateWithFritzBox(
endpoint: $fritzBoxEndpoint,
username: $fritzBoxUsername,
password: $fritzBoxPassword
);
} catch (Throwable $e) {
stdErr($e->getMessage());
break;
}
}
// Fetch the updated event logs
try {
$eventLogs = fetchEventLogs(
endpoint: $fritzBoxEndpoint,
sessionId: $fritzBoxSessionId
);
// keep only newer entries
$eventLogs = array_filter(
$eventLogs,
fn ($entry) => $entry['timestamp'] > $lastLogsTimestamp
);
} catch (Throwable $e) {
stdErr($e->getMessage());
if ($e->getCode() === 400) {
// session invalid/expired -> needs to retry authentication step
$fritzBoxSessionId = null;
continue;
}
// exit
break;
}
// attempt to push to syslog server
if (count($eventLogs) !== 0) {
try {
$lastLogsTimestamp = syncLogsToSyslog(
serverEndpoint: $syslogServerEndpoint,
eventLogs: $eventLogs
);
} catch (Throwable $e) {
stdErr($e->getMessage());
break;
}
}
}
// unexpected exit
exit(1);
/************************************************************************
* MAIN ACTIONS *
************************************************************************/
/**
* Authenticates with FRITZ!Box and returns a session ID
*
* Makes repeated attempts to authenticate with the FRITZ!Box interface
* using the provided credentials. If authentication fails, it will retry
* up to MAX_RETRIES_ALLOWED times with increasing delays between attempts.
*
* @param string $endpoint The FRITZ!Box URL (e.g., http://192.168.1.1)
* @param string $username The administrator username
* @param string $password The administrator password
*
* @throws Exception With code 400 when invalid credentials are provided
* @throws Exception When authentication fails after maximum retries
* @return string The session ID for authenticated requests
*/
function authenticateWithFritzBox(
string $endpoint,
string $username,
#[SensitiveParameter]
string $password
): string {
try {
return retryableAction(function () use ($endpoint, $username, $password) {
try {
stdOut(message: 'Attempt to login to FRITZ!Box...', eol: '');
$sessionId = makeLoginRequest(
$endpoint,
$username,
$password
);
stdOut(message: ' Success!', prefix: '');
return $sessionId;
} catch (Throwable $e) {
stdOut(message: ' Fail!', prefix: '');
// invalid credentials
if ($e->getCode() === 400) {
throw new NonRetryableException($e->getMessage(), $e->getCode(), $e);
}
throw $e;
}
});
} catch (RuntimeException $e) {
throw new Exception(
message: 'Too many login attempt have failed',
previous: $e
);
}
}
/**
* Retrieves event logs from FRITZ!Box with retry mechanism
*
* Makes repeated attempts to fetch event logs from the FRITZ!Box interface.
* If the request fails, it will retry up to MAX_RETRIES_ALLOWED times
* with increasing delays between attempts.
*
* @param string $endpoint The FRITZ!Box URL (e.g., http://192.168.1.1)
* @param string $sessionId Valid session ID from successful authentication
*
* @throws Exception When fetching fails after maximum retries
* @throws Exception With code 400 when session is invalid/expired
* @return array{
* timestamp: int,
* date: string,
* time: string,
* id: int,
* group: string,
* msg: string,
* nohelp: bool
* } List of event log entries sorted by timestamp
*/
function fetchEventLogs(
string $endpoint,
#[SensitiveParameter]
string $sessionId
): array {
try {
return retryableAction(function () use ($endpoint, $sessionId) {
try {
return makeEventLogsRequest(
$endpoint,
$sessionId
);
} catch (Throwable $e) {
// invalid credentials
if ($e->getCode() === 400) {
throw new NonRetryableException($e->getMessage(), $e->getCode(), $e);
}
throw $e;
}
});
} catch (RuntimeException $e) {
throw new Exception(
message: 'Too many unexpected failures while fetching eventlogs',
previous: $e
);
}
}
/**
* Synchronizes FRITZ!Box event logs to a syslog server with retry mechanism
*
* Makes repeated attempts to send event logs to the syslog server.
* If sending fails, it will retry up to MAX_RETRIES_ALLOWED times
* with increasing delays between attempts.
*
* @param string $serverEndpoint The syslog server URL (e.g., udp://127.0.0.1:514)
* @param array<int, array{
* timestamp: int,
* date: string,
* time: string,
* id: int,
* group: string,
* msg: string,
* nohelp: bool
* }> $eventLogs Array of log entries to send to syslog server
*
* @throws Exception When sending fails after maximum retries
* @return int Timestamp of the last successfully sent log entry
*/
function syncLogsToSyslog(
string $serverEndpoint,
array $eventLogs
): int {
try {
return retryableAction(function () use ($serverEndpoint, $eventLogs) {
sendLogsToSyslog($serverEndpoint, $eventLogs);
return end($eventLogs)['timestamp'];
});
} catch (RuntimeException $e) {
throw new Exception(
message: 'Too many unexpected failures while sending logs to syslog server',
previous: $e
);
}
}
/**
* Executes an action with automatic retry functionality
*
* Attempts to execute the provided callback function and automatically retries
* on failure up to MAX_RETRIES_ALLOWED times with exponential backoff.
*
* @param Closure $callback The function to execute. If a NonRetryableException is thrown, the retry is skipped
* @param int $backoffBaseSeconds Base time in seconds for calculating exponential backoff (default: 5)
*
* @throws RuntimeException When the maximum retry attempts are exceeded
* @return mixed The return value of the callback function
*/
function retryableAction(Closure $callback, int $backoffBaseSeconds = 5): mixed
{
$retriesCounter = 0;
while (true) {
try {
return $callback();
} catch (Throwable $e) {
if ($e instanceof NonRetryableException) {
throw $e->getPrevious();
}
stdErr($e->getMessage());
if (++$retriesCounter > MAX_RETRIES_ALLOWED) {
throw new RuntimeException('Failed too many times.');
}
$secondsToWait = $retriesCounter * $backoffBaseSeconds;
stdOut(sprintf('Waiting for %d seconds before retry.', $secondsToWait));
sleep($secondsToWait);
continue;
}
}
}
/************************************************************************
* Input/Output *
************************************************************************/
/**
* Exceptions of this type skips the retry mechanism if thrown
* inside of a callback function passed to retryableAction
*/
class NonRetryableException extends Exception
{
}
/**
* Gets the value of an environment variable.
*
* @param string $name The name of the environment variable to retrieve
* @param string $default The default value to return if the environment variable is not set
* @return string The value of the environment variable
*/
function env(string $name, string $default = ''): string
{
$env = getenv($name);
return is_string($env) ? $env : $default;
}
/**
* Outputs a message to standard output with timestamp
*
* Prepends a timestamp to the message and outputs it to stdout.
* The timestamp format is 'Y-m-d H:i:s.v' by default.
*
* @param string $message The message to output
* @param string $eol End of line character(s), defaults to PHP_EOL
* @param string|null $prefix Optional custom prefix, defaults to timestamp
* @return void
*/
function stdOut(
string $message,
string $eol = PHP_EOL,
?string $prefix = null
): void {
fwrite(STDOUT, outputFormat($message, $eol, $prefix));
}
/**
* Formats a message with timestamp prefix and returns it as string
*
* @param string $message The message to format
* @param string $eol End of line character(s), defaults to PHP_EOL
* @param string|null $prefix Optional custom prefix, defaults to timestamp
* @return string The formatted message string with prefix
*/
function outputFormat(
string $message,
string $eol = PHP_EOL,
?string $prefix = null
): string {
if ($prefix === null) {
$prefix = (new DateTime())->format('Y-m-d H:i:s.v');
}
return $prefix . ' ' . $message . $eol;
}
/**
* Outputs an error message to standard error
*
* Triggers an error with the specified level and message.
* The message is in the following format: '[LEVEL] message'
*
* @param string $message The error message to output
* @param int $level The error level (E_USER_NOTICE, E_USER_WARNING, E_USER_ERROR)
* @return void
* @see trigger_error()
*/
function stdErr(
string $message,
int $level = E_USER_WARNING
): void {
$errorLabel = match($level) {
E_USER_NOTICE => 'NOTICE',
E_USER_WARNING => 'WARNING',
E_USER_ERROR => 'ERROR',
default => 'UNKNOWN',
};
trigger_error(
message: sprintf(
'[%s] %s',
$errorLabel,
$message
),
error_level: $errorLabel === 'UNKNOWN'
? E_USER_WARNING
: $level
);
}
/**
* Sets up custom error handling for the application
*
* Configures a custom error handler that formats errors with timestamps
* and prevents duplicate error messages from the default PHP handler.
*
* @return void
* @see set_error_handler()
*/
function setupErrorHandler(): void
{
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool {
if (!(error_reporting() & $errno)) {
return false;
}
fwrite(STDERR, outputFormat($errstr));
return true;
});
}
/**
* Returns a configuration value or prompts for user input
*
* If a default value is provided, returns it. Otherwise prompts
* the user for input using the provided prompt message.
*
* @param string $prompt The prompt message to display
* @param string $default Optional default value from configuration
* @return string The configuration value or user input
*/
function getConfigOrPromptValue(
string $prompt,
string $default = ''
): string {
if ($default !== '') {
return $default;
}
return readline($prompt);
}
/**
* Returns a configuration value or prompts securely for user input
*
* If a default value is provided, returns it. Otherwise prompts
* the user for input using a secure prompt that hides the input.
*
* @param string $prompt The prompt message to display
* @param string $default Optional default value from configuration
* @return string The configuration value or secure user input
*/
function getConfigOrPromptSecure(
string $prompt,
#[SensitiveParameter]
string $default = ''
): string {
if ($default !== '') {
return $default;
}
return readlineSecure($prompt);
}
/**
* Prompts for password input without displaying characters in console
*
* Uses different methods based on the operating system:
* - Windows: Creates temporary VBScript to show password input dialog
* - Unix: Uses bash read command with -s flag for secure input
*
* @param string $prompt The message to display when asking for password
* @throws Exception When bash is not available on Unix systems
* @return string The password entered by user
* @see https://www.sitepoint.com/interactive-cli-password-prompt-in-php/
*/
function readlineSecure(string $prompt): string
{
// the following code works fine on W11 somehow
if (preg_match('/^win/i', PHP_OS)) {
$vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
file_put_contents(
$vbscript,
'wscript.echo(InputBox("'. addslashes($prompt) .'", "", "password here"))'
);
$command = "cscript //nologo " . escapeshellarg($vbscript);
$password = rtrim(shell_exec($command));
unlink($vbscript);
return $password;
}
$command = "/usr/bin/env bash -c 'echo OK'";
if (rtrim(shell_exec($command)) !== 'OK') {
throw new Exception('Can\'t invoke bash');
}
$command = "/usr/bin/env bash -c 'read -s -p \""
. addslashes($prompt)
. "\" mypassword && echo \$mypassword'";
$password = rtrim(shell_exec($command));
stdOut(message: '', eol: PHP_EOL, prefix: '');
return $password;
}
/**
* Loads environment variables from a .env file into the application environment
*
* Checks if environment variables are already defined before loading from file.
* If SYSLOG_SERVER is already set in the environment, this function returns early
* without loading the file.
*
* @param string $filename Path to the .env file, defaults to '.env'
* @return void
* @see parseEnvFile() For the function that parses the .env file
*/
function loadEnvVariables(string $filename = '.env'): void
{
if (getenv('SYSLOG_SERVER') !== false) {
return;
}
foreach (parseEnvFile($filename) as $key => $value) {
putenv("{$key}={$value}");
}
}
/**
* Parses a .env file and yields environment variables as key-value pairs
*
* @param string $path Path to the .env file to parse
* @return Generator<string, string> A generator yielding variable names as keys and their values
*/
function parseEnvFile(string $path): Generator
{
if (!is_readable($path)) {
return;
}
$fileHandler = fopen($path, 'rb');
if ($fileHandler === false) {
return;
}
try {
while ($line = fgets($fileHandler)) {
if (
empty($line)
|| str_starts_with($line, '#')
|| !str_contains($line, '=')
) {
continue;
}
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove quotes
if (preg_match('/^([\'"])((?:\\\\.|(?!\1).)*)\1$/', $value, $matches) === 1) {
$value = $matches[2];
}
yield $key => $value;
}
} finally {
fclose($fileHandler);
}
}
/**
* Configures the application timezone
*
* Sets the timezone for the application based on the provided value.
* If the timezone is invalid, falls back to the default PHP timezone.
*
* @param string $timezone The timezone to set, or empty string to use default
* @return string The timezone that was actually set
*/
function setupTimezone(string $timezone = ''): string
{
$defaultTimezone = date_default_timezone_get();
if ($timezone === '') {
stdOut(sprintf('Using default timezone: %s', $defaultTimezone));
return $defaultTimezone;
}
if (@date_default_timezone_set($timezone)) {
stdOut(sprintf('Timezone set to: %s', $timezone));
return $timezone;
} else {
stdErr(
sprintf(
'Invalid timezone value "%s". Falling back to default: %s',
$timezone,
$defaultTimezone
)
);
date_default_timezone_set($defaultTimezone);
return $defaultTimezone;
}
}
/************************************************************************
* TCP/UDP Requests *
************************************************************************/
/**
* Makes an authentication request to FRITZ!Box and returns a session ID
*
* The authentication process follows these steps:
* 1. Fetches challenge string from login page
* 2. Generates password hash using challenge
* 3. Posts credentials to obtain session ID
*
* @param string $endpoint The FRITZ!Box base URL (e.g., http://192.168.1.1)
* @param string $username The administrator username
* @param string $password The administrator password
*
* @throws Exception When challenge string cannot be found
* @throws Exception When authentication fails
* @throws Exception When HTTP request fails
* @throws Exception With code 400 when login fails
* @return string Valid session ID for authenticated requests
*/
function makeLoginRequest(
string $endpoint,
string $username,
#[SensitiveParameter]
string $password
): string {
// 1. Fetch challenge string from login page
$fritzLoginGetResponse = makeRequest(
url: $endpoint,
method: 'GET'
);
if ($fritzLoginGetResponse['status'] !== 200) {
throw new Exception(
message: sprintf(
'Request is failed! HTTP (Code: %s) GET %s',
(string) $fritzLoginGetResponse['status'],
$endpoint
),
code: (int) $fritzLoginGetResponse['status']
);
}
if (
preg_match('#"challenge":"([^"]+)"#i', $fritzLoginGetResponse['body'], $challengeRegexpMatch) === false
|| empty($challengeRegexpMatch[1])
) {
throw new Exception('Unable to find the "challenge" string');
}
// 2. Generate password hash using challenge
$passwordHash = generateLoginPasswordHash(
challenge: $challengeRegexpMatch[1],
password: $password
);
// 3. Posts credentials to obtain session ID
$formActionEndpoint = $endpoint .'/index.lua';
$fritzLoginPostResponse = makeRequest(
url: $formActionEndpoint,
method: 'POST',
headers: [
''
],
data: [
'response' => $passwordHash,
'lp' => '',
'loginView' => 'simple',
'username' => $username
]
);
if ($fritzLoginPostResponse['status'] !== 200) {
throw new Exception(
message: sprintf(
'Request is failed! HTTP (Code: %s) POST %s',
(string) $fritzLoginPostResponse['status'],
$formActionEndpoint
),
code: (int) $fritzLoginPostResponse['status']
);
}
if (
preg_match('#"sid":"([^"]+)"#i', $fritzLoginPostResponse['body'], $sessionIdRegexpMatch) === false
|| empty($sessionIdRegexpMatch[1])
) {
throw new Exception('Unable to find the "sid" string');
}
if (trim($sessionIdRegexpMatch[1], '0') === '') {
throw new Exception(
message: 'Login failed',
code: 400
);
}
return $sessionIdRegexpMatch[1];
}
/**
* Makes a request to the FRITZ!Box eventlog endpoint and returns available messages
*
* Fetches event logs using the FRITZ!Box API v0 and processes the response.
* Returned logs are sorted by ascending timestamp and include event details
* like date, time, message, and category.
*
* @param string $endpoint The FRITZ!Box base URL (e.g., http://192.168.1.1)
* @param string $sessionId Valid session ID from successful authentication
*
* @throws Exception When HTTP request fails (status != 200)
* @throws Exception With code 400 when session is invalid/expired
* @throws Exception When JSON response cannot be decoded
* @return array<int, array{
* timestamp: int,
* date: string,
* time: string,
* id: int,
* group: string,
* msg: string,
* nohelp: bool
* }> List of event log entries sorted by timestamp
*/
function makeEventLogsRequest(
string $endpoint,
string $sessionId
): array {
static $workingEndpoint = null;
$eventLogsEndpointList = [
$endpoint .'/api/v0/dino/eventlog',
$endpoint .'/api/v0/eventlog',
];
foreach ($eventLogsEndpointList as $eventLogsEndpoint) {
if ($workingEndpoint !== null && $workingEndpoint !== $eventLogsEndpoint) {
continue;
}
$response = makeRequest(
url: $eventLogsEndpoint,
method: 'GET',
headers: [
'AUTHORIZATION: AVM-SID '. $sessionId,
'Content-Type: application/json',
]
);
if ($response['status'] === 200) {
$workingEndpoint = $eventLogsEndpoint;
break;
}
}
// don't know why they chose 400 code instead of 401
if ($response['status'] === 400) {
$eventLogs = json_decode($response['body'], true);
$responseErrorMessage = 'Unknown';
// retrieving external error messages if available
if (is_array($eventLogs) && !empty($eventLogs['errors'])) {
$responseErrorMessage = implode(', ', array_column($eventLogs['errors'], 'message'));
}
throw new Exception(
message: sprintf(
'Authentication is invalid or has expired! HTTP Code: %s; Message: %s',
(string) $response['status'],
$responseErrorMessage
),
code: (int) $response['status']
);
}
if ($response['status'] !== 200) {
throw new Exception(
message: sprintf(
'Request is failed! HTTP (Code: %s) GET %s',
(string) $response['status'],
$eventLogsEndpoint
),
code: (int) $response['status']
);
}
try {
$eventLogs = json_decode(
$response['body'],
true,
512,
JSON_THROW_ON_ERROR
);
} catch (JsonException $e) {
throw new Exception(
message: sprintf('Unexpected eventlog output decoding error: %s', $e->getMessage()),
previous: $e
);
}
$eventLogs = array_map(
fn ($entry) => [
'timestamp' => DateTime::createFromFormat('d.m.y H:i:s', $entry['date'].' '.$entry['time'])->getTimestamp(),
'date' => $entry['date'],
'time' => $entry['time'],
'id' => $entry['id'],
'group' => $entry['group'],
'msg' => $entry['msg'],
'nohelp' => $entry['nohelp'],
],
$eventLogs
);
uasort($eventLogs, fn ($a, $b) => $a['timestamp'] <=> $b['timestamp']);
return $eventLogs;
}
/**
* Sends event logs to a syslog server using RFC 3164 format
*
* Establishes and maintains a persistent connection to the syslog server.
* Formats each log entry according to RFC 3164 before sending.
*
* @param string $endpoint The syslog server URL (e.g., udp://127.0.0.1:514)
* @param array<int, array{timestamp: int, ...}> $eventLogs Array of log entries
* @throws Exception When connection fails or writing to socket fails
* @return void
*/
function sendLogsToSyslog(
string $endpoint,
array $eventLogs
): void {
static $syslogConnection = null;
// open the connection once and closes it when script ends
if ($syslogConnection === null) {
[$syslogProtocol, $syslogHost, $syslogPort] = substr_count($endpoint, ':') === 2
? explode(':', $endpoint, 3)
: array_merge(explode(':', $endpoint, 2), [514]);
$syslogConnection = fsockopen(
hostname: $syslogProtocol .':'. $syslogHost,
port: (int) $syslogPort,
error_code: $errno,
error_message: $errstr,
timeout: 30
);
if ($syslogConnection === false) {
$syslogConnection = null;
throw new Exception(sprintf(
'Syslog server connection error: (%s) %s',
(string) $errno,
$errstr
));
}
stdOut('Connection to syslog server established.');
// TODO: decouple syslog connection and signal handler logic
$syslogCloseConnectionFunction = function () use ($syslogConnection) {
fclose($syslogConnection);
stdOut('Connection to syslog server closed.');
exit(0);
};
// if we can handle signalts, attempt to gracefully close the syslog server connection
if (preg_match('/^win/i', PHP_OS)) {
sapi_windows_set_ctrl_handler(fn (int $event) => match($event) {
PHP_WINDOWS_EVENT_CTRL_C => $syslogCloseConnectionFunction(),