This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpfs2.c
2072 lines (1872 loc) · 63.1 KB
/
httpfs2.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
/*
* HTTPFS: import a file from a web server to local file system
* the main use is, to mount an iso on a web server with loop device
*
* depends on:
* FUSE: Filesystem in Userspace
* Copyright (C) 2001-2007 Miklos Szeredi <[email protected]>
*
* This program can be distributed under the terms of the GNU GPL.
*
*/
/*
* (c) 2006 hmb marionraven at users.sourceforge.net
*
*/
/*
* Modified to work with fuse 2.7.
* Added keepalive
* The passthru functionality removed to simplify the code.
* (c) 2008-2012,2016 Michal Suchanek <[email protected]>
*
*/
#define FUSE_USE_VERSION 26
#include "config.h"
#include <fuse/fuse_lowlevel.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <stddef.h>
#include <inttypes.h>
#ifdef USE_THREAD
#include <pthread.h>
static pthread_key_t url_key;
pthread_mutex_t cache_lock;
#define FUSE_LOOP fuse_session_loop_mt
#else
#define FUSE_LOOP fuse_session_loop
#endif
#ifdef USE_SSL
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#endif
/*
* ECONNRESET happens with some dodgy servers so may need to handle that.
* Allow for building without ECONNRESET in case it is not defined.
*/
#ifdef ECONNRESET
#define RETRY_ON_RESET
#endif
enum sock_state {
SOCK_CLOSED,
SOCK_OPEN,
SOCK_KEEPALIVE,
};
enum url_flags {
URL_DUP,
URL_SAVE,
URL_DROP,
};
typedef struct url {
int proto;
long timeout;
char * url;
char * host; /*hostname*/
int port;
char * path; /*get path*/
char * name; /*file name*/
#ifdef USE_AUTH
char * auth; /*encoded auth data*/
#endif
#ifdef RETRY_ON_RESET
long retry_reset; /*retry reset connections*/
long resets;
#endif
int sockfd;
enum sock_state sock_type;
int redirected;
int redirect_followed;
int redirect_depth;
#ifdef USE_SSL
long ssl_log_level;
unsigned md5;
unsigned md2;
int ssl_initialized;
int ssl_connected;
gnutls_certificate_credentials_t sc;
gnutls_session_t ss;
const char * cafile;
#endif
char * req_buf;
size_t req_buf_size;
off_t file_size;
time_t last_modified;
char tname[TNAME_LEN + 1];
char xmd5[33];
} struct_url;
// ========== CACHE ============
#define CACHEMAXSIZE 2147483648LL
#define CRCLEN 32
typedef struct range struct_range;
typedef struct range {
off_t start;
size_t size;
off_t cstart;
char md5[33];
// sizef_t csize; // actually, the same as size
struct_range *next;
} struct_range;
struct_range *idxhead = 0, *lastidx = 0;
int fdcache = 0, fdidx = 0; // cache files descriptors are global for all theads
off_t cacheMaxSize = CACHEMAXSIZE; // default cache file size
//size_t cacheMaxSize = 327680; // debug
int init_cache(char *filename) {
off_t s;
struct_range *p = 0;
int i, c, l;
if ((fdcache = open(filename, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) == -1) {
fprintf(stderr, "Can't open cache file: %s\n", filename);
return -1;
}
strcat(filename,".idx");
if ((fdidx = open(filename, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) == -1) {
fprintf(stderr, "Can't open cache index file: %s\n", filename);
close(fdcache);
return -1;
}
s = lseek(fdidx, 0, SEEK_END);
if ( s == 0 ) return 0; // nothing caches yet
lseek(fdidx, 0, SEEK_SET);
read(fdidx, &c, sizeof(c)); // number of entries
read(fdidx, &l, sizeof(l)); // lask block index
for (i = 0; i < c; i++) {
if (idxhead == NULL){
p = idxhead = malloc(sizeof(struct_range));
} else {
p->next = malloc(sizeof(struct_range));
p = p->next;
}
if (i==l) lastidx = p;
read(fdidx, &p->start, sizeof(p->start));
read(fdidx, &p->size, sizeof(p->size));
read(fdidx, &p->cstart, sizeof(p->cstart));
read(fdidx, &p->md5, CRCLEN);
p->md5[32] = 0;
p->next = 0;
}
return 0;
}
ssize_t get_cached(struct_url *url, off_t start, size_t rsize) {
ssize_t bytes = 0;
struct_range *p, *p2;
char md5[2][33];
#ifdef USE_THREAD
pthread_mutex_lock(&cache_lock);
#endif
p = idxhead;
while (p) {
if ( (p->start <= start) && ((p->start + (off_t)p->size-1) >= start+(off_t)rsize-1) ) {
lseek(fdcache, p->cstart, SEEK_SET); // set to start of block to read header
read(fdcache, md5[0], CRCLEN);
md5[0][32] = 0;
lseek(fdcache, p->cstart + (start - p->start)+CRCLEN ,SEEK_SET);
bytes = (ssize_t)read(fdcache, url->req_buf, rsize);
lseek(fdcache, p->cstart + (off_t)p->size + CRCLEN, SEEK_SET); // set to start of block to read header
read(fdcache, md5[1], CRCLEN);
md5[1][32] = 0;
if (strcmp(p->md5, md5[0]) || strcmp(p->md5, md5[1])){ // Everything is bad. cache corrupted. reset cache
bytes = 0;
if (p == idxhead) { // some trick: make range zero; we should keep zero cstart for head;
p->start = 0;
p->size = 0;
memset(p->md5,0, 32);
if (lastidx == idxhead) { // need to revert lastidx to last element
while(lastidx->next) lastidx = lastidx->next;
}
if (p->next == NULL) {
idxhead = lastidx = 0; free(p); // there was only one cached block; can delete it
}
break;
}
p2=idxhead;
while (p2->next) {
if (p2->next == p) {
if (p == lastidx) lastidx = p2; // newest block is
p2->next = p->next;
free(p);
break;
}
p2 = p2->next;
}
break;
}
break;
}
p = p->next;
}
#ifdef USE_THREAD
pthread_mutex_unlock(&cache_lock);
#endif
return bytes;
}
ssize_t update_cache(struct_url *url, off_t start, size_t rsize, char *md5) {
struct_range *p, *t;
int c, last;
#ifdef USE_THREAD
pthread_mutex_lock(&cache_lock);
#endif
if (idxhead == NULL) { // nothing is cached yet
lastidx = idxhead = malloc(sizeof(struct_range));
lastidx->next = 0;
lastidx->cstart = 0;
} else if (lastidx->cstart + (off_t)lastidx->size + CRCLEN*2 > cacheMaxSize) {
lastidx = idxhead; // reached max file size. start from brginning
} else if (lastidx->next == NULL) { // we may add one more block into cache
lastidx->next = malloc(sizeof(struct_range));
lastidx->next->cstart = lastidx->cstart + (off_t)lastidx->size + CRCLEN*2;
lastidx = lastidx->next;
lastidx->next = 0;
} else { // we are in a middle of cache file.
if (lastidx->next->cstart > lastidx->cstart + (off_t)lastidx->size + CRCLEN*2 + (off_t)rsize + CRCLEN*2) { // there is enough space till oldest block (large block was deleted earlier
p = malloc(sizeof(struct_range));
p->next = lastidx->next;
p->cstart = lastidx->cstart + (off_t)lastidx->size + CRCLEN*2;
lastidx->next = p;
lastidx = p;
} else {
lastidx->next->cstart = lastidx->cstart + (off_t)lastidx->size + CRCLEN*2;
lastidx = lastidx->next;
}
}
lastidx->start = start;
lastidx->size = rsize;
strncpy(lastidx->md5, md5, 32);
lastidx->md5[32]=0;
// now we need remove indexes, which blocks will be overwritten
p = lastidx->next;
while (p) {
if (p->cstart < lastidx->cstart + (off_t)lastidx->size + CRCLEN*2) {
t = p;
p = p->next;
lastidx->next = p;
free(t);
} else p=0;
}
lseek(fdcache, lastidx->cstart, SEEK_SET);
write(fdcache, md5, CRCLEN);
write(fdcache, url->req_buf, rsize);
write(fdcache, md5, CRCLEN);
lseek(fdidx, sizeof(c)+sizeof(last), SEEK_SET);
p = idxhead; c = 0, last = 0;;
do {
if (p == lastidx) last=c;
write(fdidx, &p->start, sizeof(p->start));
write(fdidx, &p->size, sizeof(p->size));
write(fdidx, &p->cstart, sizeof(p->cstart));
write(fdidx, &p->md5, CRCLEN);
c++;
} while ( (p = p->next) );
lseek(fdidx, 0, SEEK_SET);
write(fdidx, &c, sizeof(c));
write(fdidx, &last, sizeof(last));
#ifdef USE_THREAD
pthread_mutex_unlock(&cache_lock);
#endif
return 0;
}
// ========== CACHE ============
static struct_url main_url;
static char* argv0;
static off_t get_stat(struct_url*, struct stat * stbuf);
static ssize_t get_data(struct_url*, off_t start, size_t rsize);
static int open_client_socket(struct_url *url);
static int close_client_socket(struct_url *url);
static int close_client_force(struct_url *url);
static struct_url * thread_setup(void);
static void destroy_url_copy(void *);
/* Protocol symbols. */
#define PROTO_HTTP 0
#ifdef USE_SSL
#define PROTO_HTTPS 1
#endif
#ifdef USE_AUTH
#include "md5.h"
#include "base64.h"
#endif
/*
* The FUSE operations originally ripped from the hello_ll sample.
*/
static int httpfs_stat(fuse_ino_t ino, struct stat *stbuf)
{
stbuf->st_ino = ino;
switch (ino) {
case 1:
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
break;
case 2: {
struct_url * url = thread_setup();
fprintf(stderr, "%s: %s: stat()\n", argv0, url->tname); /*DEBUG*/
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
return (int) get_stat(url, stbuf);
}
break;
default:
errno = ENOENT;
return -1;
}
return 0;
}
static void httpfs_getattr(fuse_req_t req, fuse_ino_t ino,
struct fuse_file_info *fi)
{
struct stat stbuf;
(void) fi;
memset(&stbuf, 0, sizeof(stbuf));
if (httpfs_stat(ino, &stbuf) < 0)
assert(errno),fuse_reply_err(req, errno);
else
fuse_reply_attr(req, &stbuf, 1.0);
}
static void httpfs_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
{
struct fuse_entry_param e;
memset(&e, 0, sizeof(e));
e.attr_timeout = 1.0;
e.entry_timeout = 1.0;
if (parent != 1 || strcmp(name, main_url.name) != 0){
e.ino = 0;
} else {
e.ino = 2;
if(httpfs_stat(e.ino, &e.attr) < 0){
assert(errno);
fuse_reply_err(req, errno);
return;
}
}
fuse_reply_entry(req, &e);
}
struct dirbuf {
char *p;
size_t size;
};
static void dirbuf_add(fuse_req_t req, struct dirbuf *b, const char *name,
fuse_ino_t ino)
{
struct stat stbuf;
size_t oldsize = b->size;
b->size += fuse_add_direntry(req, NULL, 0, name, NULL, 0);
b->p = (char *) realloc(b->p, b->size);
memset(&stbuf, 0, sizeof(stbuf));
stbuf.st_ino = ino;
fuse_add_direntry(req, b->p + oldsize, b->size - oldsize, name, &stbuf,
(off_t) b->size);
}
#define min(x, y) ((x) < (y) ? (x) : (y))
static int reply_buf_limited(fuse_req_t req, const char *buf, size_t bufsize,
off_t off, size_t maxsize)
{
assert(off >= 0);
if (off < bufsize)
return fuse_reply_buf(req, buf + off,
min(bufsize - (size_t)off, maxsize));
else
return fuse_reply_buf(req, NULL, 0);
}
static void httpfs_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
off_t off, struct fuse_file_info *fi)
{
(void) fi;
if (ino != 1)
fuse_reply_err(req, ENOTDIR);
else {
struct dirbuf b;
memset(&b, 0, sizeof(b));
dirbuf_add(req, &b, ".", 1);
dirbuf_add(req, &b, "..", 1);
dirbuf_add(req, &b, main_url.name, 2);
reply_buf_limited(req, b.p, b.size, off, size);
free(b.p);
}
}
static void httpfs_open(fuse_req_t req, fuse_ino_t ino,
struct fuse_file_info *fi)
{
if (ino != 2)
fuse_reply_err(req, EISDIR);
else if ((fi->flags & 3) != O_RDONLY)
fuse_reply_err(req, EACCES);
else{
/* direct_io is supposed to allow partial reads. However, setting
* the flag causes read length max at 4096 bytes which leads to
* *many* requests, poor performance, and errors. Some resources
* like TCP ports are recycled too fast for Linux to cope.
*/
//fi->direct_io = 1;
fuse_reply_open(req, fi);
}
}
static void httpfs_read(fuse_req_t req, fuse_ino_t ino, size_t size,
off_t off, struct fuse_file_info *fi)
{
(void) fi;
struct_url * url = thread_setup();
ssize_t res;
assert(ino == 2);
assert(url->file_size >= off);
size=min(size, (size_t)(url->file_size - off));
if(url->file_size == off) {
/* Handling of EOF is not well documented, returning EOF as error
* does not work but this does. */
fuse_reply_buf(req, NULL, 0);
return;
}
/* since we have to return all stuff requested the buffer cannot be
* allocated in advance */
if(url->req_buf
&& ( (url->req_buf_size < size )
|| ( (url->req_buf_size > size )
&& (url->req_buf_size > MAX_REQUEST) ) ) ){
free(url->req_buf);
url->req_buf = 0;
}
if(! url->req_buf){
url->req_buf_size = size;
url->req_buf = malloc(size);
}
if((res = get_data(url, off, size)) < 0){
assert(errno);
fuse_reply_err(req, errno);
}else{
fuse_reply_buf(req, url->req_buf, (size_t)res);
}
}
static struct fuse_lowlevel_ops httpfs_oper = {
.lookup = httpfs_lookup,
.getattr = httpfs_getattr,
.readdir = httpfs_readdir,
.open = httpfs_open,
.read = httpfs_read,
};
/*
* A few utility functions
*/
#ifdef NEED_STRNDUP
static char * strndup(const char * str, size_t n){
if(n > strlen(str)) n = strlen(str);
char * res = malloc(n + 1);
memcpy(res, str, n);
res[n] = 0;
return res;
}
#endif
static int mempref(const char * mem, const char * pref, size_t size, int case_sensitive)
{
/* return true if found */
if (size < strlen(pref)) return 0;
if (case_sensitive)
return ! memcmp(mem, pref, strlen(pref));
else {
int i;
for (i = 0; i < strlen(pref); i++)
/* Unless somebody calling setlocale() behind our back locale should be C. */
/* It is important to not uppercase in languages like Turkish. */
if (tolower(mem[i]) != tolower(pref[i]))
return 0;
return 1;
}
}
#ifdef USE_SSL
static void errno_report(const char * where);
static void ssl_error(ssize_t error, struct_url * url, const char * where);
static void ssl_error_p(ssize_t error, struct_url * url, const char * where, const char * extra);
/* Functions to deal with gnutls_datum_t stolen from gnutls docs.
* The structure does not seem documented otherwise.
*/
static gnutls_datum_t
load_file (const char *file)
{
FILE *f;
gnutls_datum_t loaded_file = { NULL, 0 };
long filelen;
void *ptr;
f = fopen (file, "r");
if (!f)
errno_report(file);
else if (fseek (f, 0, SEEK_END) != 0)
errno_report(file);
else if ((filelen = ftell (f)) < 0)
errno_report(file);
else if (fseek (f, 0, SEEK_SET) != 0)
errno_report(file);
else if (!(ptr = malloc ((size_t) filelen)))
errno_report(file);
else if (fread (ptr, 1, (size_t) filelen, f) < (size_t) filelen)
errno_report(file);
else {
loaded_file.data = ptr;
loaded_file.size = (unsigned int) filelen;
fprintf(stderr, "Loaded '%s' %ld bytes\n", file, filelen);
/* fwrite(ptr, filelen, 1, stderr); */
}
return loaded_file;
}
static void
unload_file (gnutls_datum_t data)
{
free (data.data);
}
/* This function will print some details of the
* given session.
*
* Stolen from the GNUTLS docs.
*/
int
print_ssl_info (gnutls_session_t session)
{
const char *tmp;
gnutls_credentials_type_t cred;
gnutls_kx_algorithm_t kx;
int dhe, ecdh;
dhe = ecdh = 0;
if (!session) {
fprintf(stderr, "No SSL session data.\n");
return 0;
}
/* print the key exchange’s algorithm name
*/
kx = gnutls_kx_get (session);
tmp = gnutls_kx_get_name (kx);
fprintf(stderr, "- Key Exchange: %s\n", tmp);
/* Check the authentication type used and switch
* to the appropriate.
*/
cred = gnutls_auth_get_type (session);
switch (cred)
{
case GNUTLS_CRD_CERTIFICATE:
/* certificate authentication */
/* Check if we have been using ephemeral Diffie-Hellman.
*/
if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
dhe = 1;
#if (GNUTLS_VERSION_MAJOR > 3 )
else if (kx == GNUTLS_KX_ECDHE_RSA || kx == GNUTLS_KX_ECDHE_ECDSA)
ecdh = 1;
#endif
/* cert should have been printed when it was verified */
break;
default:
fprintf(stderr, "Not a x509 sesssion !?!\n");
}
#if (GNUTLS_VERSION_MAJOR > 3 )
/* switch */
if (ecdh != 0)
fprintf(stderr, "- Ephemeral ECDH using curve %s\n",
gnutls_ecc_curve_get_name (gnutls_ecc_curve_get (session)));
else
#endif
if (dhe != 0)
fprintf(stderr, "- Ephemeral DH using prime of %d bits\n",
gnutls_dh_get_prime_bits (session));
/* print the protocol’s name (ie TLS 1.0)
*/
tmp = gnutls_protocol_get_name (gnutls_protocol_get_version (session));
fprintf(stderr, "- Protocol: %s\n", tmp);
/* print the certificate type of the peer.
* ie X.509
*/
tmp =
gnutls_certificate_type_get_name (gnutls_certificate_type_get (session));
fprintf(stderr, "- Certificate Type: %s\n", tmp);
/* print the compression algorithm (if any)
*/
tmp = gnutls_compression_get_name (gnutls_compression_get (session));
fprintf(stderr, "- Compression: %s\n", tmp);
/* print the name of the cipher used.
* ie 3DES.
*/
tmp = gnutls_cipher_get_name (gnutls_cipher_get (session));
fprintf(stderr, "- Cipher: %s\n", tmp);
/* Print the MAC algorithms name.
* ie SHA1
*/
tmp = gnutls_mac_get_name (gnutls_mac_get (session));
fprintf(stderr, "- MAC: %s\n", tmp);
fprintf(stderr, "Note: SSL paramaters may change as new connections are established to the server.\n");
return 0;
}
/* This function will try to verify the peer’s certificate, and
* also check if the hostname matches, and the activation, expiration dates.
*
* Stolen from the gnutls manual.
*/
static int
verify_certificate_callback (gnutls_session_t session)
{
unsigned int status;
const gnutls_datum_t *cert_list;
unsigned int cert_list_size;
int ret;
gnutls_x509_crt_t cert;
gnutls_datum_t data = {0};
struct_url * url = gnutls_session_get_ptr (session);
const char *hostname = url->host;
/* This verification function uses the trusted CAs in the credentials
* structure. So you must have installed one or more CA certificates.
*/
ret = gnutls_certificate_verify_peers2 (session, &status);
if (ret < 0)
{
ssl_error(ret, url, "verify certificate");
return GNUTLS_E_CERTIFICATE_ERROR;
}
if (status & GNUTLS_CERT_INVALID)
fprintf(stderr, "The server certificate is NOT trusted.\n");
if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
fprintf(stderr, "The server certificate uses an insecure algorithm.\n");
if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
fprintf(stderr, "The server certificate hasn’t got a known issuer.\n");
if (status & GNUTLS_CERT_REVOKED)
fprintf(stderr, "The server certificate has been revoked.\n");
if (status & GNUTLS_CERT_EXPIRED)
fprintf(stderr, "The server certificate has expired\n");
if (status & GNUTLS_CERT_NOT_ACTIVATED)
fprintf(stderr, "The server certificate is not yet activated\n");
/* Up to here the process is the same for X.509 certificates and
* OpenPGP keys. From now on X.509 certificates are assumed. This can
* be easily extended to work with openpgp keys as well.
*/
if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
return GNUTLS_E_CERTIFICATE_ERROR;
if (gnutls_x509_crt_init (&cert) < 0)
{
ssl_error(ret, url, "verify certificate");
return GNUTLS_E_CERTIFICATE_ERROR;
}
cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
if (cert_list == NULL)
{
fprintf(stderr, "No server certificate was found!\n");
return GNUTLS_E_CERTIFICATE_ERROR;
}
/* Check the hostname matches the certificate. */
ret = gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER);
if (ret < 0)
{
ssl_error(ret, url, "parsing certificate");
return GNUTLS_E_CERTIFICATE_ERROR;
}
if (!(url->ssl_connected)) if (!gnutls_x509_crt_print (cert, GNUTLS_CRT_PRINT_FULL, &data)) {
fprintf(stderr, "%s", data.data);
gnutls_free(data.data);
}
if (!hostname || !gnutls_x509_crt_check_hostname (cert, hostname))
{
int found = 0;
if (hostname) {
int i;
size_t len = strlen(hostname);
if (*(hostname+len-1) == '.') len--;
if (!(url->ssl_connected)) fprintf(stderr, "Server hostname verification failed. Trying to peek into the cert.\n");
for (i=0;;i++) {
char * dn = NULL;
size_t dn_size = 0;
int dn_ret = 0;
int match=0;
gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, i, 0, dn, &dn_size);
if (dn_size) dn = malloc(dn_size + 1); /* nul not counted */
if (dn)
dn_ret = gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, i, 0, dn, &dn_size);
if (!dn_ret){
if (dn) {
if (*(dn+dn_size-1) == '.') dn_size--;
if (len == dn_size)
match = ! strncmp(dn, hostname, len);
if (match) found = 1;
if (!(url->ssl_connected)) fprintf(stderr, "Cert CN(%i): %s: %c\n", i, dn, match?'*':'X');
}}
else
ssl_error(dn_ret, url, "getting cert subject data");
if (dn) free(dn);
if (dn_ret || !dn)
break;
}
}
if(!found){
fprintf(stderr, "The server certificate’s owner does not match hostname ’%s’\n",
hostname);
return GNUTLS_E_CERTIFICATE_ERROR;
}
}
gnutls_x509_crt_deinit (cert);
/*
* It the status includes GNUTLS_CERT_INVALID whenever
* there is a problem and the other flags are just informative.
*/
if (status & GNUTLS_CERT_INVALID)
return GNUTLS_E_CERTIFICATE_ERROR;
/* notify gnutls to continue handshake normally */
return 0;
}
static void logfunc(int level, const char * str)
{
fputs(str, stderr);
}
static void ssl_error_p(ssize_t error, struct_url * url, const char * where, const char * extra)
{
const char * err_desc;
if((error == GNUTLS_E_FATAL_ALERT_RECEIVED) || (error == GNUTLS_E_WARNING_ALERT_RECEIVED))
err_desc = gnutls_alert_get_name(gnutls_alert_get(url->ss));
else
err_desc = gnutls_strerror((int)error);
fprintf(stderr, "%s: %s: %s: %s%zd %s.\n", argv0, url->tname, where, extra, error, err_desc);
}
static void ssl_error(ssize_t error, struct_url * url, const char * where)
{
ssl_error_p(error, url, where, "");
/* FIXME try to decode errors more meaningfully */
errno = EIO;
}
#endif
static void errno_report(const char * where)
{
struct_url * url = thread_setup();
int e = errno;
fprintf(stderr, "%s: %s: %s: %d %s.\n", argv0, url->tname, where, errno, strerror(errno));
errno = e;
}
static char * url_encode(char * path) {
return strdup(path); /*FIXME encode*/
}
/*
* functions for handling struct_url
*/
static int init_url(struct_url* url)
{
memset(url, 0, sizeof(*url));
url->sock_type = SOCK_CLOSED;
url->timeout = TIMEOUT;
#ifdef RETRY_ON_RESET
url->retry_reset = RESET_RETRIES;
#endif
#ifdef USE_SSL
url->cafile = CERT_STORE;
#endif
return 0;
}
static int free_url(struct_url* url)
{
if(url->sock_type != SOCK_CLOSED)
close_client_force(url);
if(url->host) free(url->host);
url->host = 0;
if(url->path) free(url->path);
url->path = 0;
if(url->name) free(url->name);
url->name = 0;
#ifdef USE_AUTH
if(url->auth) free(url->auth);
url->auth = 0;
#endif
url->port = 0;
url->proto = 0; /* only after socket closed */
url->file_size=0;
url->last_modified=0;
return 0;
}
static void print_url(FILE *f, const struct_url * url)
{
char * protocol = "?!?";
switch(url->proto){
case PROTO_HTTP:
protocol = "http";
break;;
#ifdef USE_SSL
case PROTO_HTTPS:
protocol = "https";
break;;
#endif
}
fprintf(f, "file name: \t%s\n", url->name);
fprintf(f, "host name: \t%s\n", url->host);
fprintf(f, "port number: \t%d\n", url->port);
fprintf(f, "protocol: \t%s\n", protocol);
fprintf(f, "request path: \t%s\n", url->path);
#ifdef USE_AUTH
fprintf(f, "auth data: \t%s\n", url->auth ? "(present)" : "(null)");
#endif
}
static int parse_url(char * _url, struct_url* res, enum url_flags flag)
{
const char * url_orig;
const char * url;
const char * http = "http://";
#ifdef USE_SSL
const char * https = "https://";
#endif /* USE_SSL */
int path_start = '/';
if (!_url)
_url = res->url;
assert(_url);
switch(flag) {
case URL_DUP:
_url = strdup(_url);
case URL_SAVE:
assert (_url != res->url);
if (res->url)
free(res->url);
res->url = _url;
break;
case URL_DROP:
assert (res->url);
break;
}
/* constify so compiler warns about modification */
url_orig = url = _url;
close_client_force(res);
#ifdef USE_SSL
res->ssl_connected = 0;
#endif
if (strncmp(http, url, strlen(http)) == 0) {
url += strlen(http);
res->proto = PROTO_HTTP;
res->port = 80;
#ifdef USE_SSL
} else if (strncmp(https, url, strlen(https)) == 0) {
url += strlen(https);
res->proto = PROTO_HTTPS;
res->port = 443;
#endif /* USE_SSL */
} else {
fprintf(stderr, "Invalid protocol in url: %s\n", url_orig);
return -1;
}
/* determine if path was given */
if(res->path)
free(res->path);
if(strchr(url, path_start))
res->path = url_encode(strchr(url, path_start));
else{
path_start = 0;
res->path = strdup("/");
}
#ifdef USE_AUTH
/* Get user and password */
if(res->auth)
free(res->auth);
if(strchr(url, '@') && (strchr(url, '@') < strchr(url, path_start))){
res->auth = b64_encode((unsigned char *)url, strchr(url, '@') - url);
url = strchr(url, '@') + 1;
}else{
res->auth = 0;
}
#endif /* USE_AUTH */
/* Get port number. */
int host_end = path_start;
if(strchr(url, ':') && (strchr(url, ':') < strchr(url, path_start))){
/* FIXME check that port is a valid numeric value */
res->port = atoi(strchr(url, ':') + 1);
if (! res->port) {
fprintf(stderr, "Invalid port in url: %s\n", url_orig);
return -1;
}
host_end = ':';
}
/* Get the host name. */
if (url == strchr(url, host_end)){ /*no hastname in the url */
fprintf(stderr, "No hostname in url: %s\n", url_orig);
return -1;
}
if(res->host)
free(res->host);
res->host = strndup(url, (size_t)(strchr(url, host_end) - url));
if(flag != URL_DROP) {
/* Get the file name. */
url = strchr(url, path_start);
const char * end = url + strlen(url);
end--;
/* Handle broken urls with multiple slashes. */
while((end > url) && (*end == '/')) end--;
end++;
if(res->name)
free(res->name);
if((path_start == 0) || (end == url)
|| (strncmp(url, "/", (size_t)(end - url)) == 0)){
res->name = strdup(res->host);
}else{
while(strchr(url, '/') && (strchr(url, '/') < end))
url = strchr(url, '/') + 1;
res->name = strndup(url, (size_t)(end - url));