forked from roleoroleo/onvif_simple_server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
1578 lines (1397 loc) · 43.4 KB
/
Copy pathutils.c
File metadata and controls
1578 lines (1397 loc) · 43.4 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
/*
* Copyright (c) 2024 roleo.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/reboot.h>
#include <ctype.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <time.h>
#ifdef HAVE_WOLFSSL
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/sha.h>
#include <wolfssl/wolfcrypt/coding.h>
#else
#ifdef HAVE_MBEDTLS
#include <mbedtls/sha1.h>
#include <mbedtls/base64.h>
#else
#include <tomcrypt.h>
#endif
#endif
#include <zlib.h>
#include "utils.h"
#include "onvif_simple_server.h"
#include "log.h"
#define SHMOBJ_PATH "/onvif_subscription"
#define MEM_LOCK_FILE "/sub_mem_lock"
sem_t *sem_memory_lock = SEM_FAILED;
/**
* Open a semaphore
* @return 0 on success, -1 on error
*/
int sem_memory_open()
{
sem_memory_lock = sem_open(MEM_LOCK_FILE, O_CREAT, S_IRUSR | S_IWUSR, 1);
if (sem_memory_lock == SEM_FAILED) {
fprintf(stderr, "Error opening semaphore file %s\n", MEM_LOCK_FILE);
return -1;
}
return 0;
}
/**
* Close a semaphore
*/
void sem_memory_close()
{
if (sem_memory_lock != SEM_FAILED) {
sem_close(sem_memory_lock);
sem_memory_lock = SEM_FAILED;
sem_unlink(MEM_LOCK_FILE);
}
return;
}
/**
* Create or open shared memory to share subscriptions and events
* @param create Set to 1 if the memory must be created, 0 if not
* @return a pointer to the shared memory
*/
void *create_shared_memory(int create) {
int shmfd, rc;
int shared_seg_size = sizeof(shm_t);
char *shared_area; /* the pointer to the shared segment */
/* creating the shared memory object.
int shm_open(const char *name, int oflag, mode_t mode);
oflags:
O_CREAT Create the shared memory object if it does not exist.
O_RDWR Open the object for read-write access.
O_RDONLY Open the object for read access.
O_EXCL If O_CREAT was also specified, and a shared memory object
with the given name already exists, return an error. The
check for the existence of the object, and its creation if
it does not exist, are performed atomically.
O_TRUNC If the shared memory object already exists, truncate it to
zero bytes.
mode:
S_IRWXU file owner has read, write and execute permission.
S_IRWXG group has read, write and execute permission.
S_IRWXO others have read, write and execute permission.
S_IROTH others have read permission.
A new shared memory object initially has zero length.
The size of the object can be set using ftruncate(2).
Return Value: On successful completion shm_open() returns a new
nonnegative file descriptor referring to the shared memory object.
On failure, shm_open() returns -1.
*/
if (create) {
shmfd = shm_open(SHMOBJ_PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
} else {
shmfd = shm_open(SHMOBJ_PATH, O_RDWR, S_IRWXU | S_IRWXG);
}
if (shmfd < 0) {
log_error("shm_open() failed");
return NULL;
}
log_debug("Created shared memory object %s", SHMOBJ_PATH);
/* adjusting mapped file size (make room for the whole segment to map) */
rc = ftruncate(shmfd, shared_seg_size);
if (rc != 0) {
log_error("ftruncate() failed");
shm_unlink(SHMOBJ_PATH);
return NULL;
}
/* requesting the shared segment */
shared_area = (char *)mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if (shared_area == MAP_FAILED /* is ((void*)-1) */ ) {
log_error("mmap() failed");
shm_unlink(SHMOBJ_PATH);
return NULL;
}
log_debug("Shared memory segment allocated correctly (%d bytes) at address %p", shared_seg_size, shared_area);
if (sem_memory_open() != 0) {
fprintf(stderr, "Error, could not open semaphore\n") ;
munmap(shared_area, shared_seg_size);
shm_unlink(SHMOBJ_PATH);
return NULL;
}
return shared_area;
}
/**
* Destroy shared memory
* @param shared_area Pointer to the shared memory
* @param destroy_all Set to 1 to unlink the file
*/
void destroy_shared_memory(void *shared_area, int destroy_all)
{
int shared_seg_size = sizeof(shm_t);
// Check for NULL pointer to prevent segfaults
if (shared_area == NULL) {
log_debug("destroy_shared_memory called with NULL pointer, skipping");
return;
}
sem_memory_close();
if (munmap(shared_area, shared_seg_size) != 0) {
log_error("munmap() failed");
return;
}
if (destroy_all) {
if (shm_unlink(SHMOBJ_PATH) != 0) {
log_error("shm_unlink() failed");
return;
}
}
log_debug("Shared memory segment deallocated correctly");
}
int sem_memory_wait()
{
struct timespec ts;
if (sem_memory_lock == SEM_FAILED) {
log_error("Semaphore not initialized");
return -1;
}
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5;
if (sem_timedwait(sem_memory_lock, &ts) != 0) {
log_error("Semaphore wait timed out or failed -- semaphore may be stale");
return -1;
}
return 0;
}
int sem_memory_post()
{
if (sem_memory_lock == SEM_FAILED) {
log_error("Semaphore not initialized");
return -1;
}
return sem_post(sem_memory_lock);
}
#ifdef USE_ZLIB
/**
* Decompress a gzipped file
* @param file_in The input file name
* @param file_out The output file pointer
* @return 0 on success, negative on error
*/
int gzip_d(FILE *file_out, char *file_in)
{
char buf[1024];
char file_in_gz[MAX_LEN];
sprintf(file_in_gz, "%s.gz", file_in);
gzFile fi;
if (access(file_in_gz, F_OK) == 0) {
fi = gzopen(file_in_gz, "rb");
} else {
fi = gzopen(file_in, "rb");
}
if (!fi) {
return -1;
}
if (file_out == NULL) {
gzclose(fi);
return -2;
}
gzrewind(fi);
while (!gzeof(fi)) {
int len = gzread(fi, buf, sizeof(buf));
if ((len < 0) || ((len == 0) && (!gzeof(fi)))) {
gzclose(fi);
return -3;
}
if (fwrite(buf, 1, len, file_out) < 0) {
gzclose(fi);
return -4;
}
}
gzclose(fi);
return 0;
}
#endif
/**
* Generate ONVIF-compliant SOAP fault response
* @param out The output type: "stdout", char *ptr or NULL
* @param fault_subcode The ONVIF fault subcode (e.g., "ter:ActionNotSupported")
* @param fault_reason The human-readable fault reason
* @param fault_detail Additional fault details
* @return the number of bytes written
*/
// Global flag to indicate if the last cat() call returned a SOAP fault
int g_last_response_was_soap_fault = 0;
/**
* Output appropriate HTTP headers based on whether the response is a SOAP fault
* @param content_length The content length to include in headers
*/
void output_http_headers(long content_length)
{
if (g_last_response_was_soap_fault) {
fprintf(stdout, "Status: 500 Internal Server Error\r\n");
}
fprintf(stdout, "Content-type: application/soap+xml\r\n");
fprintf(stdout, "Content-Length: %ld\r\n", content_length);
fprintf(stdout, "Connection: close\r\n\r\n");
}
long cat_soap_fault(char* out, const char* fault_subcode, const char* fault_reason, const char* fault_detail)
{
const char* soap_fault_template = "<?xml version=\"1.0\" ?>"
"<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\""
" xmlns:ter=\"http://www.onvif.org/ver10/error\""
" xmlns:xs=\"http://www.w3.org/2000/10/XMLSchema\">"
"<soapenv:Body>"
"<soapenv:Fault>"
"<soapenv:Code>"
"<soapenv:Value>env:Receiver</soapenv:Value>"
"<soapenv:Subcode>"
"<soapenv:Value>%s</soapenv:Value>"
"</soapenv:Subcode>"
"</soapenv:Code>"
"<soapenv:Reason>"
"<soapenv:Text xml:lang=\"en\">%s</soapenv:Text>"
"</soapenv:Reason>"
"<soapenv:Node>http://www.w3.org/2003/05/soap-envelope/node/ultimateReceiver</soapenv:Node>"
"<soapenv:Role>http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver</soapenv:Role>"
"<soapenv:Detail>"
"<soapenv:Text>%s</soapenv:Text>"
"</soapenv:Detail>"
"</soapenv:Fault>"
"</soapenv:Body>"
"</soapenv:Envelope>\r\n";
char soap_fault[4096];
int len = snprintf(soap_fault, sizeof(soap_fault), soap_fault_template, fault_subcode, fault_reason, fault_detail);
// Set global flag to indicate this is a SOAP fault
g_last_response_was_soap_fault = 1;
if (out == NULL) {
// First call - just return size for Content-Length calculation
return len;
} else if (strcmp(out, "stdout") == 0) {
// Second call - output the SOAP fault body only
// The service function will handle HTTP status and headers
printf("%s", soap_fault);
fflush(stdout);
} else {
// Output to buffer
strcpy(out, soap_fault);
}
return len;
}
/**
* Read a file line by line and send to output after replacing arguments
* @param out The output type: "sdout", char *ptr or NULL
* @param filename The input file to process
* @param num The number of variable arguments
* @param ... The argument list to replace: src1, dst1, src2, dst2, etc...
* @return the number of processed bytes
*/
long cat(char *out, char *filename, int num, ...)
{
va_list valist;
char new_line[MAX_CAT_LEN];
char *l;
char *ptr = out;
char *pars, *pare, *par_to_find, *par_to_sub;
int i;
long ret = 0;
FILE *file;
// Reset SOAP fault flag for normal file operations
g_last_response_was_soap_fault = 0;
#ifdef USE_ZLIB
file = tmpfile();
if (file == NULL) {
log_error("Unable to open file %s", filename);
return -1;
}
if (gzip_d(file, filename) != 0) {
log_error("Unable to decompress file %s", filename);
fclose(file);
return -2;
}
rewind(file);
#else
file = fopen(filename, "r");
if (!file) {
log_error("Unable to open file %s", filename);
return -3;
}
#endif
if (!file) {
log_error("Unable to open file %s", filename);
// Return ONVIF-compliant SOAP fault instead of empty response
return cat_soap_fault(out,
"ter:ActionNotSupported",
"Optional Action Not Implemented",
"The requested XML template is not available on this device");
}
char line[MAX_CAT_LEN];
while (fgets(line, sizeof(line), file)) {
va_start(valist, num);
memset(new_line, '\0', sizeof(new_line));
for (i = 0; i < num/2; i++) {
par_to_find = va_arg(valist, char *);
par_to_sub = va_arg(valist, char *);
pars = strstr(line, par_to_find);
if (pars != NULL) {
pare = pars + strlen(par_to_find);
size_t prefix_len = pars - line;
size_t sub_len = strlen(par_to_sub);
size_t suffix_len = line + strlen(line) - pare;
// Check if the replacement will fit in new_line buffer
if (prefix_len + sub_len + suffix_len < MAX_CAT_LEN - 1) {
strncpy(new_line, line, prefix_len);
new_line[prefix_len] = '\0'; // Ensure null termination
strcpy(&new_line[prefix_len], par_to_sub);
strncpy(&new_line[prefix_len + sub_len], pare, suffix_len);
new_line[prefix_len + sub_len + suffix_len] = '\0'; // Ensure null termination
} else {
log_error("String replacement would overflow buffer in cat function");
// Keep original line unchanged if replacement would overflow
}
}
if (new_line[0] != '\0') {
strcpy(line, new_line);
memset(new_line, '\0', sizeof(new_line));
}
}
if (new_line[0] == '\0') {
l = trim(line);
} else {
l = trim(new_line);
}
if ((out != NULL) && (*l != '\0')) {
if (strcmp("stdout", out) == 0) {
if (*l != '<') {
fprintf(stdout, " ");
}
fprintf(stdout, "%s", l);
} else {
if (*l != '<') {
sprintf(ptr, " ");
ptr++;
}
sprintf(ptr, "%s", l);
ptr += strlen(l);
}
}
if ((*l != '\0') && (*l != '<')) {
ret++;
}
ret += strlen(l);
va_end(valist);
}
fclose(file);
return ret;
}
/**
* Get the IP address/netmask of an interface "name"
* @param name The name of the interface
* @param netmask String that will contain the netmask
* @param address String that will contain the address
* @return 0 on success, negative on error
*/
int get_ip_address(char *address, char *netmask, char *name)
{
struct ifaddrs *ifaddr, *ifa;
int family, s;
char *host;
char *mask;
struct sockaddr_in *sa, *san;
int found = 0;
if (getifaddrs(&ifaddr) == -1) {
log_error("Error in getifaddrs()");
return -1;
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
if ((strcmp(ifa->ifa_name, name) == 0) && (ifa->ifa_addr->sa_family == AF_INET)) {
sa = (struct sockaddr_in *) ifa->ifa_addr;
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), address, 16);
san = (struct sockaddr_in *) ifa->ifa_netmask;
inet_ntop(AF_INET, &(((struct sockaddr_in *)san)->sin_addr), netmask, 16);
log_debug("Interface: <%s>", ifa->ifa_name);
log_debug("Address: <%s>", address);
log_debug("Netmask: <%s>", netmask);
found = 1;
}
}
freeifaddrs(ifaddr);
if (found != 1)
return -2;
return 0;
}
/**
* Get the MAC address of an interface "name"
* @param name The name of the interface
* @param address String that will contain the address
* @return 0 on success, negative on error
*/
int get_mac_address(char *address, char *name)
{
struct ifreq ifr;
struct ifconf ifc;
char buf[MAX_LEN];
int success = 0;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) {
return -1;
}
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) {
close(sock);
return -2;
}
struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name);
if (strcmp(name, ifr.ifr_name) == 0) {
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
success = 1;
break;
}
}
}
}
}
if (success) {
sprintf(address, "%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned char) ifr.ifr_hwaddr.sa_data[0],
(unsigned char) ifr.ifr_hwaddr.sa_data[1],
(unsigned char) ifr.ifr_hwaddr.sa_data[2],
(unsigned char) ifr.ifr_hwaddr.sa_data[3],
(unsigned char) ifr.ifr_hwaddr.sa_data[4],
(unsigned char) ifr.ifr_hwaddr.sa_data[5]);
} else {
log_error("Unable to get mac address");
close(sock);
return -4;
}
log_debug("MAC address: <%s>", address);
close(sock);
return 0;
}
/**
* Convert the netmask to a len
* @param netmask The netmask to convert
* @return the len of the netmask
*/
int netmask2prefixlen(char *netmask)
{
int n;
int i = 0;
inet_pton(AF_INET, netmask, &n);
while (n > 0) {
n = n >> 1;
i++;
}
log_debug("Prefix length: %d", i);
return i;
}
/**
* Get MTU for interface if_name
* @param if_name The name of the interface
* @return The value of the MTU
*/
int get_mtu(char *if_name)
{
int ret = 0;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
struct ifreq ifr;
strcpy(ifr.ifr_name, if_name);
if(ioctl(sock, SIOCGIFMTU, &ifr) == 0) {
ret = ifr.ifr_mtu;
}
return ret;
}
/**
* Remove spaces from the left of the string
* @param s The input string
* @return A pointer to the resulting string
*/
char *ltrim(char *s)
{
char *p = s;
while(isspace(*p)) p++;
return p;
}
/**
* Remove spaces from the right of the string
* @param s The input string
* @return A pointer to the resulting string
*/
char *rtrim(char *s)
{
int iret = strlen(s);
char* back = s + iret;
back--;
while (isspace(*back)) {
*back = '\0';
back--;
}
return s;
}
/**
* Remove spaces from the left and the right of the string
* @param s The input string
* @return A pointer to the resulting string
*/
char *trim(char *s)
{
return ltrim(rtrim(s));
}
/**
* Remove space, tab, CR and LF from the left of the string
* @param s The input string
* @return A pointer to the resulting string
*/
char *ltrim_mf(char *s)
{
char *p = s;
while((*p == ' ') || (*p == '\t') || (*p == '\n') || (*p == '\r')) p++;
return p;
}
/**
* Remove space, tab, CR and LF from the right of the string
* @param s The input string
* @return A pointer to the resulting string
*/
char *rtrim_mf(char *s)
{
int iret = strlen(s);
char* back = s + iret;
if (iret == 0) return s;
back--;
while ((back >= s) && ((*back == ' ') || (*back == '\t') || (*back == '\n') || (*back == '\r'))) {
*back = '\0';
back--;
}
return s;
}
/**
* Remove space, tab, CR and LF from the left and the right of the string
* @param s The input string
* @return A pointer to the resulting string
*/
char *trim_mf(char *s)
{
return ltrim_mf(rtrim_mf(s));
}
int html_escape(char *url, int max_len)
{
int i, count = 0;
char s_tmp[max_len];
char *f, *t;
memset(s_tmp, '\0', max_len);
// Count chars to escape
for (i = 0; i < strlen(url); i++)
{
switch (url[i]) {
case '\"':
count += 5;
break;
case '&':
count += 4;
break;
case '\'':
count += 4;
break;
case '<':
count += 3;
break;
case '>':
count += 3;
break;
}
}
if (strlen(url) + count + 1 > max_len) {
return -1;
}
f = url;
t = (char *) &s_tmp[0];
while (*f != '\0' && (t - s_tmp) < (max_len - 10)) { // Leave room for escape sequences
switch (*f) {
case '\"':
if ((t - s_tmp) < (max_len - 6)) { // " = 6 chars
*t = '&';
t++;
*t = 'q';
t++;
*t = 'u';
t++;
*t = 'o';
t++;
*t = 't';
t++;
*t = ';';
} else {
*t = *f; // Fallback if no room for escape
}
break;
case '&':
if ((t - s_tmp) < (max_len - 5)) { // & = 5 chars
*t = '&';
t++;
*t = 'a';
t++;
*t = 'm';
t++;
*t = 'p';
t++;
*t = ';';
} else {
*t = *f;
}
break;
case '\'':
if ((t - s_tmp) < (max_len - 5)) { // ' = 5 chars
*t = '&';
t++;
*t = '#';
t++;
*t = '3';
t++;
*t = '9';
t++;
*t = ';';
} else {
*t = *f;
}
break;
case '<':
if ((t - s_tmp) < (max_len - 4)) { // < = 4 chars
*t = '&';
t++;
*t = 'l';
t++;
*t = 't';
t++;
*t = ';';
} else {
*t = *f;
}
break;
case '>':
if ((t - s_tmp) < (max_len - 4)) { // > = 4 chars
*t = '&';
t++;
*t = 'g';
t++;
*t = 't';
t++;
*t = ';';
} else {
*t = *f;
}
break;
default:
*t = *f;
}
t++;
f++;
}
*t = '\0'; // Ensure null termination
strcpy(url, (char *) s_tmp);
}
/**
* Hashes a given sequence of bytes using the SHA1 algorithm
* @param output The hash
* @param output_size The size of the buffer containing the hash (>= 20)
* @param input The input sequence pointer
* @param input_size The size of the input sequence
* @return A malloc-allocated pointer to the resulting data. 20 bytes long.
*/
int hashSHA1(char* input, unsigned long input_size, char *output, int output_size)
{
if (output_size < 20)
return -1;
#ifdef HAVE_WOLFSSL
wc_Sha sha;
wc_InitSha(&sha);
wc_ShaUpdate(&sha, input, input_size);
wc_ShaFinal(&sha, output);
#else
#ifdef HAVE_MBEDTLS
//Initial
mbedtls_sha1_context ctx;
//Initialize a state variable for the hash
mbedtls_sha1_init(&ctx);
mbedtls_sha1_starts(&ctx);
//Process the text - remember you can call process() multiple times
mbedtls_sha1_update(&ctx, (const unsigned char*) input, input_size);
//Finish the hash calculation
mbedtls_sha1_finish(&ctx, output);
mbedtls_sha1_free(&ctx);
#else
//Initial
hash_state md;
//Initialize a state variable for the hash
sha1_init(&md);
//Process the text - remember you can call process() multiple times
sha1_process(&md, (const unsigned char*) input, input_size);
//Finish the hash calculation
sha1_done(&md, output);
#endif //HAVE_MBEDTLS
#endif //HAVE_WOLFSSL
return 0;
}
/**
* Decode a base64 string
* @param output The decoded sequence pointer
* @param output_size The size of the buffer/decoded sequence
* @param input The input sequence pointer
* @param input_size The size of the input sequence
*/
void b64_decode(unsigned char *input, unsigned int input_size, unsigned char *output, unsigned long *output_size)
{
#ifdef HAVE_WOLFSSL
word32 olen;
Base64_Decode((const unsigned char*) input, input_size, output, &olen);
*output_size = olen;
#else
#ifdef HAVE_MBEDTLS
size_t olen;
mbedtls_base64_decode(output, *output_size, &olen, input, input_size);
*output_size = olen;
#else
base64_decode(input, input_size, output, output_size);
#endif
#endif
}
/**
* Encode a base64 string
* @param output The encoded sequence pointer
* @param output_size The size of the buffer/encoded sequence
* @param input The input sequence pointer
* @param input_size The size of the input sequence
*/
void b64_encode(unsigned char *input, unsigned int input_size, unsigned char *output, unsigned long *output_size)
{
#ifdef HAVE_WOLFSSL
word32 olen;
Base64_Encode_NoNl((const unsigned char*) input, input_size, output, &olen);
*output_size = olen;
#else
#ifdef HAVE_MBEDTLS
size_t olen;
mbedtls_base64_encode(output, *output_size, &olen, input, input_size);
*output_size = olen;
#else
base64_encode(input, input_size, output, output_size);
#endif
#endif
}
/**
* Convert an interval in ONVIF notation to a interval in seconds
* @param interval String that represents the interval
* @return Time interval in seconds
*/
int interval2sec(const char *interval)
{
int d1 = -1, d2 = -1, d3 = -1, n, ret;
char c1 = 'c', c2 = 'c', c3 = 'c';
n = sscanf(interval, "PT%d%c%d%c%d%c", &d1, &c1, &d2, &c2, &d3, &c3);
if (n % 2 == 1)
return -1;
if ((n < 2) || (n > 6))
return -1;
ret = -2;
switch (c1) {
case 's':
case 'S':
ret = d1;
break;
case 'm':
case 'M':
ret = d1 * 60;
break;
case 'h':
case 'H':
ret = d1 * 3600;
break;
default:
return ret;
}
switch (c2) {
case 's':
case 'S':
ret += d2;
break;
case 'm':
case 'M':
ret += d2 * 60;
break;
case 'h':
case 'H':
ret += d2 * 3600;
break;
default:
return ret;
}
switch (c3) {
case 's':
case 'S':
ret += d3;
break;
case 'm':
case 'M':
ret += d3 * 60;
break;
case 'h':
case 'H':
ret += d3 * 3600;
break;
default:
return ret;
}
return ret;
}
/**
* Convert a time_t to a datetime in ISO format
* @param timestamp Time in time_t
* @param iso_date Output time in ISO format
* @return 0 on success, negative on error
*/
int to_iso_date(char *iso_date, int size, time_t timestamp)
{
struct tm my_tm;
gmtime_r(×tamp, &my_tm);
if (size < 21) return -1;
sprintf(iso_date, "%04d-%02d-%02dT%02d:%02d:%02dZ",
my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday,
my_tm.tm_hour, my_tm.tm_min, my_tm.tm_sec);
return 0;
}
/**
* Convert a datetime in ISO format to a time_t
* @param iso_date Time in ISO format
* @return Time in time_t
*/
time_t from_iso_date(const char *date)
{
struct tm tt = {0};
double seconds = 0;
// Try date with seconds
if (sscanf(date, "%04d-%02d-%02dT%02d:%02d:%lfZ",
&tt.tm_year, &tt.tm_mon, &tt.tm_mday,