Debian Codegraph @

src/link.c

raw symbols SCIP
1 /*
2 * HTTPDirFS - HTTP Directory Filesystem
3 *
4 * Copyright (C) 2020-2026 Fufu Fang <[email protected]>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * In addition, as a special exception, the copyright holders give
20 * permission to link the code of portions of this program with the OpenSSL
21 * library.
22 */
23
24 /**
25 * \file link.c
26 * \brief Link structure and handling functions implementation
27 */
28
29 #include "link.h"
30
31 #include "cache.h"
32 #include "config.h"
33 #include "log.h"
34 #include "memcache.h"
35 #include "network.h"
36 #include "util.h"
37
38 #include <assert.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <gumbo.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <strings.h>
45 #include <sys/param.h>
46 #include <unistd.h>
47
48 #define STATUS_LEN 64
49
50 /*
51 * ---------------- External variables -----------------------
52 */
53 LinkTable *ROOT_LINK_TBL = NULL;
54 int ROOT_LINK_OFFSET = 0;
55
56 /**
57 * \brief LinkTable generation priority lock
58 * \details This allows LinkTable generation to be run exclusively. This
59 * effectively gives LinkTable generation priority over file transfer.
60 */
61 static pthread_mutex_t link_lock = PTHREAD_MUTEX_INITIALIZER;
62 static void make_link_relative(const char *page_url, char *link_url);
63
64 /**
65 * \brief create a new Link
66 */
67 static Link *Link_new(const char *linkname, LinkType type)
68 {
69 Link *link = CALLOC(1, sizeof(Link));
70
71 strncpy(link->linkname, linkname, NAME_MAX);
72 strncpy(link->linkpath, linkname, NAME_MAX);
73 link->type = type;
74
75 /*
76 * remove the '/' from linkname if it exists
77 */
78 size_t len = strnlen(link->linkname, NAME_MAX);
79 if (len > 0) {
80 char *c = &(link->linkname[len - 1]);
81 if (*c == '/') {
82 *c = '\0';
83 }
84 }
85
86 return link;
87 }
88
89 static int is_same_origin(const char *link_url)
90 {
91 return !CONFIG.external_links || !ROOT_LINK_TBL
92 || !is_cross_origin(ROOT_LINK_TBL->links[0]->f_url, link_url);
93 }
94
95 static CURL *Link_to_curl(Link *link)
96 {
97 CURL *curl = curl_easy_init();
98 if (!curl) {
99 lprintf(fatal, "curl_easy_init() failed!\n");
100 }
101 /*
102 * set up some basic curl stuff
103 */
104 CURLcode ret = curl_easy_setopt(curl, CURLOPT_USERAGENT, CONFIG.user_agent);
105 if (ret) {
106 lprintf(error, "%s\n", curl_easy_strerror(ret));
107 }
108 ret = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
109 if (ret) {
110 lprintf(error, "%s\n", curl_easy_strerror(ret));
111 }
112 /*
113 * for following directories without the '/'
114 */
115 ret = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2);
116 if (ret) {
117 lprintf(error, "%s\n", curl_easy_strerror(ret));
118 }
119 ret = curl_easy_setopt(curl, CURLOPT_URL, link->f_url);
120 if (ret) {
121 lprintf(error, "%s\n", curl_easy_strerror(ret));
122 }
123 ret = curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1);
124 if (ret) {
125 lprintf(error, "%s\n", curl_easy_strerror(ret));
126 }
127 ret = curl_easy_setopt(curl, CURLOPT_PIPEWAIT, 1L);
128 if (ret) {
129 lprintf(error, "%s\n", curl_easy_strerror(ret));
130 }
131 if (curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_3)) {
132 ret = curl_easy_setopt(curl, CURLOPT_HTTP_VERSION,
133 CURL_HTTP_VERSION_2_0);
134 if (ret) {
135 lprintf(error, "%s\n", curl_easy_strerror(ret));
136 }
137 }
138 ret = curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15);
139 if (ret) {
140 lprintf(error, "%s\n", curl_easy_strerror(ret));
141 }
142 ret = curl_easy_setopt(curl, CURLOPT_SHARE, CURL_SHARE);
143 if (ret) {
144 lprintf(error, "%s\n", curl_easy_strerror(ret));
145 }
146 ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback);
147 if (ret) {
148 lprintf(error, "%s\n", curl_easy_strerror(ret));
149 }
150 if (CONFIG.cafile || CONFIG.capath) {
151 /*
152 * Having been given a certificate file or directory, disable any search
153 * paths built into libcurl, so that we exclusively use the explicitly
154 * given certificate(s).
155 */
156 ret = curl_easy_setopt(curl, CURLOPT_CAPATH, CONFIG.capath);
157 if (ret) {
158 lprintf(error, "%s\n", curl_easy_strerror(ret));
159 }
160
161 ret = curl_easy_setopt(curl, CURLOPT_CAINFO, CONFIG.cafile);
162 if (ret) {
163 lprintf(error, "%s\n", curl_easy_strerror(ret));
164 }
165 }
166
167 if (CONFIG.insecure_tls) {
168 ret = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
169 if (ret) {
170 lprintf(error, "%s\n", curl_easy_strerror(ret));
171 }
172 }
173
174 if (CONFIG.log_type & libcurl_debug) {
175 ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
176 if (ret) {
177 lprintf(error, "%s\n", curl_easy_strerror(ret));
178 }
179 }
180
181 if (CONFIG.http_headers) {
182 if (is_same_origin(link->f_url)) {
183 ret = curl_easy_setopt(curl, CURLOPT_HTTPHEADER,
184 CONFIG.http_headers);
185 if (ret) {
186 lprintf(error, "%s\n", curl_easy_strerror(ret));
187 }
188 }
189 }
190
191 if (CONFIG.http_username) {
192 /*
193 * Only apply credentials to the mounted server. When
194 * --external-links is active, cross-origin links must NOT receive
195 * the user's credentials for the primary server.
196 */
197 if (is_same_origin(link->f_url)) {
198 ret = curl_easy_setopt(curl, CURLOPT_USERNAME,
199 CONFIG.http_username);
200 if (ret) {
201 lprintf(error, "%s\n", curl_easy_strerror(ret));
202 }
203 }
204 }
205
206 if (CONFIG.http_password) {
207 if (is_same_origin(link->f_url)) {
208 ret = curl_easy_setopt(curl, CURLOPT_PASSWORD,
209 CONFIG.http_password);
210 if (ret) {
211 lprintf(error, "%s\n", curl_easy_strerror(ret));
212 }
213 }
214 }
215
216 if (CONFIG.proxy) {
217 ret = curl_easy_setopt(curl, CURLOPT_PROXY, CONFIG.proxy);
218 if (ret) {
219 lprintf(error, "%s\n", curl_easy_strerror(ret));
220 }
221 }
222
223 if (CONFIG.proxy_username) {
224 ret = curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME,
225 CONFIG.proxy_username);
226 if (ret) {
227 lprintf(error, "%s\n", curl_easy_strerror(ret));
228 }
229 }
230
231 if (CONFIG.proxy_password) {
232 ret = curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD,
233 CONFIG.proxy_password);
234 if (ret) {
235 lprintf(error, "%s\n", curl_easy_strerror(ret));
236 }
237 }
238
239 if (CONFIG.proxy_cafile || CONFIG.proxy_capath) {
240 /* See CONFIG.cafile above */
241 ret = curl_easy_setopt(curl, CURLOPT_PROXY_CAPATH, CONFIG.proxy_capath);
242 if (ret) {
243 lprintf(error, "%s\n", curl_easy_strerror(ret));
244 }
245
246 ret = curl_easy_setopt(curl, CURLOPT_PROXY_CAINFO, CONFIG.proxy_cafile);
247 if (ret) {
248 lprintf(error, "%s\n", curl_easy_strerror(ret));
249 }
250 }
251
252 return curl;
253 }
254
255 static void Link_req_file_stat(Link *this_link)
256 {
257 CURL *curl = Link_to_curl(this_link);
258 CURLcode ret = curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
259 if (ret) {
260 lprintf(error, "%s\n", curl_easy_strerror(ret));
261 }
262 ret = curl_easy_setopt(curl, CURLOPT_FILETIME, 1L);
263 if (ret) {
264 lprintf(error, "%s\n", curl_easy_strerror(ret));
265 }
266
267 /*
268 * We need to put the variable on the heap, because otherwise the
269 * variable gets popped from the stack as the function returns.
270 *
271 * It gets freed in curl_process_msgs();
272 */
273 TransferStruct *transfer = CALLOC(1, sizeof(TransferStruct));
274
275 transfer->link = this_link;
276 transfer->type = FILESTAT;
277 ret = curl_easy_setopt(curl, CURLOPT_PRIVATE, transfer);
278 if (ret) {
279 lprintf(error, "%s\n", curl_easy_strerror(ret));
280 }
281
282 transfer_nonblocking(curl);
283 }
284
285 /**
286 * \brief Fill in the uninitialised entries in a link table
287 * \details Try and get the stats for each link in the link table. This will get
288 * repeated until the uninitialised entry count drop to zero.
289 */
290 static void LinkTable_uninitialised_fill(LinkTable *linktbl)
291 {
292 if (!linktbl) {
293 return;
294 }
295 int u;
296 char s[STATUS_LEN];
297
298 /*
299 * Start all uninitialized requests once
300 */
301 int total_uninitialized = 0;
302 for (int i = 0; i < linktbl->size; i++) {
303 Link *this_link = linktbl->links[i];
304 if (this_link->type == LINK_UNINITIALISED_FILE
305 || this_link->type == LINK_UNINITIALISED_DIR) {
306 Link_req_file_stat(linktbl->links[i]);
307 total_uninitialized++;
308 }
309 }
310
311 if (total_uninitialized == 0) {
312 return;
313 }
314
315 int n = total_uninitialized;
316 int j = 0;
317 do {
318 u = 0;
319 for (int i = 0; i < linktbl->size; i++) {
320 Link *this_link = linktbl->links[i];
321 if (this_link->type == LINK_UNINITIALISED_FILE
322 || this_link->type == LINK_UNINITIALISED_DIR) {
323 u++;
324 }
325 }
326
327 if (u > 0) {
328 if (CONFIG.log_type & debug) {
329 if (j) {
330 erase_string(stderr, STATUS_LEN, s);
331 }
332 snprintf(s, STATUS_LEN, "%d / %d", n - u, n);
333 fprintf(stderr, "%s", s);
334 j++;
335 }
336
337 /*
338 * Block until some handles are processed
339 */
340 int n_running = curl_multi_perform_once();
341
342 if (n_running == 0) {
343 for (int i = 0; i < linktbl->size; i++) {
344 Link *this_link = linktbl->links[i];
345 if (this_link->type == LINK_UNINITIALISED_FILE
346 || this_link->type == LINK_UNINITIALISED_DIR) {
347 lprintf(error, "Failed to initialize: %s\n",
348 this_link->f_url);
349 this_link->type = LINK_INVALID;
350 }
351 }
352 break;
353 }
354 }
355 } while (u > 0);
356
357 if (CONFIG.log_type & debug) {
358 erase_string(stderr, STATUS_LEN, s);
359 fprintf(stderr, "... Done!\n");
360 }
361 }
362
363 /**
364 * \brief Create the root linktable for single file mode
365 */
366 static LinkTable *single_LinkTable_new(const char *url)
367 {
368 const char *orig_ptr = strrchr(url, '/') + 1;
369 char *ptr = curl_easy_unescape(NULL, orig_ptr, 0, NULL);
370 LinkTable *linktbl = LinkTable_alloc(url);
371 Link *link = Link_new(ptr ? ptr : orig_ptr, LINK_UNINITIALISED_FILE);
372 strncpy(link->f_url, url, PATH_MAX);
373 if (ptr) {
374 curl_free(ptr);
375 }
376 LinkTable_add(linktbl, link);
377 LinkTable_uninitialised_fill(linktbl);
378 LinkTable_print(linktbl);
379 return linktbl;
380 }
381
382 LinkTable *LinkSystem_init(const char *url)
383 {
384 size_t len = strnlen(url, PATH_MAX);
385 /*
386 * --------- Set the length of the root link -----------
387 */
388 /*
389 * This is where the '/' should be
390 */
391 ROOT_LINK_OFFSET
392 = (len > 0 && url[len - 1] == '/') ? (int)len - 1 : (int)len;
393
394 /*
395 * --------------------- Enable cache system --------------------
396 */
397 if (CONFIG.cache_enabled) {
398 if (CONFIG.cache_dir) {
399 CacheSystem_init(CONFIG.cache_dir, 0);
400 } else {
401 CacheSystem_init(url, 1);
402 }
403 }
404
405 /*
406 * ----------- Create the root link table --------------
407 */
408 if (CONFIG.mode == NORMAL) {
409 ROOT_LINK_TBL = LinkTable_new(url);
410 } else if (CONFIG.mode == SINGLE) {
411 ROOT_LINK_TBL = single_LinkTable_new(url);
412 } else if (CONFIG.mode == SONIC) {
413 sonic_config_init(url, CONFIG.sonic_username, CONFIG.sonic_password);
414 if (!CONFIG.sonic_id3) {
415 ROOT_LINK_TBL = sonic_LinkTable_new_index("0");
416 } else {
417 ROOT_LINK_TBL = sonic_LinkTable_new_id3(0, "0");
418 }
419 } else {
420 lprintf(fatal, "Invalid CONFIG.mode\n");
421 }
422 return ROOT_LINK_TBL;
423 }
424
425 void LinkTable_add(LinkTable *linktbl, Link *link)
426 {
427 linktbl->links = (Link **)REALLOC(
428 (void *)linktbl->links, ((size_t)linktbl->size + 1) * sizeof(Link *));
429 linktbl->links[linktbl->size] = link;
430 link->parent_table = linktbl;
431 linktbl->size++;
432 }
433
434 static LinkType linkname_to_LinkType(const char *linkname)
435 {
436 if (linkname[0] == '\0' || linkname[0] == '/') {
437 return LINK_INVALID;
438 }
439
440 /* Now allow all printable characters */
441 for (int i = 0; linkname[i] != '\0'; i++) {
442 char c = linkname[i];
443 if (!isprint(c)) {
444 return LINK_INVALID;
445 }
446 }
447
448 /* The linkname must not contain '/' in the middle. */
449 const char *slash = strchr(linkname, '/');
450 if (slash) {
451 int linkname_len = strnlen(linkname, NAME_MAX) - 1;
452 if (slash - linkname != linkname_len) {
453 return LINK_INVALID;
454 }
455 }
456
457 /* '/' must be at the end to be a valid directory name */
458 if (linkname[strnlen(linkname, NAME_MAX) - 1] == '/') {
459 return LINK_UNINITIALISED_DIR;
460 }
461
462 return LINK_UNINITIALISED_FILE;
463 }
464
465 int link_linknames_equal(const char *str_a, const char *str_b)
466 {
467 if (!str_a || !str_b) {
468 return 0;
469 }
470 size_t len_a = strnlen(str_a, NAME_MAX);
471 size_t len_b = strnlen(str_b, NAME_MAX);
472 size_t max_len = MAX(len_a, len_b);
473 size_t comp_len = MIN(len_a, len_b);
474 int identical = 0;
475
476 /* The length of the strings differ by more than 1 character. */
477 if (max_len - comp_len > 1) {
478 goto end;
479 }
480
481 /* Assuming that the shorter string has a non-zero length */
482 if (comp_len) {
483 /* Assuming that the common parts of the strings are the same */
484 if (!strncmp(str_a, str_b, comp_len)) {
485 /* If the lengths are equal, they are identical */
486 if (len_a == len_b) {
487 identical = 1;
488 } else {
489 /* Otherwise the last character of the longer string should be
490 * '/' */
491 const char *longer_str = len_a > len_b ? str_a : str_b;
492 identical = (longer_str[comp_len] == '/');
493 }
494 }
495 }
496
497 end:
498 return identical;
499 }
500
501 struct LinkHashSet {
502 const char **buckets;
503 int capacity;
504 int size;
505 };
506
507 unsigned int link_hash_str(const char *str)
508 {
509 unsigned int hash = 5381;
510 int c;
511 size_t len = strnlen(str, NAME_MAX);
512
513 /* Strip all trailing slashes */
514 while (len > 0 && str[len - 1] == '/') {
515 len--;
516 }
517
518 for (size_t i = 0; i < len; i++) {
519 c = (unsigned char)str[i];
520 hash = ((hash << 5) + hash) + c;
521 }
522 return hash;
523 }
524
525 LinkHashSet *LinkHashSet_new(int capacity)
526 {
527 if (capacity <= 0) {
528 capacity = 16;
529 } else {
530 int power = 1;
531 while (power < capacity && power < (1 << 30)) {
532 power <<= 1;
533 }
534 capacity = power;
535 }
536 LinkHashSet *set = (LinkHashSet *)CALLOC(1, sizeof(LinkHashSet));
537 set->capacity = capacity;
538 set->buckets = (const char **)CALLOC(capacity, sizeof(const char *));
539 return set;
540 }
541
542 static void LinkHashSet_resize(LinkHashSet *set)
543 {
544 if (set->capacity <= 0) {
545 return;
546 }
547 int old_capacity = set->capacity;
548 const char **old_buckets = set->buckets;
549 if (set->capacity > INT_MAX / 2) {
550 lprintf(fatal, "LinkHashSet capacity overflow\n");
551 }
552 set->capacity *= 2;
553 set->buckets = (const char **)CALLOC(set->capacity, sizeof(const char *));
554
555 for (int i = 0; i < old_capacity; i++) {
556 if (old_buckets[i]) {
557 unsigned int hash = link_hash_str(old_buckets[i]);
558 int bucket = hash & (set->capacity - 1);
559 while (set->buckets[bucket] != NULL) {
560 bucket = (bucket + 1) & (set->capacity - 1);
561 }
562 set->buckets[bucket] = old_buckets[i];
563 }
564 }
565 FREE(old_buckets);
566 }
567
568 int LinkHashSet_add(LinkHashSet *set, const char *linkname)
569 {
570 if (!set || !linkname || set->capacity <= 0) {
571 return 0;
572 }
573 if (set->size >= set->capacity / 2) {
574 LinkHashSet_resize(set);
575 }
576 unsigned int hash = link_hash_str(linkname);
577 int bucket = hash & (set->capacity - 1);
578 while (set->buckets[bucket] != NULL) {
579 if (link_linknames_equal(set->buckets[bucket], linkname)) {
580 return 0;
581 }
582 bucket = (bucket + 1) & (set->capacity - 1);
583 }
584 set->buckets[bucket] = STRDUP(linkname);
585 set->size++;
586 return 1;
587 }
588
589 void LinkHashSet_free(LinkHashSet *set)
590 {
591 if (!set) {
592 return;
593 }
594 for (int i = 0; i < set->capacity; i++) {
595 if (set->buckets[i]) {
596 FREE(set->buckets[i]);
597 }
598 }
599 FREE(set->buckets);
600 FREE(set);
601 }
602
603 /**
604 * \brief Check if a URL is an external (absolute) URL.
605 * \return 1 if the URL starts with http:// or https://, 0 otherwise
606 */
607 int is_external_url(const char *url)
608 {
609 if (!url) {
610 return 0;
611 }
612 return (strncasecmp(url, "http://", 7) == 0
613 || strncasecmp(url, "https://", 8) == 0);
614 }
615
616 static int parse_origin(const char *url, size_t origin_len, char *scheme,
617 size_t scheme_max, char *host, size_t host_max,
618 int *port)
619 {
620 if (!url || origin_len == 0) {
621 return -1;
622 }
623
624 // Find "://" within origin_len
625 const char *scheme_end = NULL;
626 for (size_t i = 0; i + 2 < origin_len; i++) {
627 if (url[i] == ':' && url[i + 1] == '/' && url[i + 2] == '/') {
628 scheme_end = url + i;
629 break;
630 }
631 }
632
633 if (!scheme_end) {
634 return -1; // malformed origin
635 }
636
637 size_t scheme_len = (size_t)(scheme_end - url);
638 if (scheme_len >= scheme_max) {
639 return -1;
640 }
641 strncpy(scheme, url, scheme_len);
642 scheme[scheme_len] = '\0';
643 // Lowercase scheme
644 for (size_t i = 0; i < scheme_len; i++) {
645 if (scheme[i] >= 'A' && scheme[i] <= 'Z') {
646 scheme[i] += 32;
647 }
648 }
649
650 const char *host_start = scheme_end + 3;
651 const char *origin_end = url + origin_len;
652 if (host_start >= origin_end) {
653 return -1;
654 }
655
656 size_t host_part_len = (size_t)(origin_end - host_start);
657
658 // Check for IPv6 bracketed host
659 const char *bracket_close = NULL;
660 if (*host_start == '[') {
661 for (const char *p = host_start; p < origin_end; p++) {
662 if (*p == ']') {
663 bracket_close = p;
664 break;
665 }
666 }
667 }
668
669 const char *port_colon = NULL;
670 if (bracket_close) {
671 // Look for colon after the closing bracket
672 for (const char *p = bracket_close + 1; p < origin_end; p++) {
673 if (*p == ':') {
674 port_colon = p;
675 break;
676 }
677 }
678 } else {
679 // Look for colon in the host part (there should be at most one colon if
680 // no brackets)
681 for (const char *p = host_start; p < origin_end; p++) {
682 if (*p == ':') {
683 port_colon = p;
684 break;
685 }
686 }
687 }
688
689 size_t host_len;
690 if (port_colon) {
691 host_len = (size_t)(port_colon - host_start);
692 // Parse port
693 int p_val = 0;
694 for (const char *p = port_colon + 1; p < origin_end; p++) {
695 if (*p >= '0' && *p <= '9') {
696 p_val = p_val * 10 + (*p - '0');
697 } else {
698 return -1; // invalid character in port
699 }
700 }
701 *port = p_val;
702 } else {
703 host_len = host_part_len;
704 // Default port based on scheme
705 if (strcmp(scheme, "http") == 0) {
706 *port = 80;
707 } else if (strcmp(scheme, "https") == 0) {
708 *port = 443;
709 } else {
710 *port = 0; // unknown scheme default port
711 }
712 }
713
714 if (host_len >= host_max) {
715 return -1;
716 }
717 strncpy(host, host_start, host_len);
718 host[host_len] = '\0';
719 // Lowercase host
720 for (size_t i = 0; i < host_len; i++) {
721 if (host[i] >= 'A' && host[i] <= 'Z') {
722 host[i] += 32;
723 }
724 }
725
726 return 0;
727 }
728
729 /**
730 * \brief Check if link_url has a different origin than page_url.
731 * \details Compares scheme + host + port by finding the path component
732 * (the third '/') of each URL and doing a prefix comparison.
733 * \return 1 if cross-origin, 0 if same origin
734 */
735 int is_cross_origin(const char *page_url, const char *link_url)
736 {
737 if (!page_url || !link_url) {
738 return 1;
739 }
740 /*
741 * Walk past "scheme://host:port" in both URLs and compare the
742 * prefix up to (but not including) the first path slash.
743 * If either URL has fewer than 3 slashes, check if it is a valid
744 * absolute URL to determine the origin length.
745 */
746 int slashes = 0;
747 const char *p = page_url;
748 while (*p && slashes < 3 && *p != '?' && *p != '#') {
749 if (*p == '/') {
750 slashes++;
751 }
752 p++;
753 }
754 size_t page_origin_len;
755 if (slashes < 3) {
756 if (is_external_url(page_url)) {
757 const char *q = strpbrk(page_url, "?#");
758 page_origin_len = q ? (size_t)(q - page_url) : strlen(page_url);
759 } else {
760 return 1; /* malformed page_url */
761 }
762 } else {
763 page_origin_len = (size_t)(p - page_url) - 1;
764 }
765
766 slashes = 0;
767 const char *l = link_url;
768 while (*l && slashes < 3 && *l != '?' && *l != '#') {
769 if (*l == '/') {
770 slashes++;
771 }
772 l++;
773 }
774 size_t link_origin_len;
775 if (slashes < 3) {
776 if (is_external_url(link_url)) {
777 const char *q = strpbrk(link_url, "?#");
778 link_origin_len = q ? (size_t)(q - link_url) : strlen(link_url);
779 } else {
780 return 1; /* malformed link_url */
781 }
782 } else {
783 link_origin_len = (size_t)(l - link_url) - 1;
784 }
785
786 char page_scheme[32];
787 char page_host[PATH_MAX];
788 int page_port = 0;
789 if (parse_origin(page_url, page_origin_len, page_scheme,
790 sizeof(page_scheme), page_host, sizeof(page_host),
791 &page_port)
792 != 0) {
793 return 1;
794 }
795
796 char link_scheme[32];
797 char link_host[PATH_MAX];
798 int link_port = 0;
799 if (parse_origin(link_url, link_origin_len, link_scheme,
800 sizeof(link_scheme), link_host, sizeof(link_host),
801 &link_port)
802 != 0) {
803 return 1;
804 }
805
806 if (strcmp(page_scheme, link_scheme) != 0) {
807 return 1;
808 }
809 if (strcmp(page_host, link_host) != 0) {
810 return 1;
811 }
812 if (page_port != link_port) {
813 return 1;
814 }
815
816 return 0;
817 }
818
819
820 /**
821 * \brief Extract the filename component from an external URL.
822 * \details For "http://example.com/path/file.iso" returns "file.iso".
823 * For "http://example.com/path/dir/" returns "dir".
824 * Query strings ("?") are stripped.
825 * Returns empty string for a root-only URL.
826 * \note The caller must free the returned string with FREE().
827 */
828 char *external_url_to_filename(const char *url)
829 {
830 if (!url) {
831 return STRDUP("");
832 }
833 /*
834 * Skip the scheme://host:port/ prefix — walk past the third slash.
835 */
836 int slashes = 0;
837 const char *p = url;
838 while (*p && slashes < 3) {
839 if (*p == '/') {
840 slashes++;
841 }
842 p++;
843 }
844 /* p now points to the first character of the path (after the
845 * trailing slash of the origin, e.g. "path/file.iso"). */
846
847 if (*p == '\0') {
848 /* Root-only URL — no filename to extract. */
849 return STRDUP("");
850 }
851
852 size_t path_len = strlen(p);
853 char *path_copy = STRNDUP(p, path_len);
854
855 /* Strip query string and fragment identifier if present (must be done
856 * before trailing slash check).
857 */
858 char *q = strpbrk(path_copy, "?#");
859 if (q) {
860 *q = '\0';
861 }
862
863 /* Strip trailing slash if present. */
864 path_len = strlen(path_copy);
865 if (path_len > 0 && path_copy[path_len - 1] == '/') {
866 path_copy[path_len - 1] = '\0';
867 }
868
869 /* Find the last '/' and take everything after it. */
870 char *last_slash = strrchr(path_copy, '/');
871 char *filename;
872 if (last_slash) {
873 filename = STRDUP(last_slash + 1);
874 } else {
875 filename = STRDUP(path_copy);
876 }
877 FREE(path_copy);
878
879 /* URL-decode the filename so it can be used as a filesystem name. */
880 char *decoded = curl_easy_unescape(NULL, filename, 0, NULL);
881 if (!decoded) {
882 return filename;
883 }
884 char *result = STRDUP(decoded);
885 curl_free(decoded);
886 FREE(filename);
887 for (char *ptr = result; *ptr; ptr++) {
888 if (*ptr == '/') {
889 *ptr = '_';
890 }
891 }
892 return result;
893 }
894
895 /**
896 * Shamelessly copied and pasted from:
897 * https://github.com/google/gumbo-parser/blob/master/examples/find_links.cc
898 */
899 static void HTML_to_LinkTable(const char *url, GumboNode *node,
900 LinkTable *linktbl, LinkHashSet *set)
901 {
902 if (node->type != GUMBO_NODE_ELEMENT) {
903 return;
904 }
905 GumboAttribute *href;
906 href = gumbo_get_attribute(&node->v.element.attributes, "href");
907 if (node->v.element.tag == GUMBO_TAG_A && href) {
908 const char *raw_href = href->value;
909
910 if (CONFIG.external_links && is_external_url(raw_href)
911 && is_cross_origin(url, raw_href)) {
912 /*
913 * -------- External (cross-origin) link handling --------
914 * Extract the filename from the external URL and create a
915 * Link with f_url already pointing to the external server.
916 * LinkTable_fill() will skip URL-construction for these.
917 */
918 char *filename = external_url_to_filename(raw_href);
919 if (filename && filename[0] != '\0' && strcmp(filename, ".") != 0
920 && strcmp(filename, "..") != 0) {
921 /* Determine type: directory if URL (ignoring query/fragment)
922 * ends with '/' */
923 const char *qf = strpbrk(raw_href, "?#");
924 size_t href_len
925 = qf ? (size_t)(qf - raw_href) : strlen(raw_href);
926 LinkType type = (href_len > 0 && raw_href[href_len - 1] == '/')
927 ? LINK_UNINITIALISED_DIR
928 : LINK_UNINITIALISED_FILE;
929
930 /* First-wins: skip if a link with this name already exists */
931 if (LinkHashSet_add(set, filename)) {
932 Link *link = Link_new(filename, type);
933 snprintf(link->f_url, sizeof(link->f_url), "%s", raw_href);
934 LinkTable_add(linktbl, link);
935 }
936 }
937 FREE(filename);
938 } else {
939 /*
940 * -------- Same-origin / relative link handling (unchanged)
941 * --------
942 */
943 char *relative_url = STRNDUP(raw_href, PATH_MAX);
944 make_link_relative(url, relative_url);
945
946 /* Truncate at the first slash to support links to subdirectories */
947 char *slash = strchr(relative_url, '/');
948 if (slash && slash != relative_url) {
949 /* Don't truncate full URIs like http://... */
950 if (*(slash - 1) != ':' && slash[1] != '/') {
951 slash[1] = '\0';
952 }
953 }
954
955 /* if it is valid, copy the link onto the heap */
956 LinkType type = linkname_to_LinkType(relative_url);
957
958 /* Check if the new link is a duplicate */
959 if ((type == LINK_UNINITIALISED_DIR)
960 || (type == LINK_UNINITIALISED_FILE)) {
961 if (LinkHashSet_add(set, relative_url)) {
962 LinkTable_add(linktbl, Link_new(relative_url, type));
963 }
964 }
965 FREE(relative_url);
966 }
967 }
968
969 /* Note the recursive call */
970 GumboVector *children = &node->v.element.children;
971 for (size_t i = 0; i < children->length; ++i) {
972 HTML_to_LinkTable(url, (GumboNode *)children->data[i], linktbl, set);
973 }
974 }
975
976 void LinkTable_parse_html(LinkTable *linktbl, const char *url, const char *html)
977 {
978 if (!linktbl || !url || !html) {
979 return;
980 }
981 GumboOutput *output = gumbo_parse(html);
982 if (!output) {
983 return;
984 }
985 LinkHashSet *set = LinkHashSet_new(4096);
986 if (output->root) {
987 HTML_to_LinkTable(url, output->root, linktbl, set);
988 }
989 LinkHashSet_free(set);
990 gumbo_destroy_output(&kGumboDefaultOptions, output);
991 }
992 void Link_set_file_stat(Link *this_link, CURL *curl)
993 {
994 long http_resp;
995 CURLcode ret = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_resp);
996 if (ret) {
997 lprintf(error, "%s\n", curl_easy_strerror(ret));
998 }
999 if (http_resp == HTTP_OK) {
1000 curl_off_t cl = 0;
1001 ret = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl);
1002 if (ret) {
1003 lprintf(error, "%s\n", curl_easy_strerror(ret));
1004 }
1005 ret = curl_easy_getinfo(curl, CURLINFO_FILETIME, &(this_link->time));
1006 if (ret) {
1007 lprintf(error, "%s\n", curl_easy_strerror(ret));
1008 }
1009
1010 if (this_link->type == LINK_UNINITIALISED_FILE) {
1011 if (cl < 0) {
1012 this_link->type = LINK_INVALID;
1013 } else if (cl == 0 && CONFIG.zero_len_is_dir) {
1014 this_link->type = LINK_DIR;
1015 } else {
1016 this_link->type = LINK_FILE;
1017 this_link->content_length = cl;
1018 }
1019 } else if (this_link->type == LINK_UNINITIALISED_DIR) {
1020 this_link->type = LINK_DIR;
1021 }
1022
1023 } else {
1024 lprintf(warning, "%s: HTTP %ld\n", this_link->f_url, http_resp);
1025 /*
1026 * Emit a targeted warning if an external link needs authentication
1027 * that we are not providing.
1028 */
1029 if (CONFIG.external_links && (http_resp == 401 || http_resp == 403)
1030 && ROOT_LINK_TBL
1031 && is_cross_origin(ROOT_LINK_TBL->links[0]->f_url,
1032 this_link->f_url)) {
1033 lprintf(warning,
1034 "External link %s requires authentication (HTTP %ld). "
1035 "Credentials are only applied to the mounted "
1036 "server.\n",
1037 this_link->f_url, http_resp);
1038 }
1039 if (HTTP_temp_failure(http_resp) || CONFIG.invalid_refresh) {
1040 lprintf(warning, ", retrying later.\n");
1041 } else {
1042 this_link->type = LINK_INVALID;
1043 }
1044 }
1045 }
1046
1047 static void LinkTable_fill(LinkTable *linktbl)
1048 {
1049 Link *head_link = linktbl->links[0];
1050 for (int i = 1; i < linktbl->size; i++) {
1051 Link *this_link = linktbl->links[i];
1052
1053 /*
1054 * External links have f_url pre-populated by HTML_to_LinkTable().
1055 * Skip URL construction for them.
1056 */
1057 if (this_link->f_url[0] != '\0') {
1058 continue;
1059 }
1060
1061 /* Some web sites use characters in their href attributes that really
1062 shouldn't be in their href attributes, most commonly spaces. And
1063 some web sites _do_ properly encode their href attributes. So we
1064 first unescape the link path, and then we escape it, so that curl
1065 will definitely be happy with it (e.g., curl won't accept URLs with
1066 spaces in them!). If we only escaped it, and there were already
1067 encoded characters in it, then that would break the link. */
1068 char *unescaped_path
1069 = curl_easy_unescape(NULL, this_link->linkpath, 0, NULL);
1070 char *escaped_path = curl_easy_escape(
1071 NULL, unescaped_path ? unescaped_path : this_link->linkpath, 0);
1072 if (unescaped_path) {
1073 curl_free(unescaped_path);
1074 }
1075
1076 if (escaped_path) {
1077 /* Our code does the wrong thing if there's a trailing slash that's
1078 been replaced with %2F, which curl_easy_escape does, God bless
1079 it, so if it did that then let's put it back. */
1080 int escaped_len = strlen(escaped_path);
1081 if (escaped_len >= 3
1082 && !strcmp(escaped_path + escaped_len - 3, "%2F")) {
1083 escaped_path[escaped_len - 3] = '/';
1084 escaped_path[escaped_len - 2] = '\0';
1085 }
1086 char *url = path_append(head_link->f_url, escaped_path);
1087 curl_free(escaped_path);
1088 strncpy(this_link->f_url, url, PATH_MAX);
1089 FREE(url);
1090 } else {
1091 /* Fallback in case escape fails */
1092 char *url = path_append(head_link->f_url, this_link->linkpath);
1093 strncpy(this_link->f_url, url, PATH_MAX);
1094 FREE(url);
1095 }
1096
1097 char *unescaped_linkname
1098 = curl_easy_unescape(NULL, this_link->linkname, 0, NULL);
1099 if (unescaped_linkname) {
1100 snprintf(this_link->linkname, sizeof(this_link->linkname), "%s",
1101 unescaped_linkname);
1102 curl_free(unescaped_linkname);
1103 }
1104 }
1105 LinkTable_uninitialised_fill(linktbl);
1106 }
1107
1108 void LinkTable_ref(LinkTable *tbl)
1109 {
1110 if (!tbl) {
1111 return;
1112 }
1113 PTHREAD_MUTEX_LOCK(&link_lock);
1114 tbl->refcount++;
1115 tbl->orphaned = 0;
1116 PTHREAD_MUTEX_UNLOCK(&link_lock);
1117 }
1118
1119 void LinkTable_mark_orphaned(LinkTable *tbl)
1120 {
1121 if (!tbl) {
1122 return;
1123 }
1124 PTHREAD_MUTEX_LOCK(&link_lock);
1125 tbl->orphaned = 1;
1126 PTHREAD_MUTEX_UNLOCK(&link_lock);
1127 }
1128
1129 void LinkTable_unref(LinkTable *tbl)
1130 {
1131 if (!tbl) {
1132 return;
1133 }
1134 PTHREAD_MUTEX_LOCK(&link_lock);
1135 tbl->refcount--;
1136 if (tbl->refcount == 0 && tbl->orphaned) {
1137 LinkTable *parent = tbl->parent_tbl;
1138 Link *parent_link = tbl->parent_link;
1139 if (parent_link) {
1140 parent_link->next_table = NULL;
1141 }
1142 PTHREAD_MUTEX_UNLOCK(&link_lock);
1143
1144 LinkTable_free(tbl);
1145
1146 if (parent) {
1147 LinkTable_unref(parent);
1148 }
1149 return;
1150 }
1151 PTHREAD_MUTEX_UNLOCK(&link_lock);
1152 }
1153
1154 void LinkTable_free(LinkTable *linktbl)
1155 {
1156 if (linktbl) {
1157 for (int i = 0; i < linktbl->size; i++) {
1158 Link *entry = linktbl->links ? linktbl->links[i] : NULL;
1159 if (!entry) {
1160 continue;
1161 }
1162 LinkTable_free(entry->next_table);
1163 FREE(entry);
1164 }
1165 FREE(linktbl->links);
1166 FREE(linktbl);
1167 }
1168 }
1169
1170 void LinkTable_print(LinkTable *linktbl)
1171 {
1172 if (CONFIG.log_type & info) {
1173 int j = 0;
1174 lprintf(info, "--------------------------------------------\n");
1175 lprintf(info, " LinkTable %p for %s\n", (void *)linktbl,
1176 linktbl->links[0]->f_url);
1177 lprintf(info, "--------------------------------------------\n");
1178 for (int i = 0; i < linktbl->size; i++) {
1179 Link *this_link = linktbl->links[i];
1180 lprintf(info, "%d %c %lu %s %s\n", i, this_link->type,
1181 this_link->content_length, this_link->linkname,
1182 this_link->f_url);
1183 if ((this_link->type != LINK_FILE) && (this_link->type != LINK_DIR)
1184 && (this_link->type != LINK_HEAD)) {
1185 j++;
1186 }
1187 }
1188 lprintf(info, "--------------------------------------------\n");
1189 lprintf(info, " Invalid link count: %d\n", j);
1190 lprintf(info, "--------------------------------------------\n");
1191 }
1192 }
1193
1194 LinkTable *LinkTable_alloc(const char *url)
1195 {
1196 LinkTable *linktbl = CALLOC(1, sizeof(LinkTable));
1197 linktbl->size = 0;
1198 linktbl->index_time = 0;
1199 linktbl->links = NULL;
1200
1201
1202 /*
1203 * populate the base URL
1204 */
1205 Link *head_link = Link_new("/", LINK_HEAD);
1206 LinkTable_add(linktbl, head_link);
1207 strncpy(head_link->f_url, url, PATH_MAX);
1208 assert(linktbl->size == 1);
1209 return linktbl;
1210 }
1211
1212 char *url_to_cache_path(const char *url)
1213 {
1214 if (!url) {
1215 return NULL;
1216 }
1217 char *unescaped_path;
1218 /*
1219 * When --external-links is active a directory link from an external
1220 * server may be navigated. Its URL won't share the root server's
1221 * origin, so applying ROOT_LINK_OFFSET would produce garbage. Detect
1222 * this case by checking whether url is cross-origin from root.
1223 */
1224 if (ROOT_LINK_TBL && is_cross_origin(ROOT_LINK_TBL->links[0]->f_url, url)) {
1225 /* External URL: use the full URL as the cache key path. */
1226 char *temp = curl_easy_unescape(NULL, url, 0, NULL);
1227 unescaped_path = temp ? STRDUP(temp) : STRDUP(url);
1228 if (temp) {
1229 curl_free(temp);
1230 }
1231 /* Sanitize unescaped_path to prevent path traversal via ".." */
1232 char *p = unescaped_path;
1233 while ((p = strstr(p, ".."))) {
1234 p[0] = '_';
1235 p[1] = '_';
1236 p += 2;
1237 }
1238 /* Sanitize unescaped_path to prevent path traversal and invalid
1239 * directory structures */
1240 for (char *sp = unescaped_path; *sp; sp++) {
1241 if (*sp == '/' || *sp == ':') {
1242 *sp = '_';
1243 }
1244 }
1245 } else {
1246 size_t url_len = strlen(url);
1247 const char *offset_url = (url_len >= (size_t)ROOT_LINK_OFFSET)
1248 ? url + ROOT_LINK_OFFSET
1249 : url;
1250 char *temp = curl_easy_unescape(NULL, offset_url, 0, NULL);
1251 unescaped_path = temp ? STRDUP(temp) : STRDUP(offset_url);
1252 if (temp) {
1253 curl_free(temp);
1254 }
1255 }
1256 return unescaped_path;
1257 }
1258
1259 LinkTable *LinkTable_new(const char *url)
1260 {
1261 char *unescaped_path = url_to_cache_path(url);
1262 LinkTable *linktbl = NULL;
1263
1264 /*
1265 * Attempt to load the LinkTable from the disk.
1266 */
1267 if (CACHE_SYSTEM_INIT) {
1268 CacheDir_create(unescaped_path);
1269 LinkTable *disk_linktbl;
1270
1271 disk_linktbl = LinkTable_disk_open(unescaped_path);
1272 if (disk_linktbl) {
1273 /*
1274 * Check if the LinkTable needs to be refreshed based on timeout.
1275 */
1276 time_t time_now = time(NULL);
1277 if (time_now - disk_linktbl->index_time > CONFIG.refresh_timeout) {
1278 lprintf(info, "time_now: %ld, index_time: %ld\n",
1279 (long)time_now, (long)disk_linktbl->index_time);
1280 lprintf(info, "diff: %ld, limit: %d\n",
1281 (long)(time_now - disk_linktbl->index_time),
1282 CONFIG.refresh_timeout);
1283 LinkTable_free(disk_linktbl);
1284 } else {
1285 linktbl = disk_linktbl;
1286 }
1287 }
1288 }
1289
1290 /*
1291 * Download a new LinkTable because we didn't manage to load it from the
1292 * disk
1293 */
1294 if (!linktbl) {
1295 linktbl = LinkTable_alloc(url);
1296 linktbl->index_time = time(NULL);
1297
1298 /*
1299 * start downloading the base URL
1300 */
1301 TransferStruct ts = Link_download_full(linktbl->links[0]);
1302 if (ts.curr_size == 0) {
1303 LinkTable_free(linktbl);
1304 return NULL;
1305 }
1306
1307 /*
1308 * Otherwise parsed the received data
1309 */
1310 LinkTable_parse_html(linktbl, url, ts.data);
1311 FREE(ts.data);
1312
1313
1314 LinkTable_fill(linktbl);
1315
1316 /*
1317 * Save the link table
1318 */
1319 if (CACHE_SYSTEM_INIT && LinkTable_disk_save(linktbl, unescaped_path)) {
1320 lprintf(error, "Failed to save the LinkTable!\n");
1321 }
1322 }
1323
1324 FREE(unescaped_path);
1325 LinkTable_print(linktbl);
1326 return linktbl;
1327 }
1328
1329 static void LinkTable_disk_delete(const char *dirn)
1330 {
1331 char *metadirn = path_append(META_DIR, dirn);
1332 char *path = path_append(metadirn, ".LinkTable");
1333 if (unlink(path)) {
1334 lprintf(error, "unlink(%s): %s\n", path, strerror(errno));
1335 }
1336 FREE(path);
1337 FREE(metadirn);
1338 }
1339
1340 /* This is necessary to get the compiler on some platforms to stop
1341 complaining about the fact that we're not using the return value of
1342 fread, when we know we aren't and that's fine. */
1343 static inline void ignore_value(int i)
1344 {
1345 (void)i;
1346 }
1347
1348 int LinkTable_disk_save(LinkTable *linktbl, const char *dirn)
1349 {
1350 char *metadirn = path_append(META_DIR, dirn);
1351 char *path = path_append(metadirn, ".LinkTable");
1352 FILE *fp = fopen(path, "w");
1353 FREE(metadirn);
1354
1355 if (!fp) {
1356 lprintf(error, "fopen(%s): %s\n", path, strerror(errno));
1357 FREE(path);
1358 return -1;
1359 }
1360
1361 if (fwrite(&linktbl->size, sizeof(int), 1, fp) != 1
1362 || fwrite(&linktbl->index_time, sizeof(time_t), 1, fp) != 1) {
1363 lprintf(error, "Failed to save the header of %s!\n", path);
1364 }
1365 FREE(path);
1366 for (int i = 0; i < linktbl->size; i++) {
1367 ignore_value(
1368 fwrite(linktbl->links[i]->linkname, sizeof(char), NAME_MAX, fp));
1369 ignore_value(
1370 fwrite(linktbl->links[i]->f_url, sizeof(char), PATH_MAX, fp));
1371 ignore_value(fwrite(&linktbl->links[i]->type, sizeof(LinkType), 1, fp));
1372 ignore_value(
1373 fwrite(&linktbl->links[i]->content_length, sizeof(size_t), 1, fp));
1374 ignore_value(fwrite(&linktbl->links[i]->time, sizeof(long), 1, fp));
1375 }
1376
1377 int res = 0;
1378
1379 if (ferror(fp)) {
1380 lprintf(error, "encountered ferror!\n");
1381 res = -1;
1382 }
1383
1384 if (fclose(fp)) {
1385 lprintf(error, "cannot close the file pointer, %s\n", strerror(errno));
1386 res = -1;
1387 }
1388
1389 return res;
1390 }
1391
1392 LinkTable *LinkTable_disk_open(const char *dirn)
1393 {
1394 char *metadirn = path_append(META_DIR, dirn);
1395 char *path = path_append(metadirn, ".LinkTable");
1396 FILE *fp = fopen(path, "r");
1397 FREE(metadirn);
1398
1399 if (!fp) {
1400 FREE(path);
1401 return NULL;
1402 }
1403
1404 LinkTable *linktbl = CALLOC(1, sizeof(LinkTable));
1405 int sz = 0;
1406 if (fread(&sz, sizeof(int), 1, fp) != 1
1407 || fread(&linktbl->index_time, sizeof(time_t), 1, fp) != 1) {
1408 lprintf(error, "Failed to read the header of %s!\n", path);
1409 fclose(fp);
1410 LinkTable_free(linktbl);
1411 LinkTable_disk_delete(dirn);
1412 FREE(path);
1413 return NULL;
1414 }
1415
1416 long entry_size = (long)(NAME_MAX + PATH_MAX + sizeof(LinkType)
1417 + sizeof(size_t) + sizeof(long));
1418 if (fseek(fp, 0, SEEK_END) != 0) {
1419 lprintf(error, "Failed to seek %s!\n", path);
1420 fclose(fp);
1421 LinkTable_free(linktbl);
1422 LinkTable_disk_delete(dirn);
1423 FREE(path);
1424 return NULL;
1425 }
1426 long file_size = ftell(fp);
1427 if (file_size < 0
1428 || fseek(fp, (long)(sizeof(int) + sizeof(time_t)), SEEK_SET) != 0) {
1429 lprintf(error, "Failed to inspect %s!\n", path);
1430 fclose(fp);
1431 LinkTable_free(linktbl);
1432 LinkTable_disk_delete(dirn);
1433 FREE(path);
1434 return NULL;
1435 }
1436
1437 long max_entries
1438 = (file_size - (long)(sizeof(int) + sizeof(time_t))) / entry_size;
1439
1440 if (sz < 1 || max_entries < sz) {
1441 lprintf(error, "Invalid link table size: %d in %s!\n", sz, path);
1442 fclose(fp);
1443 LinkTable_free(linktbl);
1444 LinkTable_disk_delete(dirn);
1445 FREE(path);
1446 return NULL;
1447 }
1448
1449 linktbl->size = sz;
1450 linktbl->links
1451 = (Link **)CALLOC( // NOLINT(clang-analyzer-optin.taint.TaintedAlloc)
1452 sz, sizeof(Link *));
1453
1454 for (int i = 0; i < sz; i++) {
1455 linktbl->links[i] = CALLOC(1, sizeof(Link));
1456 linktbl->links[i]->parent_table = linktbl;
1457 if (fread(linktbl->links[i]->linkname, sizeof(char), NAME_MAX, fp)
1458 != NAME_MAX
1459 || fread(linktbl->links[i]->f_url, sizeof(char), PATH_MAX, fp)
1460 != PATH_MAX
1461 || fread(&linktbl->links[i]->type, sizeof(LinkType), 1, fp) != 1
1462 || fread(&linktbl->links[i]->content_length, sizeof(size_t), 1, fp)
1463 != 1
1464 || fread(&linktbl->links[i]->time, sizeof(long), 1, fp) != 1) {
1465 lprintf(error, "Corrupted LinkTable at index %d!\n", i);
1466 fclose(fp);
1467 LinkTable_free(linktbl);
1468 LinkTable_disk_delete(dirn);
1469 FREE(path);
1470 return NULL;
1471 }
1472 }
1473 if (fclose(fp)) {
1474 lprintf(error, "cannot close the file pointer, %s\n", strerror(errno));
1475 }
1476
1477 FREE(path);
1478 return linktbl;
1479 }
1480
1481 LinkTable *path_to_LinkTable(const char *path)
1482 {
1483 Link *link = NULL;
1484 Link *tmp_link = NULL;
1485 LinkTable *next_table = NULL;
1486
1487 if (!strcmp(path, "/")) {
1488 next_table = ROOT_LINK_TBL;
1489 LinkTable_ref(next_table);
1490 return next_table;
1491 } else {
1492 link = path_to_Link(path);
1493 if (!link) {
1494 return NULL;
1495 }
1496 tmp_link = link;
1497
1498 PTHREAD_MUTEX_LOCK(&link_lock);
1499 next_table = link->next_table;
1500 if (next_table) {
1501 next_table->refcount++;
1502 next_table->orphaned = 0;
1503 }
1504 PTHREAD_MUTEX_UNLOCK(&link_lock);
1505 }
1506
1507 if (!next_table) {
1508 LinkTable *new_table = NULL;
1509 if (CONFIG.mode == NORMAL) {
1510 new_table = LinkTable_new(tmp_link->f_url);
1511 } else if (CONFIG.mode == SINGLE) {
1512 new_table = single_LinkTable_new(tmp_link->f_url);
1513 } else if (CONFIG.mode == SONIC) {
1514 if (!CONFIG.sonic_id3) {
1515 new_table = sonic_LinkTable_new_index(tmp_link->sonic.id);
1516 } else {
1517 new_table = sonic_LinkTable_new_id3(tmp_link->sonic.depth,
1518 tmp_link->sonic.id);
1519 }
1520 } else {
1521 lprintf(fatal, "Invalid CONFIG.mode: %d\n", CONFIG.mode);
1522 }
1523
1524 if (!new_table) {
1525 if (link) {
1526 LinkTable_unref(link->parent_table);
1527 }
1528 return NULL;
1529 }
1530
1531 PTHREAD_MUTEX_LOCK(&link_lock);
1532 if (!link->next_table) {
1533 link->next_table = new_table;
1534 new_table->parent_tbl = link->parent_table;
1535 new_table->parent_link = link;
1536 if (new_table->parent_tbl) {
1537 new_table->parent_tbl->refcount++;
1538 }
1539 new_table->refcount++;
1540 new_table->orphaned = 0;
1541 next_table = new_table;
1542 } else {
1543 LinkTable_free(new_table);
1544 next_table = link->next_table;
1545 next_table->refcount++;
1546 next_table->orphaned = 0;
1547 }
1548 PTHREAD_MUTEX_UNLOCK(&link_lock);
1549
1550 if (CONFIG.invalid_refresh) {
1551 LinkTable_uninitialised_fill(next_table);
1552 }
1553 }
1554
1555 if (link) {
1556 LinkTable_unref(link->parent_table);
1557 }
1558
1559 return next_table;
1560 }
1561
1562 static Link *path_to_Link_recursive(char *path, LinkTable *linktbl)
1563 {
1564 if (!linktbl || !path || path[0] == '\0') {
1565 return NULL;
1566 }
1567
1568 /*
1569 * skip the leading '/' if it exists
1570 */
1571 if (*path == '/') {
1572 path++;
1573 }
1574
1575 /*
1576 * remove the last '/' if it exists
1577 */
1578 size_t path_len = strnlen(path, PATH_MAX);
1579 if (path_len > 0) {
1580 char *slash = &(path[path_len - 1]);
1581 if (*slash == '/') {
1582 *slash = '\0';
1583 }
1584 }
1585
1586 char *slash = strchr(path, '/');
1587 if (slash == NULL) {
1588 /*
1589 * We cannot find another '/', we have reached the last level
1590 */
1591 for (int i = 1; i < linktbl->size; i++) {
1592 if (!strncmp(path, linktbl->links[i]->linkname, NAME_MAX)) {
1593 /*
1594 * We found our link
1595 */
1596 return linktbl->links[i];
1597 }
1598 }
1599 } else {
1600 /*
1601 * We can still find '/', time to consume the path and traverse
1602 * the tree structure
1603 */
1604
1605 /*
1606 * add termination mark to the current string,
1607 * effective create two substrings
1608 */
1609 *slash = '\0';
1610 /*
1611 * move the pointer past the '/'
1612 */
1613 char *next_path = slash + 1;
1614 for (int i = 1; i < linktbl->size; i++) {
1615 if (!strncmp(path, linktbl->links[i]->linkname, NAME_MAX)) {
1616 /*
1617 * The next sub-directory exists
1618 */
1619 LinkTable *next_table = linktbl->links[i]->next_table;
1620 if (!next_table) {
1621 linktbl->refcount++;
1622 PTHREAD_MUTEX_UNLOCK(&link_lock);
1623 LinkTable *new_table = NULL;
1624 if (CONFIG.mode == NORMAL) {
1625 new_table = LinkTable_new(linktbl->links[i]->f_url);
1626 } else if (CONFIG.mode == SONIC) {
1627 if (!CONFIG.sonic_id3) {
1628 new_table = sonic_LinkTable_new_index(
1629 linktbl->links[i]->sonic.id);
1630 } else {
1631 new_table = sonic_LinkTable_new_id3(
1632 linktbl->links[i]->sonic.depth,
1633 linktbl->links[i]->sonic.id);
1634 }
1635 } else {
1636 lprintf(fatal, "Invalid CONFIG.mode\n");
1637 }
1638
1639 if (!new_table) {
1640 PTHREAD_MUTEX_LOCK(&link_lock);
1641 linktbl->refcount--;
1642 if (linktbl->refcount == 0 && linktbl->orphaned) {
1643 LinkTable *parent = linktbl->parent_tbl;
1644 Link *parent_link = linktbl->parent_link;
1645 if (parent_link) {
1646 parent_link->next_table = NULL;
1647 }
1648 PTHREAD_MUTEX_UNLOCK(&link_lock);
1649 LinkTable_free(linktbl);
1650 if (parent) {
1651 LinkTable_unref(parent);
1652 }
1653 PTHREAD_MUTEX_LOCK(&link_lock);
1654 }
1655 return NULL;
1656 }
1657
1658 PTHREAD_MUTEX_LOCK(&link_lock);
1659 if (!linktbl->links[i]->next_table) {
1660 linktbl->links[i]->next_table = new_table;
1661 new_table->parent_tbl = linktbl;
1662 new_table->parent_link = linktbl->links[i];
1663 linktbl->refcount++;
1664 next_table = new_table;
1665 } else {
1666 LinkTable_free(new_table);
1667 next_table = linktbl->links[i]->next_table;
1668 }
1669 linktbl->refcount--;
1670 }
1671 return path_to_Link_recursive(next_path, next_table);
1672 }
1673 }
1674 }
1675 return NULL;
1676 }
1677
1678 Link *path_to_Link(const char *path)
1679 {
1680 lprintf(link_lock_debug, "thread %lx: locking link_lock;\n",
1681 (unsigned long)pthread_self());
1682
1683 PTHREAD_MUTEX_LOCK(&link_lock);
1684 char *new_path = STRNDUP(path, PATH_MAX);
1685 if (!new_path) {
1686 lprintf(fatal, "cannot allocate memory\n");
1687 }
1688 Link *link = path_to_Link_recursive(new_path, ROOT_LINK_TBL);
1689 FREE(new_path);
1690
1691 if (link && link->parent_table) {
1692 link->parent_table->refcount++;
1693 }
1694
1695 lprintf(link_lock_debug, "thread %lx: unlocking link_lock;\n",
1696 (unsigned long)pthread_self());
1697 PTHREAD_MUTEX_UNLOCK(&link_lock);
1698 return link;
1699 }
1700
1701 TransferStruct Link_download_full(Link *link)
1702 {
1703 char *url = link->f_url;
1704 CURL *curl = Link_to_curl(link);
1705
1706 TransferStruct ts = {0};
1707 ts.type = DATA;
1708 ts.transferring = 1;
1709
1710 CURLcode ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&ts);
1711 if (ret) {
1712 lprintf(error, "%s\n", curl_easy_strerror(ret));
1713 }
1714 ret = curl_easy_setopt(curl, CURLOPT_PRIVATE, (void *)&ts);
1715 if (ret) {
1716 lprintf(error, "%s\n", curl_easy_strerror(ret));
1717 }
1718
1719 /*
1720 * If we get temporary HTTP failure, wait for 5 seconds before retry
1721 */
1722 long http_resp = 0;
1723 do {
1724 /*
1725 * Reset the transfer struct for each attempt to avoid accumulating
1726 * data from failed/partial attempts.
1727 */
1728 FREE(ts.data);
1729 ts.curr_size = 0;
1730 ts.transferring = 1;
1731
1732 transfer_blocking(curl);
1733 ret = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_resp);
1734 if (ret) {
1735 lprintf(error, "%s\n", curl_easy_strerror(ret));
1736 }
1737 if (HTTP_temp_failure(http_resp)) {
1738 lprintf(warning, "URL: %s, HTTP %ld, retrying later.\n", url,
1739 http_resp);
1740 sleep(CONFIG.http_wait_sec);
1741 } else if (http_resp != HTTP_OK) {
1742 lprintf(warning, "cannot retrieve URL: %s, HTTP %ld\n", url,
1743 http_resp);
1744 ts.curr_size = 0;
1745 free(ts.data); /* not FREE(); can be NULL on error path! */
1746 curl_easy_cleanup(curl);
1747 return ts;
1748 }
1749 } while (HTTP_temp_failure(http_resp));
1750
1751 ret = curl_easy_getinfo(curl, CURLINFO_FILETIME, &(link->time));
1752 if (ret) {
1753 lprintf(error, "%s\n", curl_easy_strerror(ret));
1754 }
1755 curl_easy_cleanup(curl);
1756 return ts;
1757 }
1758
1759 static CURL *Link_download_curl_setup(Link *link, size_t req_size, off_t offset,
1760 TransferStruct *header,
1761 TransferStruct *ts)
1762 {
1763 if (!link) {
1764 lprintf(fatal, "Invalid supplied\n");
1765 }
1766
1767 size_t start = offset;
1768 size_t end = start + req_size - 1;
1769
1770 char range_str[64];
1771 snprintf(range_str, sizeof(range_str), "%lu-%lu", start, end);
1772 CURL *curl = Link_to_curl(link);
1773 CURLcode ret = curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void *)header);
1774 if (ret) {
1775 lprintf(error, "%s\n", curl_easy_strerror(ret));
1776 }
1777 ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)ts);
1778 if (ret) {
1779 lprintf(error, "%s\n", curl_easy_strerror(ret));
1780 }
1781 ret = curl_easy_setopt(curl, CURLOPT_PRIVATE, (void *)ts);
1782 if (ret) {
1783 lprintf(error, "%s\n", curl_easy_strerror(ret));
1784 }
1785 ret = curl_easy_setopt(curl, CURLOPT_RANGE, range_str);
1786 if (ret) {
1787 lprintf(error, "%s\n", curl_easy_strerror(ret));
1788 }
1789
1790 return curl;
1791 }
1792
1793 static curl_off_t Link_download_cleanup(CURL *curl, TransferStruct *header)
1794 {
1795 /*
1796 * Check for range seek support
1797 */
1798 if (!CONFIG.no_range_check) {
1799 if (!strcasestr((header->data), "Accept-Ranges: bytes")
1800 && !strcasestr((header->data), "Content-Range: bytes")) {
1801 fprintf(stderr, "This web server does not support HTTP range \
1802 requests. If you do not believe that is the case, and if you plan to file a \
1803 bug report, please include the following HTTP header information:\n%s\n",
1804 header->data);
1805 exit(EXIT_FAILURE);
1806 }
1807 }
1808
1809 FREE(header->data);
1810
1811 long http_resp;
1812 CURLcode ret = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_resp);
1813 if (ret) {
1814 lprintf(error, "%s\n", curl_easy_strerror(ret));
1815 }
1816 curl_off_t recv = -1;
1817 if ((http_resp == HTTP_OK) || (http_resp == HTTP_PARTIAL_CONTENT)
1818 || (http_resp == HTTP_RANGE_NOT_SATISFIABLE)) {
1819 ret = curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD_T, &recv);
1820 if (ret) {
1821 lprintf(error, "%s\n", curl_easy_strerror(ret));
1822 }
1823 } else {
1824 char *url;
1825 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
1826 lprintf(warning, "Could not download %s, HTTP %ld\n", url, http_resp);
1827 if (HTTP_temp_failure(http_resp)) {
1828 recv = -EAGAIN;
1829 } else {
1830 recv = -ENOENT;
1831 }
1832 }
1833
1834 curl_easy_cleanup(curl);
1835
1836 return recv;
1837 }
1838
1839 static void Link_download_finish_transfer(Cache *cf, off_t offset,
1840 TransferStruct *ts)
1841 {
1842 if (!cf) {
1843 ts->transferring = 0;
1844 return;
1845 }
1846
1847 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1848 ts->transferring = 0;
1849 ActiveDownload *ad = ActiveDownload_find(cf, offset);
1850 if (ad && ad->ts == ts) {
1851 ad->ts = NULL;
1852 }
1853 if (ts->ad_ptr) {
1854 ActiveDownload_unref(ts->ad_ptr);
1855 ts->ad_ptr = NULL;
1856 }
1857 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1858 }
1859
1860 long Link_download(Link *link, char *output_buf, size_t req_size, off_t offset,
1861 Cache *cf)
1862 {
1863 if (req_size == 0 || link->content_length == 0 || offset < 0
1864 || (size_t)offset >= link->content_length) {
1865 return 0;
1866 }
1867
1868 TransferStruct ts = {0};
1869 TransferStruct header = {0};
1870 curl_off_t recv_sz;
1871
1872 size_t remaining = link->content_length - (size_t)offset;
1873 if (req_size > remaining) {
1874 lprintf(info, "requested size larger than remaining size, req_size: \
1875 %zu, remaining: %zu\n",
1876 req_size, remaining);
1877 req_size = remaining;
1878 }
1879
1880 do {
1881 ts.curr_size = 0;
1882 ts.data = NULL;
1883 ts.type = DATA;
1884 ts.transferring = 1;
1885 ts.cache_ptr = cf;
1886 ts.ad_ptr = NULL;
1887
1888 if (cf) {
1889 PTHREAD_MUTEX_LOCK(&cf->dl_lock);
1890 ActiveDownload *ad = ActiveDownload_find(cf, offset);
1891 if (ad) {
1892 ad->ts = &ts;
1893 ts.ad_ptr = ad;
1894 ad->refcount++;
1895 PTHREAD_COND_BROADCAST(&ad->cond);
1896 }
1897 PTHREAD_MUTEX_UNLOCK(&cf->dl_lock);
1898 }
1899
1900 header.curr_size = 0;
1901 header.data = NULL;
1902 header.cache_ptr = NULL;
1903
1904 CURL *curl
1905 = Link_download_curl_setup(link, req_size, offset, &header, &ts);
1906
1907 transfer_blocking(curl);
1908
1909 recv_sz = Link_download_cleanup(curl, &header);
1910
1911 if (recv_sz < 0) {
1912 Link_download_finish_transfer(cf, offset, &ts);
1913 FREE(ts.data);
1914 if (recv_sz == -EAGAIN) {
1915 lprintf(warning, "HTTP temporary failure, retrying...\n");
1916 sleep(CONFIG.http_wait_sec);
1917 continue;
1918 }
1919 return recv_sz;
1920 }
1921
1922 if (recv_sz != (long int)req_size) {
1923 lprintf(error,
1924 "req_size != recv, req_size: %lu, recv: %ld, retrying...\n",
1925 req_size, recv_sz);
1926 Link_download_finish_transfer(cf, offset, &ts);
1927 FREE(ts.data);
1928 sleep(CONFIG.http_wait_sec);
1929 continue;
1930 }
1931
1932 /* success */
1933 break;
1934 } while (1);
1935
1936 Link_download_finish_transfer(cf, offset, &ts);
1937
1938 memmove(output_buf, ts.data, recv_sz);
1939 FREE(ts.data);
1940
1941 return recv_sz;
1942 }
1943
1944 long path_download(const char *path, char *output_buf, size_t req_size,
1945 off_t offset)
1946 {
1947 if (!path) {
1948 lprintf(fatal, "NULL path supplied\n");
1949 }
1950
1951 Link *link;
1952 link = path_to_Link(path);
1953 if (!link) {
1954 return -ENOENT;
1955 }
1956
1957 long res = Link_download(link, output_buf, req_size, offset, NULL);
1958 LinkTable_unref(link->parent_table);
1959 return res;
1960 }
1961
1962 static void make_link_relative(const char *page_url, char *link_url)
1963 {
1964 /*
1965 Some servers make the links to subdirectories absolute (in URI terms:
1966 path-absolute), but our code expects them to be relative (in URI terms:
1967 path-noscheme), so change the contents of link_url as needed to
1968 accommodate that.
1969
1970 Also, some servers serve their links as `./name`. This is helpful to
1971 them because it is the only way to express relative references when the
1972 first new path segment of the target contains an unescaped colon (`:`),
1973 eg in `./6:1-balun.png`. While stripping the ./ strictly speaking
1974 reintroduces that ambiguity, it is of little practical concern in this
1975 implementation, as full URI link targets are filtered by their number of
1976 slashes anyway. In URI terms, this converts path-noscheme with a leading
1977 `.` segment into path-noscheme or path-rootless without that segment.
1978 */
1979
1980 if (link_url[0] == '.' && link_url[1] == '/') {
1981 memmove(link_url, link_url + 2, strlen(link_url) - 1);
1982 return;
1983 }
1984
1985 if (link_url[0] != '/') {
1986 /* Already relative, nothing to do here!
1987
1988 (Full URIs, eg. `http://example.com/path`, pass through here
1989 unmodified, but those are classified in different LinkTypes later
1990 anyway).
1991 */
1992 return;
1993 }
1994
1995 /* Find the slash after the host name. */
1996 int slashes_left_to_find = 3;
1997 while (*page_url) {
1998 if (*page_url == '/' && !--slashes_left_to_find) {
1999 break;
2000 }
2001 /* N.B. This is here, rather than doing `while (*page_url++)`, because
2002 when we're done we want the pointer to point at the final slash. */
2003 page_url++;
2004 }
2005 if (slashes_left_to_find) {
2006 if (slashes_left_to_find == 1 && !*page_url) {
2007 /* We're at the top level of the web site and the user entered the
2008 URL without a trailing slash. */
2009 page_url = "/";
2010 } else {
2011 /* Well, that's odd. Let's return rather than trying to dig
2012 ourselves deeper into whatever hole we're in. */
2013 return;
2014 }
2015 }
2016 /* The page URL is no longer the full page_url, it's just the part after
2017 the host name. */
2018 /* The link URL should start with the page URL. */
2019 if (strstr(link_url, page_url) != link_url) {
2020 return;
2021 }
2022 int skip_len = strlen(page_url);
2023 if (page_url[skip_len - 1] != '/') {
2024 if (page_url[skip_len] != '/') {
2025 /* Um, I'm not sure what to do here, so give up. */
2026 return;
2027 }
2028 skip_len++;
2029 }
2030 /* Move the part of the link URL after the parent page's pat to
2031 the beginning of the link URL string, discarding what came
2032 before it. */
2033 memmove(link_url, link_url + skip_len, strlen(link_url) - skip_len + 1);
2034 }