-
Notifications
You must be signed in to change notification settings - Fork 728
/
Copy pathlibfreshclam_internal.c
2769 lines (2383 loc) · 91.9 KB
/
libfreshclam_internal.c
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) 2013-2025 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
* Copyright (C) 2002-2007 Tomasz Kojm <[email protected]>
*
* HTTP/1.1 compliance by Arkadiusz Miskiewicz <[email protected]>
* Proxy support by Nigel Horne <[email protected]>
* Proxy authorization support by Gernot Tenchio <[email protected]>
* (uses fmt_base64() from libowfat (http://www.fefe.de))
*
* CDIFF code (C) 2006 Sensory Networks, Inc.
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
/* for strptime, it is POSIX, but defining _XOPEN_SOURCE to 600
* fails on Solaris because it would require a c99 compiler,
* 500 fails completely on Solaris, and FreeBSD, and w/o _XOPEN_SOURCE
* strptime is not defined on Linux */
#define __EXTENSIONS
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <ctype.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#endif
#include <sys/types.h>
#include <time.h>
#include <fcntl.h>
#ifndef _WIN32
#include <sys/wait.h>
#endif
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <zlib.h>
#include <math.h>
#include <curl/curl.h>
#include <openssl/rand.h>
#include "target.h"
// libclamav
#include "clamav.h"
#include "others.h"
#include "str.h"
#include "cvd.h"
#include "regex_list.h"
// common
#include "optparser.h"
#include "output.h"
#include "clamav_rust.h"
#include "tar.h"
#include "clamdcom.h"
#include "cert_util.h"
#include "libfreshclam.h"
#include "libfreshclam_internal.h"
#include "dns.h"
#define DB_FILENAME_MAX 60
#define CVD_HEADER_SIZE 512
/*
* Globals
*/
/* Callback function pointers */
fccb_download_complete g_cb_download_complete = NULL;
/* Configuration options */
char *g_localIP = NULL;
char *g_userAgent = NULL;
char *g_proxyServer = NULL;
uint16_t g_proxyPort = 0;
char *g_proxyUsername = NULL;
char *g_proxyPassword = NULL;
char *g_tempDirectory = NULL;
char *g_databaseDirectory = NULL;
uint32_t g_maxAttempts = 0;
uint32_t g_connectTimeout = 0;
uint32_t g_requestTimeout = 0;
uint32_t g_bCompressLocalDatabase = 0;
freshclam_dat_v1_t *g_freshclamDat = NULL;
uint8_t g_lastRay[CFRAY_LEN + 1] = {0};
/** @brief Generate a Version 4 UUID according to RFC-4122
*
* Uses the openssl RAND_bytes function to generate a Version 4 UUID.
*
* Copyright 2021 Karthik Velakur with some modifications by the ClamAV team.
* License: MIT
* From: https://gist.github.com/kvelakur/9069c9896577c3040030
*
* @param buffer A buffer that is SIZEOF_UUID_V4
*/
static void uuid_v4_gen(char *buffer)
{
union {
struct
{
uint32_t time_low;
uint16_t time_mid;
uint16_t time_hi_and_version;
uint8_t clk_seq_hi_res;
uint8_t clk_seq_low;
uint8_t node[6];
};
uint8_t __rnd[16];
} uuid;
if (0 >= RAND_bytes(uuid.__rnd, sizeof(uuid.__rnd))) {
/* Failed to generate random bytes for new UUID */
memset(uuid.__rnd, 0, sizeof(uuid.__rnd));
uuid.time_low = (uint32_t)time(NULL);
}
// Refer Section 4.2 of RFC-4122
// https://tools.ietf.org/html/rfc4122#section-4.2
uuid.clk_seq_hi_res = (uint8_t)((uuid.clk_seq_hi_res & 0x3F) | 0x80);
uuid.time_hi_and_version = (uint16_t)((uuid.time_hi_and_version & 0x0FFF) | 0x4000);
snprintf(buffer, SIZEOF_UUID_V4, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
uuid.clk_seq_hi_res, uuid.clk_seq_low,
uuid.node[0], uuid.node[1], uuid.node[2],
uuid.node[3], uuid.node[4], uuid.node[5]);
buffer[SIZEOF_UUID_V4 - 1] = 0;
return;
}
fc_error_t load_freshclam_dat(void)
{
fc_error_t status = FC_EINIT;
int handle = -1;
ssize_t bread = 0;
freshclam_dat_v1_t *mdat = NULL;
uint32_t version = 0;
char magic[13] = {0};
/* Change directory to database directory */
if (chdir(g_databaseDirectory)) {
logg(LOGG_ERROR, "Can't change dir to %s\n", g_databaseDirectory);
status = FC_EDIRECTORY;
goto done;
}
logg(LOGG_DEBUG, "Current working dir is %s\n", g_databaseDirectory);
if (-1 == (handle = open("freshclam.dat", O_RDONLY | O_BINARY))) {
char currdir[PATH_MAX];
if (getcwd(currdir, sizeof(currdir)))
logg(LOGG_DEBUG, "Can't open freshclam.dat in %s\n", currdir);
else
logg(LOGG_DEBUG, "Can't open freshclam.dat in the current directory\n");
logg(LOGG_DEBUG, "It probably doesn't exist yet. That's ok.\n");
status = FC_EFILE;
goto done;
}
if (strlen(MIRRORS_DAT_MAGIC) != (bread = read(handle, &magic, strlen(MIRRORS_DAT_MAGIC)))) {
char error_message[260];
cli_strerror(errno, error_message, 260);
logg(LOGG_ERROR, "Can't read magic from freshclam.dat. Bytes read: %zi, error: %s\n", bread, error_message);
goto done;
}
if (0 != strncmp(magic, MIRRORS_DAT_MAGIC, strlen(MIRRORS_DAT_MAGIC))) {
logg(LOGG_DEBUG, "Magic bytes for freshclam.dat did not match expectations.\n");
goto done;
}
if (sizeof(uint32_t) != (bread = read(handle, &version, sizeof(uint32_t)))) {
char error_message[260];
cli_strerror(errno, error_message, 260);
logg(LOGG_ERROR, "Can't read version from freshclam.dat. Bytes read: %zi, error: %s\n", bread, error_message);
goto done;
}
switch (version) {
case 1: {
/* Verify that file size is as expected. */
off_t file_size = lseek(handle, 0L, SEEK_END);
size_t minSize = strlen(MIRRORS_DAT_MAGIC) + sizeof(freshclam_dat_v1_t);
if (minSize > (size_t)file_size) {
logg(LOGG_DEBUG, "freshclam.dat is smaller than expected: %zu != %ld\n", sizeof(freshclam_dat_v1_t), file_size);
goto done;
}
/* Rewind to just after the magic bytes and read data struct */
if (-1 == lseek(handle, strlen(MIRRORS_DAT_MAGIC), SEEK_SET)) {
char error_message[260];
cli_strerror(errno, error_message, 260);
logg(LOGG_ERROR, "Can't seek to %lu, error: %s\n", strlen(MIRRORS_DAT_MAGIC), error_message);
goto done;
}
mdat = malloc(sizeof(freshclam_dat_v1_t));
if (NULL == mdat) {
logg(LOGG_ERROR, "Failed to allocate memory for freshclam.dat\n");
status = FC_EMEM;
goto done;
}
if (sizeof(freshclam_dat_v1_t) != (bread = read(handle, mdat, sizeof(freshclam_dat_v1_t)))) {
char error_message[260];
cli_strerror(errno, error_message, 260);
logg(LOGG_ERROR, "Can't read from freshclam.dat. Bytes read: %zi, error: %s\n", bread, error_message);
goto done;
}
if (sizeof(g_lastRay) != (bread = read(handle, &g_lastRay, sizeof(g_lastRay)))) {
char error_message[260];
cli_strerror(errno, error_message, 260);
logg(LOGG_DEBUG, "Last cf-ray not present in freshclam.dat.\n");
memset(g_lastRay, 0, sizeof(g_lastRay));
}
/* Got it. */
close(handle);
handle = -1;
/* This is the latest version.
If we change the format in the future, we may wish to create a new
freshclam.dat struct, import the relevant bits to the new format,
and then save (overwrite) freshclam.dat with the new data. */
if (NULL != g_freshclamDat) {
free(g_freshclamDat);
}
g_freshclamDat = mdat;
mdat = NULL;
break;
}
default: {
logg(LOGG_DEBUG, "freshclam.dat version is different than expected: %u != %u\n", 1, version);
goto done;
}
}
logg(LOGG_DEBUG, "Loaded freshclam.dat:\n");
logg(LOGG_DEBUG, " version: %d\n", g_freshclamDat->version);
logg(LOGG_DEBUG, " uuid: %s\n", g_freshclamDat->uuid);
if (g_freshclamDat->retry_after > 0) {
char retry_after_string[26];
struct tm *tm_info = localtime(&g_freshclamDat->retry_after);
if (NULL == tm_info) {
logg(LOGG_ERROR, "Failed to query the local time for the retry-after date!\n");
goto done;
}
strftime(retry_after_string, 26, "%Y-%m-%d %H:%M:%S", tm_info);
logg(LOGG_DEBUG, " retry-after: %s\n", retry_after_string);
}
status = FC_SUCCESS;
done:
if (-1 != handle) {
close(handle);
}
if (FC_SUCCESS != status) {
if (NULL != mdat) {
free(mdat);
}
if (NULL != g_freshclamDat) {
free(g_freshclamDat);
g_freshclamDat = NULL;
}
}
return status;
}
fc_error_t save_freshclam_dat(void)
{
fc_error_t status = FC_EINIT;
int handle = -1;
if (NULL == g_freshclamDat) {
logg(LOGG_ERROR, "Attempted to save freshclam.dat before initializing data struct!\n");
goto done;
}
if (-1 == (handle = open("freshclam.dat", O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644))) {
char currdir[PATH_MAX];
if (getcwd(currdir, sizeof(currdir)))
logg(LOGG_ERROR, "Can't create freshclam.dat in %s\n", currdir);
else
logg(LOGG_ERROR, "Can't create freshclam.dat in the current directory\n");
logg(LOGG_INFO, "Hint: The database directory must be writable for UID %d or GID %d\n", getuid(), getgid());
status = FC_EDBDIRACCESS;
goto done;
}
if (-1 == write(handle, MIRRORS_DAT_MAGIC, strlen(MIRRORS_DAT_MAGIC))) {
logg(LOGG_ERROR, "Can't write to freshclam.dat\n");
}
if (-1 == write(handle, g_freshclamDat, sizeof(freshclam_dat_v1_t))) {
logg(LOGG_ERROR, "Can't write to freshclam.dat\n");
}
if (-1 == write(handle, &g_lastRay, sizeof(g_lastRay))) {
logg(LOGG_ERROR, "Can't write to freshclam.dat\n");
}
logg(LOGG_DEBUG, "Saved freshclam.dat\n");
status = FC_SUCCESS;
done:
if (-1 != handle) {
close(handle);
}
return status;
}
fc_error_t new_freshclam_dat(void)
{
fc_error_t status = FC_EINIT;
freshclam_dat_v1_t *mdat = calloc(1, sizeof(freshclam_dat_v1_t));
if (NULL == mdat) {
logg(LOGG_ERROR, "Failed to allocate memory for freshclam.dat\n");
status = FC_EMEM;
goto done;
}
mdat->version = 1;
mdat->retry_after = 0;
uuid_v4_gen(mdat->uuid);
if (NULL != g_freshclamDat) {
free(g_freshclamDat);
}
g_freshclamDat = mdat;
logg(LOGG_DEBUG, "Creating new freshclam.dat\n");
if (FC_SUCCESS != save_freshclam_dat()) {
logg(LOGG_ERROR, "Failed to save freshclam.dat!\n");
status = FC_EFILE;
goto done;
}
status = FC_SUCCESS;
done:
if (FC_SUCCESS != status) {
if (NULL != mdat) {
free(mdat);
}
g_freshclamDat = NULL;
}
return status;
}
/**
* @brief Get DNS text record field # for official databases.
*
* @param database Official database name.
* @return int DNS text record field #
*/
static int textrecordfield(const char *database)
{
if (!strcmp(database, "main")) {
return 1;
} else if (!strcmp(database, "daily")) {
return 2;
} else if (!strcmp(database, "bytecode")) {
return 7;
} else if (!strcmp(database, "safebrowsing")) {
return 6;
}
return 0;
}
#if (LIBCURL_VERSION_MAJOR > 7) || ((LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR >= 61))
/* In libcurl 7.61.0, support was added for extracting the time in plain
microseconds. Older libcurl versions are stuck in using 'double' for this
information so we complicate this example a bit by supporting either
approach. */
#define TIME_IN_US 1
#define TIMETYPE curl_off_t
#define TIMEOPT CURLINFO_TOTAL_TIME_T
#define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 3000000
#else
#define TIMETYPE double
#define TIMEOPT CURLINFO_TOTAL_TIME
#define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 3
#endif
#define STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES 6000
struct xfer_progress {
TIMETYPE lastRunTime; /* type depends on version, see above */
uint8_t bComplete;
CURL *curl;
};
static void printTime(double seconds)
{
if (seconds >= 3600) {
fprintf(stdout, "%2.0fh %02.0fm", trunc(seconds / 3600), trunc(fmod(seconds, 3600.0) / 60));
} else if (seconds >= 60) {
fprintf(stdout, "%2.0fm %02.0fs", trunc(seconds / 60), trunc(fmod(seconds, 60.0)));
} else {
fprintf(stdout, "%6.1fs", seconds);
}
}
static void printBytes(curl_off_t bytes, int bPad)
{
if (bytes >= (1024 * 1024)) {
const char *format = bPad ? "%7.02fMiB" : "%.02fMiB";
double megabytes = bytes / (double)(1024 * 1024);
fprintf(stdout, format, megabytes);
} else if (bytes >= 1024) {
const char *format = bPad ? "%7.02fKiB" : "%.02fKiB";
double kilobytes = bytes / (double)(1024);
fprintf(stdout, format, kilobytes);
} else {
const char *format = bPad ? "%9" CURL_FORMAT_CURL_OFF_T "B" : "%" CURL_FORMAT_CURL_OFF_T "B";
fprintf(stdout, format, bytes);
}
}
/**
* Function from curl example code, Copyright (C) 1998 - 2018, Daniel Stenberg, see COPYING.curl for license details
* Progress bar callback function ( CURLOPT_XFERINFOFUNCTION ).
*/
static int xferinfo(void *prog,
curl_off_t TotalToDownload, curl_off_t NowDownloaded,
curl_off_t TotalToUpload, curl_off_t NowUploaded)
{
struct xfer_progress *xferProg = (struct xfer_progress *)prog;
CURL *curl = xferProg->curl;
TIMETYPE curtime = 0;
TIMETYPE remtime = 0;
uint32_t i = 0;
uint32_t totalNumDots = 25;
uint32_t numDots = 0;
double fractiondownloaded = 0.0;
UNUSEDPARAM(TotalToUpload);
UNUSEDPARAM(NowUploaded);
if ((TotalToDownload <= 0.0) || (xferProg->bComplete)) {
return 0;
}
fractiondownloaded = (double)NowDownloaded / (double)TotalToDownload;
numDots = round(fractiondownloaded * totalNumDots);
curl_easy_getinfo(curl, TIMEOPT, &curtime);
xferProg->lastRunTime = curtime;
#ifndef _WIN32
fprintf(stdout, "\e[?7l");
#endif
#ifdef TIME_IN_US
if (fractiondownloaded <= 0.0) {
fprintf(stdout, "Time: ");
printTime(curtime / 1000000.0);
fprintf(stdout, " ");
} else {
remtime = (curtime / fractiondownloaded) - curtime;
fprintf(stdout, "Time: ");
printTime(curtime / 1000000.0);
fprintf(stdout, ", ETA: ");
printTime(remtime / 1000000.0);
fprintf(stdout, " ");
}
#else
if (fractiondownloaded <= 0.0) {
fprintf(stdout, "Time: ");
printTime(curtime);
fprintf(stdout, " ");
} else {
remtime = (curtime / fractiondownloaded) - curtime;
fprintf(stdout, "Time: ");
printTime(curtime);
fprintf(stdout, ", ETA: ");
printTime(remtime);
fprintf(stdout, " ");
}
#endif
fprintf(stdout, "[");
if (numDots > 0) {
if (numDots > 1) {
for (i = 0; i < numDots - 1; i++) {
fprintf(stdout, "=");
}
}
fprintf(stdout, ">");
i++;
}
for (; i < totalNumDots; i++) {
fprintf(stdout, " ");
}
fprintf(stdout, "] ");
printBytes(NowDownloaded, 1);
fprintf(stdout, "/");
printBytes(TotalToDownload, 0);
if (NowDownloaded < TotalToDownload) {
fprintf(stdout, "\r");
} else {
fprintf(stdout, "\n");
xferProg->bComplete = 1;
}
#ifndef _WIN32
fprintf(stdout, "\e[?7h");
#endif
fflush(stdout);
return 0;
}
#if (LIBCURL_VERSION_MAJOR < 7) || ((LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR < 32))
/**
* Function from curl example code, Copyright (C) 1998 - 2018, Daniel Stenberg, see COPYING.curl for license details
* Older style progress bar callback shim; for libcurl older than 7.32.0 ( CURLOPT_PROGRESSFUNCTION ).
*/
static int older_progress(void *prog,
double TotalToDownload, double NowDownloaded,
double TotalToUpload, double NowUploaded)
{
return xferinfo(prog,
(curl_off_t)TotalToDownload,
(curl_off_t)NowDownloaded,
(curl_off_t)TotalToUpload,
(curl_off_t)NowUploaded);
}
#endif
static fc_error_t create_curl_handle(
int bHttp,
int bAllowRedirect,
CURL **curlHandle)
{
fc_error_t status = FC_EARG;
CURL *curl = NULL;
#if (LIBCURL_VERSION_MAJOR > 7) || ((LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR >= 33))
CURLcode curl_ret = CURLE_OK;
#endif
char userAgent[128];
if (NULL == curlHandle) {
logg(LOGG_ERROR, "create_curl_handle: Invalid arguments!\n");
goto done;
}
*curlHandle = NULL;
curl = curl_easy_init();
if (NULL == curl) {
logg(LOGG_ERROR, "create_curl_handle: curl_easy_init failed!\n");
status = FC_EINIT;
goto done;
}
if (g_userAgent) {
strncpy(userAgent, g_userAgent, sizeof(userAgent));
} else {
/*
* Use a randomly generated UUID in the User-Agent
* We'll try to load it from a file in the database directory.
* If none exists, we'll create a new one and save it to said file.
*/
snprintf(userAgent, sizeof(userAgent),
PACKAGE "/%s (OS: " TARGET_OS_TYPE ", ARCH: " TARGET_ARCH_TYPE ", CPU: " TARGET_CPU_TYPE ", UUID: %s)",
get_version(),
g_freshclamDat->uuid);
}
userAgent[sizeof(userAgent) - 1] = 0;
if (mprintf_verbose) {
/* ask libcurl to show us the verbose output */
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_VERBOSE!\n");
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_STDERR, stdout)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to direct curl debug output to stdout!\n");
}
}
if (bHttp) {
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_USERAGENT (%s)!\n", userAgent);
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, g_connectTimeout)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_CONNECTTIMEOUT (%u)!\n", g_connectTimeout);
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, g_requestTimeout)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_LOW_SPEED_TIME (%u)!\n", g_requestTimeout);
}
if (g_requestTimeout > 0) {
/* Minimum speed is 1 byte/second over the previous g_requestTimeout seconds. */
int minimumSpeed = 1;
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, minimumSpeed)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_LOW_SPEED_LIMIT (%u)!\n", minimumSpeed);
}
}
if (bAllowRedirect) {
/* allow three redirects */
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_FOLLOWLOCATION!\n");
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_MAXREDIRS!\n");
}
}
}
#if (LIBCURL_VERSION_MAJOR > 7) || ((LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR >= 33))
if (g_localIP) {
if (NULL == strchr(g_localIP, ':')) {
logg(LOGG_DEBUG, "Local IPv4 address requested: %s\n", g_localIP);
curl_ret = curl_easy_setopt(curl, CURLOPT_DNS_LOCAL_IP4, g_localIP); // Option requires libcurl built with c-ares
switch (curl_ret) {
case CURLE_BAD_FUNCTION_ARGUMENT:
logg(LOGG_ERROR, "create_curl_handle: Unable to bind DNS resolves to %s. Invalid IPv4 address.\n", g_localIP);
status = FC_ECONFIG;
goto done;
break;
case CURLE_UNKNOWN_OPTION:
case CURLE_NOT_BUILT_IN:
logg(LOGG_ERROR, "create_curl_handle: Unable to bind DNS resolves to %s. Option requires that libcurl was built with c-ares.\n", g_localIP);
status = FC_ECONFIG;
goto done;
default:
break;
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_IPRESOLVE (IPv4)!\n");
}
} else {
logg(LOGG_DEBUG, "Local IPv6 address requested: %s\n", g_localIP);
curl_ret = curl_easy_setopt(curl, CURLOPT_DNS_LOCAL_IP6, g_localIP); // Option requires libcurl built with c-ares
switch (curl_ret) {
case CURLE_BAD_FUNCTION_ARGUMENT:
logg(LOGG_WARNING, "create_curl_handle: Unable to bind DNS resolves to %s. Invalid IPv4 address.\n", g_localIP);
status = FC_ECONFIG;
goto done;
break;
case CURLE_UNKNOWN_OPTION:
case CURLE_NOT_BUILT_IN:
logg(LOGG_WARNING, "create_curl_handle: Unable to bind DNS resolves to %s. Option requires that libcurl was built with c-ares.\n", g_localIP);
status = FC_ECONFIG;
goto done;
default:
break;
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_IPRESOLVE (IPv6)!\n");
}
}
}
#endif
if (g_proxyServer) {
/*
* Proxy requested.
*/
logg(LOGG_DEBUG, "Using proxy: %s:%u\n", g_proxyServer, g_proxyPort);
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_PROXY, g_proxyServer)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_PROXY (%s)!\n", g_proxyServer);
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_PROXYPORT, g_proxyPort)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_PROXYPORT (%u)!\n", g_proxyPort);
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1L)) { // Necessary?
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_HTTPPROXYTUNNEL (1)!\n");
}
#ifdef CURLOPT_SUPPRESS_CONNECT_HEADERS
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L)) { // Necessary?
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_SUPPRESS_CONNECT_HEADERS (1)!\n");
}
#endif
if (g_proxyUsername) {
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, g_proxyUsername)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_PROXYUSERNAME (%s)!\n", g_proxyUsername);
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, g_proxyPassword)) {
logg(LOGG_ERROR, "create_curl_handle: Failed to set CURLOPT_PROXYPASSWORD (%s)!\n", g_proxyPassword);
}
}
}
#if defined(C_DARWIN) || defined(_WIN32)
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, *sslctx_function)) {
logg(LOGG_DEBUG, "create_curl_handle: Failed to set SSL CTX function. Your libcurl may use an SSL backend that does not support CURLOPT_SSL_CTX_FUNCTION.\n");
}
#else
/* Use an alternate CA bundle, if specified by the CURL_CA_BUNDLE environment variable. */
set_tls_ca_bundle(curl);
#endif
/* Authenticate using a client certificate and private key, if specified by the FRESHCLAM_CLIENT_CERT, FRESHCLAM_CLIENT_KEY, and FRESHCLAM_CLIENT_KEY_PASSWD environment variables. */
if (CL_SUCCESS != set_tls_client_certificate(curl)) {
logg(LOGG_DEBUG, "create_curl_handle: Failed to set certificate and private key for client authentication.\n");
goto done;
}
*curlHandle = curl;
status = FC_SUCCESS;
done:
if (FC_SUCCESS != status) {
if (NULL != curl) {
curl_easy_cleanup(curl);
}
}
return status;
}
struct MemoryStruct {
char *buffer;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t real_size = size * nmemb;
struct MemoryStruct *receivedData = (struct MemoryStruct *)userp;
if ((NULL == contents) || (NULL == userp)) {
return 0;
}
char *newBuffer = realloc(receivedData->buffer, receivedData->size + real_size + 1);
if (NULL == newBuffer) {
logg(LOGG_ERROR, "remote_cvdhead - recv callback: Failed to allocate memory CVD header data.\n");
return 0;
}
receivedData->buffer = newBuffer;
memcpy(&(receivedData->buffer[receivedData->size]), contents, real_size);
receivedData->size += real_size;
receivedData->buffer[receivedData->size] = 0;
return real_size;
}
struct FileStruct {
int handle;
size_t size;
};
static size_t WriteFileCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t real_size = size * nmemb;
struct FileStruct *receivedFile = (struct FileStruct *)userp;
size_t bytes_written = 0;
if ((NULL == contents) || (NULL == userp)) {
return 0;
}
bytes_written = write(receivedFile->handle, contents, real_size);
receivedFile->size += bytes_written;
return bytes_written;
}
size_t HeaderCallback(char *buffer,
size_t size,
size_t nitems,
void *userdata)
{
const char *const needle = "cf-ray: ";
size_t totBytes = size * nitems;
if (totBytes >= strlen(needle) + CFRAY_LEN) {
if (0 == strncmp(needle, buffer, strlen(needle))) {
uint8_t *last = (uint8_t *)userdata;
memcpy(last, &(buffer[strlen(needle)]), CFRAY_LEN);
last[CFRAY_LEN] = 0;
}
}
return size * nitems;
}
/**
* @brief Get the cvd header info struct for the newest available database.
*
* The last-modified datetime will be used to set the If-Modified-Since header.
* If the remote CVD isn't newer, we should get an HTTP 304 and return
* FC_UPTODATE instead of FC_SUCCESS, and cvd will be NULL.
*
* @param cvdfile database name including extension.
* @param ifModifiedSince modified time of local database. May be 0 to always get the CVD header.
* @param server server to use to retrieve for database header.
* @param logerr non-zero to upgrade warnings to errors.
* @param[out] cvd CVD header of newest available CVD, if FC_SUCCESS
* @return fc_error_t FC_SUCCESS if CVD header obtained.
* @return fc_error_t FC_UPTODATE if received 304 in response to ifModifiedSince date.
* @return fc_error_t Another error code if failure occurred.
*/
static fc_error_t remote_cvdhead(
const char *cvdfile,
uint32_t ifModifiedSince,
char *server,
int logerr,
struct cl_cvd **cvd)
{
fc_error_t ret;
fc_error_t status = FC_EARG;
int bHttpServer = 0;
char *url = NULL;
size_t urlLen = 0;
char head[CVD_HEADER_SIZE + 1];
struct MemoryStruct receivedData = {0};
unsigned int i;
struct cl_cvd *cvdhead;
CURL *curl = NULL;
CURLcode curl_ret;
char errbuf[CURL_ERROR_SIZE];
struct curl_slist *slist = NULL;
struct xfer_progress prog;
long http_code = 0;
if (NULL == cvd) {
logg(LOGG_ERROR, "remote_cvdhead: Invalid arguments.\n");
goto done;
}
*cvd = NULL;
if (0 == strncasecmp(server, "http", strlen("http"))) {
bHttpServer = 1;
}
/*
* Request CVD header.
*/
urlLen = strlen(server) + strlen("/") + strlen(cvdfile);
url = malloc(urlLen + 1);
snprintf(url, urlLen + 1, "%s/%s", server, cvdfile);
logg(LOGG_INFO, "Trying to retrieve CVD header from %s\n", url);
if (FC_SUCCESS != (ret = create_curl_handle(
bHttpServer, // Set extra HTTP-specific headers.
1, // Allow redirects.
&curl))) { // [out] curl session handle.
logg(LOGG_ERROR, "remote_cvdhead: Failed to create curl handle.\n");
status = ret;
goto done;
}
#ifdef HAVE_UNISTD_H
if (!mprintf_quiet && (mprintf_progress || isatty(fileno(stdout))))
#else
if (!mprintf_quiet)
#endif
{
prog.lastRunTime = 0;
prog.curl = curl;
prog.bComplete = 0;
#if (LIBCURL_VERSION_MAJOR > 7) || ((LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR >= 32))
/* xferinfo was introduced in 7.32.0, no earlier libcurl versions will
compile as they won't have the symbols around.
If built with a newer libcurl, but running with an older libcurl:
curl_easy_setopt() will fail in run-time trying to set the new
callback, making the older callback get used.
New libcurls will prefer the new callback and instead use that one even
if both callbacks are set. */
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferinfo)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set transfer info function!\n");
}
/* pass the struct pointer into the xferinfo function, note that this is
an alias to CURLOPT_PROGRESSDATA */
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &prog)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set transfer info data structure!\n");
}
#else
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, older_progress)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set progress function!\n");
}
/* pass the struct pointer into the progress function */
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set progress data structure!\n");
}
#endif
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to disable progress function!\n");
}
}
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_URL, url)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set CURLOPT_URL for curl session (%s).\n", url);
status = FC_EFAILEDGET;
goto done;
}
if (bHttpServer) {
/*
* For HTTP, set some extra headers.
*/
struct curl_slist *temp = NULL;
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set CURLOPT_HTTPGET for curl session.\n");
}
#ifdef FRESHCLAM_NO_CACHE
if (NULL == (temp = curl_slist_append(slist, "Cache-Control: no-cache"))) { // Necessary?
logg(LOGG_ERROR, "remote_cvdhead: Failed to append \"Cache-Control: no-cache\" header to custom curl header list.\n");
} else {
slist = temp;
}
#endif
if (NULL == (temp = curl_slist_append(slist, "Connection: close"))) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to append \"Connection: close\" header to custom curl header list.\n");
} else {
slist = temp;
}
if (NULL != slist) {
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to add custom header list to curl session.\n");
}
}
}
if (0 != ifModifiedSince) {
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_TIMEVALUE, ifModifiedSince)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set if-Modified-Since time value for curl session.\n");
}
/* If-Modified-Since the above time stamp */
else if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE)) {
logg(LOGG_ERROR, "remote_cvdhead: Failed to set if-Modified-Since time condition for curl session.\n");
}
}
/* Request only the first 512 bytes (CVD_HEADER_SIZE) */
if (CURLE_OK != curl_easy_setopt(curl, CURLOPT_RANGE, "0-511")) {