+
+static int is_token_char(char c)
+{
+ return isalnum(c) || c == '_';
+}
+
+/* Replace name with getenv(name), return pointer to zero-terminating char
+ */
+static char *expand_macro(char *name, int maxlength)
+{
+ char *value;
+ int len;
+
+ len = 0;
+ value = getenv(name);
+ if (value) {
+ len = strlen(value);
+ if (len > maxlength)
+ len = maxlength;
+ strncpy(name, value, len);
+ }
+ return name + len;
+}
+
+#define EXPBUFSIZE (1024 * 8)
+
+/* Replace all tokens prefixed by '$' in the specified text with the
+ * value of the named environment variable.
+ * NB: the return value is a static buffer, i.e. it must be strdup'd
+ * by the caller.
+ */
+char *expand_macros(const char *txt)
+{
+ static char result[EXPBUFSIZE];
+ char *p, *start;
+ int len;
+
+ p = result;
+ start = NULL;
+ while (p < result + EXPBUFSIZE - 1 && txt && *txt) {
+ *p = *txt;
+ if (start) {
+ if (!is_token_char(*txt)) {
+ if (p - start > 0) {
+ *p = '\0';
+ len = result + EXPBUFSIZE - start - 1;
+ p = expand_macro(start, len) - 1;
+ }
+ start = NULL;
+ txt--;
+ }
+ p++;
+ txt++;
+ continue;
+ }
+ if (*txt == '$') {
+ start = p;
+ txt++;
+ continue;
+ }
+ p++;
+ txt++;
+ }
+ *p = '\0';
+ if (start && p - start > 0) {
+ len = result + EXPBUFSIZE - start - 1;
+ p = expand_macro(start, len);
+ *p = '\0';
+ }
+ return result;
+}
+
+char *get_mimetype_for_filename(const char *filename)
+{
+ static const char *delimiters;
+ char *ext = NULL, *iterate, *mimetype = NULL, *token;
+ char line[1024];
+ FILE *fd;
+ struct string_list_item *mime;
+
+ if (filename == NULL)
+ return NULL;
+
+ ext = strrchr(filename, '.');
+
+ if (ext && *(++ext)) {
+ mime = string_list_lookup(&ctx.cfg.mimetypes, ext);
+ if (mime) {
+ /* We could just pass the pointer here, but would have to care
+ * whether or not to free the memory. Instead just dup. */
+ mimetype = xstrdup(mime->util);
+ } else if (ctx.cfg.mimetype_file != NULL) {
+ fd = fopen(ctx.cfg.mimetype_file, "r");
+ if (fd == NULL)
+ return NULL;
+
+ delimiters = " \t\r\n";
+
+ /* loop over all lines in the file */
+ while (mimetype == NULL && fgets(line, sizeof(line), fd)) {
+ iterate = strtok(line, delimiters);
+
+ /* skip empty lines and comment lines */
+ if (iterate == NULL || (iterate[0] == '#'))
+ continue;
+
+ /* loop over all extensions of mimetype */
+ while ((token = strtok(NULL, delimiters))) {
+ if (strcasecmp(ext, token) == 0) {
+ mimetype = xstrdup(iterate);
+ break;
+ }
+ }
+ }
+ fclose(fd);
+ }
+ }
+
+ return mimetype;
+}