+static const char *output_file;
+static int output_fd;
+static int error_ret;
+
+static int open_output_file(const char *path, bool create)
+{
+ const char *str;
+ char *filename;
+ int len;
+ int flags = O_WRONLY;
+
+ if (create)
+ flags |= O_CREAT;
+
+ if (output_file) {
+ if (!strcmp(output_file, "-"))
+ return STDOUT_FILENO;
+
+ return open(output_file, flags, 0644);
+ }
+
+ /* Don't automatically overwrite files if the name is derived from the URL */
+ if (create)
+ flags |= O_EXCL;
+
+ len = strcspn(path, ";&");
+ while (len > 0 && path[len - 1] == '/')
+ len--;
+
+ for (str = path + len - 1; str >= path; str--) {
+ if (*str == '/')
+ break;
+ }
+
+ str++;
+ len -= str - path;
+
+ if (len > 0) {
+ filename = alloca(len + 1);
+ strncpy(filename, str, len);
+ filename[len] = 0;
+ } else {
+ filename = "index.html";
+ }
+
+ return open(filename, flags, 0644);
+}