Debian Codegraph @

src/main.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 main.c
26 * \brief Main entry point and argument parsing
27 */
28
29 #include "cache.h"
30 #include "config.h"
31 #include "fuse_local.h"
32 #include "link.h"
33 #include "log.h"
34 #include "network.h"
35 #include "util.h"
36
37 #include <ctype.h>
38 #include <errno.h>
39 #include <getopt.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44
45 void add_arg(char ***fuse_argv_ptr, int *fuse_argc, char *opt_string);
46 static void print_long_help(void);
47 static int parse_arg_list(int argc, char **argv, char ***fuse_argv,
48 int *fuse_argc);
49 void parse_config_file(char ***argv, int *argc);
50
51 static char *config_path = NULL;
52
53 static void print_help(char *program_name)
54 {
55 /* FUSE prints its help to stderr */
56 fprintf(stderr, "usage: %s [options] URL mountpoint\n", program_name);
57 }
58
59 int main(int argc, char **argv)
60 {
61 /*
62 * Automatically print help if not enough arguments are supplied
63 */
64 if (argc < 2) {
65 print_help(argv[0]);
66 fprintf(stderr, "For more information, run \"%s --help.\"\n", argv[0]);
67 exit(EXIT_FAILURE);
68 }
69
70 /*
71 * These are passed into fuse initialiser
72 */
73 char **fuse_argv = NULL;
74 int fuse_argc = 0;
75 int res = 0;
76 /*
77 * These are the combined argument with the config file
78 */
79 char **all_argv = NULL;
80 int all_argc = 0;
81
82 /*--- Add the program's name to the combined argument list ---*/
83 add_arg(&all_argv, &all_argc, argv[0]);
84 /*--- FUSE expects the first initialisation to be the program's name ---*/
85 add_arg(&fuse_argv, &fuse_argc, argv[0]);
86
87 /*
88 * initialise network configuration struct
89 */
90 Config_init();
91
92 /*
93 * initialise network subsystem
94 */
95 NetworkSystem_init();
96
97 /*
98 * Copy the command line argument list to the combined argument list
99 */
100 for (int i = 1; i < argc; i++) {
101 add_arg(&all_argv, &all_argc, argv[i]);
102 if (!strncmp(argv[i], "--config=", 9)) {
103 if (argv[i][9] == '\0') {
104 lprintf(error, "--config requires a path\n");
105 exit(EXIT_FAILURE);
106 }
107 FREE(config_path);
108 config_path = STRDUP(argv[i] + 9);
109 } else if (!strcmp(argv[i], "--config")) {
110 if (i + 1 >= argc || argv[i + 1][0] == '\0'
111 || argv[i + 1][0] == '-') {
112 lprintf(error, "--config requires a path\n");
113 exit(EXIT_FAILURE);
114 }
115 FREE(config_path);
116 config_path = STRDUP(argv[i + 1]);
117 add_arg(&all_argv, &all_argc, argv[i + 1]);
118 i++;
119 }
120 }
121
122 /*
123 * parse the config file, if it exists, store it in all_argv and
124 * all_argc
125 */
126 parse_config_file(&all_argv, &all_argc);
127
128 /*
129 * parse the combined argument list
130 */
131 optind = 1;
132
133 int skip = parse_arg_list(all_argc, all_argv, &fuse_argv, &fuse_argc);
134 if (skip) {
135 /*
136 * The user basically didn't supply enough arguments, if we reach here
137 * The point is to print some error messages
138 */
139 goto fuse_start;
140 }
141
142 if (optind + 2 != all_argc) {
143 fprintf(
144 stderr,
145 "Error: You must provide exactly one URL and one mountpoint.\n");
146 print_help(argv[0]);
147 exit(EXIT_FAILURE);
148 }
149
150 /*--- Check if FUSE is available ---*/
151 if (access("/dev/fuse", F_OK) == -1) {
152 fprintf(stderr, "Error: FUSE kernel module is not loaded.\n");
153 exit(EXIT_FAILURE);
154 }
155
156 /*--- Add the last remaining argument, which is the mountpoint ---*/
157 char *abs_mountpoint = REALPATH(all_argv[optind + 1], NULL);
158 if (!abs_mountpoint) {
159 fprintf(stderr, "Error: Invalid mountpoint %s: %s\n",
160 all_argv[optind + 1], strerror(errno));
161 print_help(argv[0]);
162 exit(EXIT_FAILURE);
163 }
164
165 struct stat st;
166 if (stat(abs_mountpoint, &st) == -1) {
167 fprintf(stderr, "Error: Could not stat mountpoint %s: %s\n",
168 abs_mountpoint, strerror(errno));
169 FREE(abs_mountpoint);
170 exit(EXIT_FAILURE);
171 }
172
173 if (!S_ISDIR(st.st_mode)) {
174 fprintf(stderr, "Error: Mountpoint %s is not a directory.\n",
175 abs_mountpoint);
176 FREE(abs_mountpoint);
177 exit(EXIT_FAILURE);
178 }
179
180 add_arg(&fuse_argv, &fuse_argc, abs_mountpoint);
181 FREE(abs_mountpoint);
182
183 /*
184 * The second last remaining argument is the URL
185 */
186 char *base_url = all_argv[optind];
187
188 if (strncmp(base_url, "http://", 7) != 0
189 && strncmp(base_url, "https://", 8) != 0) {
190 fprintf(stderr, "Error: Please supply a valid URL.\n");
191 print_help(argv[0]);
192 exit(EXIT_FAILURE);
193 } else {
194 if (CONFIG.sonic_username && CONFIG.sonic_password) {
195 CONFIG.mode = SONIC;
196 } else if (CONFIG.sonic_username || CONFIG.sonic_password) {
197 fprintf(stderr,
198 "Error: You have to supply both username and password to \
199 activate Sonic mode.\n");
200 exit(EXIT_FAILURE);
201 }
202 if (!LinkSystem_init(base_url)) {
203 fprintf(stderr, "Network initialisation failed.\n");
204 exit(EXIT_FAILURE);
205 }
206 }
207
208 fuse_start:
209 res = fuse_local_init(fuse_argc, fuse_argv);
210
211 for (int i = 0; i < all_argc; i++) {
212 FREE(all_argv[i]);
213 }
214 FREE(all_argv);
215
216 for (int i = 0; i < fuse_argc; i++) {
217 FREE(fuse_argv[i]);
218 }
219 FREE(fuse_argv);
220
221 FREE(config_path);
222
223 if (skip == 2) {
224 print_long_help();
225 }
226
227 return res;
228 }
229
230 static char *get_XDG_CONFIG_HOME(void)
231 {
232 const char *default_config_subdir = "/.config";
233 char *config_dir = NULL;
234
235 const char *xdg_config_home = getenv("XDG_CONFIG_HOME");
236 if (xdg_config_home) {
237 config_dir = STRNDUP(xdg_config_home, PATH_MAX);
238 } else {
239 const char *user_home = getenv("HOME");
240 if (user_home) {
241 config_dir = path_append(user_home, default_config_subdir);
242 } else {
243 lprintf(warning, "$HOME is unset\n");
244 char *cur_dir = REALPATH("./", NULL);
245 if (cur_dir) {
246 config_dir = path_append(cur_dir, default_config_subdir);
247 FREE(cur_dir);
248 } else {
249 lprintf(warning, "Could not get config directory\n");
250 }
251 }
252 }
253 return config_dir;
254 }
255
256 void parse_config_file(char ***argv, int *argc)
257 {
258 char *full_path;
259 if (!config_path) {
260 char *xdg_config_home = get_XDG_CONFIG_HOME();
261 full_path = path_append(xdg_config_home, "/httpdirfs/config");
262 FREE(xdg_config_home);
263 } else {
264 full_path = config_path;
265 }
266
267 char *buf = NULL;
268 size_t buf_len = 0;
269 FILE *config = fopen(full_path, "r");
270 if (!config) {
271 if (config_path) {
272 lprintf(fatal, "Could not open config file %s: %s\n", full_path,
273 strerror(errno));
274 }
275 } else {
276 while (getline(&buf, &buf_len, config) != -1) {
277 // Remove trailing whitespace
278 size_t len = strlen(buf);
279 while (len > 0 && isspace((unsigned char)buf[len - 1])) {
280 buf[--len] = '\0';
281 }
282
283 char *line = buf;
284 while (*line && isspace((unsigned char)*line)) {
285 line++;
286 }
287
288 if (line[0] == '-') {
289 char *space = strpbrk(line, " \t");
290 if (!space) {
291 add_arg(argv, argc, line);
292 } else {
293 *space = '\0';
294 add_arg(argv, argc, line);
295 /*
296 * Starts copying after the space, skipping leading
297 * whitespace
298 */
299 char *value = space + 1;
300 while (*value && isspace((unsigned char)*value)) {
301 value++;
302 }
303 if (*value != '\0') {
304 add_arg(argv, argc, value);
305 }
306 }
307 }
308 }
309 FREE(buf);
310 fclose(config);
311 }
312 if (full_path != config_path) {
313 FREE(full_path);
314 }
315 }
316
317 static int parse_arg_list(int argc, char **argv, char ***fuse_argv,
318 int *fuse_argc)
319 {
320 int c;
321 int long_index = 0;
322 const char *short_opts = "o:hVdfsp:u:P:";
323 const struct option long_opts[]
324
325 = {/* Note that 'L' is returned for long options */
326 {"help", no_argument, NULL, 'h'}, /* 0 */
327 {"version", no_argument, NULL, 'V'}, /* 1 */
328 {"debug", no_argument, NULL, 'd'}, /* 2 */
329 {"username", required_argument, NULL, 'u'}, /* 3 */
330 {"password", required_argument, NULL, 'p'}, /* 4 */
331 {"proxy", required_argument, NULL, 'P'}, /* 5 */
332 {"proxy-username", required_argument, NULL, 'L'}, /* 6 */
333 {"proxy-password", required_argument, NULL, 'L'}, /* 7 */
334 {"cache", no_argument, NULL, 'L'}, /* 8 */
335 {"dl-seg-size", required_argument, NULL, 'L'}, /* 9 */
336 {"max-conns", required_argument, NULL, 'L'}, /* 10 */
337 {"user-agent", required_argument, NULL, 'L'}, /* 11 */
338 {"retry-wait", required_argument, NULL, 'L'}, /* 12 */
339 {"cache-location", required_argument, NULL, 'L'}, /* 13 */
340 {"sonic-username", required_argument, NULL, 'L'}, /* 14 */
341 {"sonic-password", required_argument, NULL, 'L'}, /* 15 */
342 {"sonic-id3", no_argument, NULL, 'L'}, /* 16 */
343 {"no-range-check", no_argument, NULL, 'L'}, /* 17 */
344 {"sonic-insecure", no_argument, NULL, 'L'}, /* 18 */
345 {"insecure-tls", no_argument, NULL, 'L'}, /* 19 */
346 {"config", required_argument, NULL, 'L'}, /* 20 */
347 {"single-file-mode", no_argument, NULL, 'L'}, /* 21 */
348 {"cacert", required_argument, NULL, 'L'}, /* 22 */
349 {"proxy-cacert", required_argument, NULL, 'L'}, /* 23 */
350 {"refresh-timeout", required_argument, NULL, 'L'}, /* 24 */
351 {"http-header", required_argument, NULL, 'L'}, /* 25 */
352 {"cache-clear", no_argument, NULL, 'L'}, /* 26 */
353 {"zero-len-is-dir", no_argument, NULL, 'L'}, /* 27 */
354 {"invalid-refresh", no_argument, NULL, 'L'}, /* 28 */
355 {"capath", required_argument, NULL, 'L'}, /* 29 */
356 {"proxy-capath", required_argument, NULL, 'L'}, /* 30 */
357 {"external-links", no_argument, NULL, 'L'}, /* 31 */
358 {"cache-min-size", required_argument, NULL, 'L'}, /* 32 */
359 {"cache-max-size", required_argument, NULL, 'L'}, /* 33 */
360 {0, 0, 0, 0}};
361 while ((c = getopt_long(argc, argv, short_opts, long_opts, &long_index))
362 != -1) {
363 switch (c) {
364 case 'o':
365 add_arg(fuse_argv, fuse_argc, "-o");
366 add_arg(fuse_argv, fuse_argc, optarg);
367 break;
368 case 'h':
369 add_arg(fuse_argv, fuse_argc, "-h");
370 /* skip everything else to print the help. */
371 return 2;
372 case 'V':
373 print_version();
374 add_arg(fuse_argv, fuse_argc, "-V");
375 /* skip everything else to print the version info. */
376 return 1;
377 case 'd':
378 add_arg(fuse_argv, fuse_argc, "-d");
379 CONFIG.log_type |= debug;
380 break;
381 case 'f':
382 add_arg(fuse_argv, fuse_argc, "-f");
383 break;
384 case 's':
385 add_arg(fuse_argv, fuse_argc, "-s");
386 break;
387 case 'u':
388 CONFIG.http_username = STRDUP(optarg);
389 break;
390 case 'p':
391 CONFIG.http_password = STRDUP(optarg);
392 break;
393 case 'P':
394 CONFIG.proxy = STRDUP(optarg);
395 break;
396 case 'L':
397 /*
398 * Long options
399 */
400 switch (long_index) {
401 case 6:
402 CONFIG.proxy_username = STRDUP(optarg);
403 break;
404 case 7:
405 CONFIG.proxy_password = STRDUP(optarg);
406 break;
407 case 8:
408 CONFIG.cache_enabled = 1;
409 break;
410 case 9:
411 CONFIG.data_blksz = (int)strtol(optarg, NULL, 10) * 1024 * 1024;
412 break;
413 case 10:
414 CONFIG.max_conns = (int)strtol(optarg, NULL, 10);
415 break;
416 case 11:
417 CONFIG.user_agent = STRDUP(optarg);
418 break;
419 case 12:
420 CONFIG.http_wait_sec = (int)strtol(optarg, NULL, 10);
421 break;
422 case 13:
423 CONFIG.cache_dir = STRDUP(optarg);
424 break;
425 case 14:
426 CONFIG.sonic_username = STRDUP(optarg);
427 break;
428 case 15:
429 CONFIG.sonic_password = STRDUP(optarg);
430 break;
431 case 16:
432 CONFIG.sonic_id3 = 1;
433 break;
434 case 17:
435 CONFIG.no_range_check = 1;
436 break;
437 case 18:
438 CONFIG.sonic_insecure = 1;
439 break;
440 case 19:
441 CONFIG.insecure_tls = 1;
442 break;
443 case 20:
444 /*
445 * This is for --config, we don't need to do anything
446 */
447 break;
448 case 21:
449 CONFIG.mode = SINGLE;
450 break;
451 case 22:
452 CONFIG.cafile = STRDUP(optarg);
453 break;
454 case 23:
455 CONFIG.proxy_cafile = STRDUP(optarg);
456 break;
457 case 24:
458 CONFIG.refresh_timeout = (int)strtol(optarg, NULL, 10);
459 break;
460 case 25:
461 CONFIG.http_headers
462 = curl_slist_append(CONFIG.http_headers, optarg);
463 break;
464 case 26:
465 CacheSystem_clear();
466 break;
467 case 27:
468 CONFIG.zero_len_is_dir = 1;
469 break;
470 case 28:
471 CONFIG.invalid_refresh = 1;
472 break;
473 case 29:
474 CONFIG.capath = STRDUP(optarg);
475 break;
476 case 30:
477 CONFIG.proxy_capath = STRDUP(optarg);
478 break;
479 case 31:
480 CONFIG.external_links = 1;
481 break;
482 case 32: {
483 char *endptr;
484 errno = 0;
485 long long val = strtoll(optarg, &endptr, 10);
486 if (errno != 0 || endptr == optarg || *endptr != '\0' || val < 0
487 || (long long)(off_t)val != val) {
488 fprintf(stderr,
489 "Error: --cache-min-size requires a "
490 "non-negative integer within off_t range\n");
491 exit(EXIT_FAILURE);
492 }
493 CONFIG.cache_min_size = (off_t)val;
494 } break;
495 case 33: {
496 char *endptr;
497 errno = 0;
498 long long val = strtoll(optarg, &endptr, 10);
499 if (errno != 0 || endptr == optarg || *endptr != '\0' || val < 0
500 || (long long)(off_t)val != val) {
501 fprintf(stderr,
502 "Error: --cache-max-size requires a "
503 "non-negative integer within off_t range\n");
504 exit(EXIT_FAILURE);
505 }
506 CONFIG.cache_max_size = (off_t)val;
507 } break;
508 default:
509 fprintf(stderr, "see httpdirfs -h for usage\n");
510 exit(EXIT_FAILURE);
511 }
512 break;
513 default:
514 fprintf(stderr, "see httpdirfs -h for usage\n");
515 exit(EXIT_FAILURE);
516 }
517 };
518 if (CONFIG.cache_min_size >= 0 && CONFIG.cache_max_size >= 0
519 && CONFIG.cache_min_size > CONFIG.cache_max_size) {
520 fprintf(stderr, "Error: --cache-min-size cannot be greater than "
521 "--cache-max-size\n");
522 exit(EXIT_FAILURE);
523 }
524 return 0;
525 }
526
527 /**
528 * \brief add an argument to an argv array
529 * \details This is basically how you add a string to an array of string
530 */
531 void add_arg(char ***fuse_argv_ptr, int *fuse_argc, char *opt_string)
532 {
533 char **new_argv = (char **)REALLOC(
534 (void *)*fuse_argv_ptr, ((size_t)*fuse_argc + 1) * sizeof(char *));
535 *fuse_argv_ptr = new_argv;
536 char **fuse_argv = *fuse_argv_ptr;
537 fuse_argv[*fuse_argc] = STRDUP(opt_string);
538 (*fuse_argc)++;
539 }
540
541 static void print_long_help(void)
542 {
543 /* FUSE prints its help to stderr */
544 fprintf(stderr, "\n\
545 general options:\n\
546 --config Specify a configuration file \n\
547 -o opt,[opt...] Mount options\n\
548 -h --help Print help\n\
549 -V --version Print version\n\
550 -f Foreground operation\n\
551 -s Disable multi-threaded operation\n\
552 -d --debug Enable debug output (implies -f)\n\
553 \n\
554 HTTPDirFS options:\n\
555 -u --username HTTP authentication username\n\
556 -p --password HTTP authentication password\n\
557 -P --proxy Proxy for libcurl, for more details refer to\n\
558 https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html\n\
559 --proxy-username Username for the proxy\n\
560 --proxy-password Password for the proxy\n\
561 --proxy-cacert Certificate authority for the proxy\n\
562 --proxy-capath Certificate authority directory for the proxy\n\
563 --cache Enable cache (default: off)\n\
564 --cache-location Set a custom cache location\n\
565 (default: \"${XDG_CACHE_HOME}/httpdirfs\")\n\
566 --cache-clear Delete the cache directory or the custom location\n\
567 specified with `--cache-location`, if the option is\n\
568 seen first. Then exit in either case.\n\
569 --cache-min-size Set minimum file size threshold for caching, in bytes\n\
570 (default: none)\n\
571 --cache-max-size Set maximum file size threshold for caching, in bytes\n\
572 (default: none)\n\
573 --cacert Certificate authority for the server\n\
574 --capath Certificate authority directory for the server\n\
575 --dl-seg-size Set cache download segment size, in MB (default: " XSTR(
576 DEFAULT_DATA_BLKSZ_MB) ")\n\
577 Note: this setting is ignored if previously\n\
578 cached data is found for the requested file.\n\
579 --http-header Set one or more HTTP headers\n\
580 --max-conns Set maximum number of network connections that\n\
581 libcurl is allowed to make. (default: " XSTR(DEFAULT_NETWORK_MAX_CONNS) ")\n\
582 --refresh-timeout The directories are refreshed after the specified\n\
583 time, in seconds (default: " XSTR(DEFAULT_REFRESH_TIMEOUT) ")\n\
584 --retry-wait Set delay in seconds before retrying an HTTP request\n\
585 after encountering an error. (default: " XSTR(DEFAULT_HTTP_WAIT_SEC) ")\n\
586 --invalid-refresh Try refreshing invalid links when reading a directory.\n\
587 --user-agent Set user agent string (default: \"" DEFAULT_USER_AGENT "\")\n\
588 --no-range-check Disable the built-in check for the server's support\n\
589 for HTTP range requests\n\
590 --zero-len-is-dir If a file has a zero length, treat it as a directory\n\
591 --insecure-tls Disable libcurl TLS certificate verification by\n\
592 setting CURLOPT_SSL_VERIFYHOST to 0\n\
593 --external-links Include external (cross-origin) links from\n\
594 directory listings (default: off)\n\
595 --single-file-mode Single file mode - rather than mounting a whole\n\
596 directory, present a single file inside a virtual\n\
597 directory.\n\
598 \n\
599 For mounting a Airsonic / Subsonic server:\n\
600 --sonic-username The username for your Airsonic / Subsonic server\n\
601 --sonic-password The password for your Airsonic / Subsonic server\n\
602 --sonic-id3 Enable ID3 mode - this present the server content in\n\
603 Artist/Album/Song layout \n\
604 --sonic-insecure Authenticate against your Airsonic / Subsonic server\n\
605 using the insecure username / hex encoded password\n\
606 scheme\n\
607 \n");
608 }