]> git.seodisparate.com - c_simple_http/commitdiff
Add new arg for program: --enable-cache-dir=<DIR>
authorStephen Seo <seo.disparate@gmail.com>
Sun, 22 Sep 2024 05:42:41 +0000 (14:42 +0900)
committerStephen Seo <seo.disparate@gmail.com>
Sun, 22 Sep 2024 05:42:41 +0000 (14:42 +0900)
src/arg_parse.c
src/arg_parse.h

index 7250e36d8c6731a7efb0c77e8d867a0116d61aec..ce626e0e4f51d447de59a51085828ff400d3250b 100644 (file)
 #include <stdlib.h>
 #include <stdio.h>
 
+// libc includes.
+#include <sys/types.h>
+#include <dirent.h>
+#include <errno.h>
+
+// Posix includes.
+#include <sys/stat.h>
+
 void print_usage(void) {
   puts("Usage:");
   puts("  -p <port> | --port <port>");
@@ -30,6 +38,7 @@ void print_usage(void) {
   puts("    For example: --req-header-to-print=User-Agent");
   puts("    Note that this option is case-insensitive");
   puts("  --enable-reload-config-on-change");
+  puts("  --enable-cache-dir=<DIR>");
 }
 
 Args parse_args(int32_t argc, char **argv) {
@@ -69,6 +78,36 @@ Args parse_args(int32_t argc, char **argv) {
       }
     } else if (strcmp(argv[0], "--enable-reload-config-on-change") == 0) {
       args.flags |= 2;
+    } else if (strncmp(argv[0], "--enable-cache-dir=", 19) == 0) {
+      args.cache_dir = argv[0] + 19;
+      // Check if it actually is an existing directory.
+      DIR *d = opendir(args.cache_dir);
+      if (d == NULL) {
+        if (errno == ENOENT) {
+          printf(
+            "Directory \"%s\" doesn't exist, creating it...\n",
+            args.cache_dir);
+          int ret = mkdir(
+              args.cache_dir,
+              S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
+          if (ret == -1) {
+            fprintf(
+              stderr,
+              "ERROR Failed to create new directory (errno %d)\n",
+              errno);
+            exit(1);
+          }
+        } else {
+          fprintf(
+            stderr,
+            "ERROR Failed to open directory \"%s\" (errno %d)!\n",
+            args.cache_dir,
+            errno);
+          exit(1);
+        }
+      } else {
+        printf("Directory \"%s\" exists.\n", args.cache_dir);
+      }
     } else {
       puts("ERROR: Invalid args!\n");
       print_usage();
index 8f56fcd652a98a42151e47e10e1dacaee842e04a..c14ee905d254b81699f7ea4f538a1a34f5b0da5c 100644 (file)
@@ -34,6 +34,9 @@ typedef struct Args {
   const char *config_file;
   // Needs to be free'd.
   SDArchiverLinkedList *list_of_headers_to_log;
+  // Non-NULL if cache-dir is specified and cache is to be used.
+  // Does not need to be free'd since it points to a string in argv.
+  const char *cache_dir;
 } Args;
 
 void print_usage(void);