static CURLcode operate_do(struct GlobalConfig *global,
                           struct OperationConfig *config)
{
  char errorbuffer[CURL_ERROR_SIZE];
  struct ProgressData progressbar;
  struct getout *urlnode;

  struct HdrCbData hdrcbdata;
  struct OutStruct heads;

  metalinkfile *mlfile_last = NULL;

  CURL *curl = config->easy;
  char *httpgetfields = NULL;

  CURLcode result = CURLE_OK;
  unsigned long li;

  /* Save the values of noprogress and isatty to restore them later on */
  bool orig_noprogress = global->noprogress;
  bool orig_isatty = global->isatty;

  errorbuffer[0] = '\0';

  /* default headers output stream is stdout */
  memset(&hdrcbdata, 0, sizeof(struct HdrCbData));
  memset(&heads, 0, sizeof(struct OutStruct));
  heads.stream = stdout;
  heads.config = config;

  /*
  ** Beyond this point no return'ing from this function allowed.
  ** Jump to label 'quit_curl' in order to abandon this function
  ** from outside of nested loops further down below.
  */

  /* Check we have a url */
  if(!config->url_list || !config->url_list->url) {
    helpf(global->errors, "no URL specified!\n");
    result = CURLE_FAILED_INIT;
    goto quit_curl;
  }

  /* On WIN32 we can't set the path to curl-ca-bundle.crt
   * at compile time. So we look here for the file in two ways:
   * 1: look at the environment variable CURL_CA_BUNDLE for a path
   * 2: if #1 isn't found, use the windows API function SearchPath()
   *    to find it along the app's path (includes app's dir and CWD)
   *
   * We support the environment variable thing for non-Windows platforms
   * too. Just for the sake of it.
   */
  if(!config->cacert &&
     !config->capath &&
     !config->insecure_ok) {
    char *env;
    env = curlx_getenv("CURL_CA_BUNDLE");
    if(env) {
      config->cacert = strdup(env);
      if(!config->cacert) {
        curl_free(env);
        helpf(global->errors, "out of memory\n");
        result = CURLE_OUT_OF_MEMORY;
        goto quit_curl;
      }
    }
    else {
      env = curlx_getenv("SSL_CERT_DIR");
      if(env) {
        config->capath = strdup(env);
        if(!config->capath) {
          curl_free(env);
          helpf(global->errors, "out of memory\n");
          result = CURLE_OUT_OF_MEMORY;
          goto quit_curl;
        }
      }
      else {
        env = curlx_getenv("SSL_CERT_FILE");
        if(env) {
          config->cacert = strdup(env);
          if(!config->cacert) {
            curl_free(env);
            helpf(global->errors, "out of memory\n");
            result = CURLE_OUT_OF_MEMORY;
            goto quit_curl;
          }
        }
      }
    }

    if(env)
      curl_free(env);
#ifdef WIN32
    else {
      result = FindWin32CACert(config, "curl-ca-bundle.crt");
      if(result)
        goto quit_curl;
    }
#endif
  }

  if(config->postfields) {
    if(config->use_httpget) {
      /* Use the postfields data for a http get */
      httpgetfields = strdup(config->postfields);
      Curl_safefree(config->postfields);
      if(!httpgetfields) {
        helpf(global->errors, "out of memory\n");
        result = CURLE_OUT_OF_MEMORY;
        goto quit_curl;
      }
      if(SetHTTPrequest(config,
                        (config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
                        &config->httpreq)) {
        result = CURLE_FAILED_INIT;
        goto quit_curl;
      }
    }
    else {
      if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq)) {
        result = CURLE_FAILED_INIT;
        goto quit_curl;
      }
    }
  }

  /* Single header file for all URLs */
  if(config->headerfile) {
    /* open file for output: */
    if(!curlx_strequal(config->headerfile, "-")) {
      FILE *newfile = fopen(config->headerfile, "wb");
      if(!newfile) {
        warnf(config->global, "Failed to open %s\n", config->headerfile);
        result = CURLE_WRITE_ERROR;
        goto quit_curl;
      }
      else {
        heads.filename = config->headerfile;
        heads.s_isreg = TRUE;
        heads.fopened = TRUE;
        heads.stream = newfile;
      }
    }
    else {
      /* always use binary mode for protocol header output */
      set_binmode(heads.stream);
    }
  }

  /*
  ** Nested loops start here.
  */

  /* loop through the list of given URLs */

  for(urlnode = config->url_list; urlnode; urlnode = urlnode->next) {

    unsigned long up; /* upload file counter within a single upload glob */
    char *infiles; /* might be a glob pattern */
    char *outfiles;
    unsigned long infilenum;
    URLGlob *inglob;

    int metalink = 0; /* nonzero for metalink download. */
    metalinkfile *mlfile;
    metalink_resource *mlres;

    outfiles = NULL;
    infilenum = 1;
    inglob = NULL;

    if(urlnode->flags & GETOUT_METALINK) {
      metalink = 1;
      if(mlfile_last == NULL) {
        mlfile_last = config->metalinkfile_list;
      }
      mlfile = mlfile_last;
      mlfile_last = mlfile_last->next;
      mlres = mlfile->resource;
    }
    else {
      mlfile = NULL;
      mlres = NULL;
    }

    /* urlnode->url is the full URL (it might be NULL) */

    if(!urlnode->url) {
      /* This node has no URL. Free node data without destroying the
         node itself nor modifying next pointer and continue to next */
      Curl_safefree(urlnode->outfile);
      Curl_safefree(urlnode->infile);
      urlnode->flags = 0;
      continue; /* next URL please */
    }

    /* save outfile pattern before expansion */
    if(urlnode->outfile) {
      outfiles = strdup(urlnode->outfile);
      if(!outfiles) {
        helpf(global->errors, "out of memory\n");
        result = CURLE_OUT_OF_MEMORY;
        break;
      }
    }

    infiles = urlnode->infile;

    if(!config->globoff && infiles) {
      /* Unless explicitly shut off */
      result = glob_url(&inglob, infiles, &infilenum,
                        global->showerror?global->errors:NULL);
      if(result) {
        Curl_safefree(outfiles);
        break;
      }
    }

    /* Here's the loop for uploading multiple files within the same
       single globbed string. If no upload, we enter the loop once anyway. */
    for(up = 0 ; up < infilenum; up++) {

      char *uploadfile; /* a single file, never a glob */
      int separator;
      URLGlob *urls;
      unsigned long urlnum;

      uploadfile = NULL;
      urls = NULL;
      urlnum = 0;

      if(!up && !infiles)
        Curl_nop_stmt;
      else {
        if(inglob) {
          result = glob_next_url(&uploadfile, inglob);
          if(result == CURLE_OUT_OF_MEMORY)
            helpf(global->errors, "out of memory\n");
        }
        else if(!up) {
          uploadfile = strdup(infiles);
          if(!uploadfile) {
            helpf(global->errors, "out of memory\n");
            result = CURLE_OUT_OF_MEMORY;
          }
        }
        else
          uploadfile = NULL;
        if(!uploadfile)
          break;
      }

      if(metalink) {
        /* For Metalink download, we don't use glob. Instead we use
           the number of resources as urlnum. */
        urlnum = count_next_metalink_resource(mlfile);
      }
      else
      if(!config->globoff) {
        /* Unless explicitly shut off, we expand '{...}' and '[...]'
           expressions and return total number of URLs in pattern set */
        result = glob_url(&urls, urlnode->url, &urlnum,
                          global->showerror?global->errors:NULL);
        if(result) {
          Curl_safefree(uploadfile);
          break;
        }
      }
      else
        urlnum = 1; /* without globbing, this is a single URL */

      /* if multiple files extracted to stdout, insert separators! */
      separator= ((!outfiles || curlx_strequal(outfiles, "-")) && urlnum > 1);

      /* Here's looping around each globbed URL */
      for(li = 0 ; li < urlnum; li++) {

        int infd;
        bool infdopen;
        char *outfile;
        struct OutStruct outs;
        struct InStruct input;
        struct timeval retrystart;
        curl_off_t uploadfilesize;
        long retry_numretries;
        long retry_sleep_default;
        long retry_sleep;
        char *this_url = NULL;
        int metalink_next_res = 0;

        outfile = NULL;
        infdopen = FALSE;
        infd = STDIN_FILENO;
        uploadfilesize = -1; /* -1 means unknown */

        /* default output stream is stdout */
        memset(&outs, 0, sizeof(struct OutStruct));
        outs.stream = stdout;
        outs.config = config;

        if(metalink) {
          /* For Metalink download, use name in Metalink file as
             filename. */
          outfile = strdup(mlfile->filename);
          if(!outfile) {
            result = CURLE_OUT_OF_MEMORY;
            goto show_error;
          }
          this_url = strdup(mlres->url);
          if(!this_url) {
            result = CURLE_OUT_OF_MEMORY;
            goto show_error;
          }
        }
        else {
          if(urls) {
            result = glob_next_url(&this_url, urls);
            if(result)
              goto show_error;
          }
          else if(!li) {
            this_url = strdup(urlnode->url);
            if(!this_url) {
              result = CURLE_OUT_OF_MEMORY;
              goto show_error;
            }
          }
          else
            this_url = NULL;
          if(!this_url)
            break;

          if(outfiles) {
            outfile = strdup(outfiles);
            if(!outfile) {
              result = CURLE_OUT_OF_MEMORY;
              goto show_error;
            }
          }
        }

        if(((urlnode->flags&GETOUT_USEREMOTE) ||
            (outfile && !curlx_strequal("-", outfile))) &&
           (metalink || !config->use_metalink)) {

          /*
           * We have specified a file name to store the result in, or we have
           * decided we want to use the remote file name.
           */

          if(!outfile) {
            /* extract the file name from the URL */
            result = get_url_file_name(&outfile, this_url);
            if(result)
              goto show_error;
            if(!*outfile && !config->content_disposition) {
              helpf(global->errors, "Remote file name has no length!\n");
              result = CURLE_WRITE_ERROR;
              goto quit_urls;
            }
#if defined(MSDOS) || defined(WIN32)
            /* For DOS and WIN32, we do some major replacing of
               bad characters in the file name before using it */
            outfile = sanitize_dos_name(outfile);
            if(!outfile) {
              result = CURLE_OUT_OF_MEMORY;
              goto show_error;
            }
#endif /* MSDOS || WIN32 */
          }
          else if(urls) {
            /* fill '#1' ... '#9' terms from URL pattern */
            char *storefile = outfile;
            result = glob_match_url(&outfile, storefile, urls);
            Curl_safefree(storefile);
            if(result) {
              /* bad globbing */
              warnf(config->global, "bad output glob!\n");
              goto quit_urls;
            }
          }

          /* Create the directory hierarchy, if not pre-existent to a multiple
             file output call */

          if(config->create_dirs || metalink) {
            result = create_dir_hierarchy(outfile, global->errors);
            /* create_dir_hierarchy shows error upon CURLE_WRITE_ERROR */
            if(result == CURLE_WRITE_ERROR)
              goto quit_urls;
            if(result) {
              goto show_error;
            }
          }

          if((urlnode->flags & GETOUT_USEREMOTE)
             && config->content_disposition) {
            /* Our header callback MIGHT set the filename */
            DEBUGASSERT(!outs.filename);
          }

          if(config->resume_from_current) {
            /* We're told to continue from where we are now. Get the size
               of the file as it is now and open it for append instead */
            struct_stat fileinfo;
            /* VMS -- Danger, the filesize is only valid for stream files */
            if(0 == stat(outfile, &fileinfo))
              /* set offset to current file size: */
              config->resume_from = fileinfo.st_size;
            else
              /* let offset be 0 */
              config->resume_from = 0;
          }

          if(config->resume_from) {
#ifdef __VMS
            /* open file for output, forcing VMS output format into stream
               mode which is needed for stat() call above to always work. */
            FILE *file = fopen(outfile, config->resume_from?"ab":"wb",
                               "ctx=stm", "rfm=stmlf", "rat=cr", "mrs=0");
#else
            /* open file for output: */
            FILE *file = fopen(outfile, config->resume_from?"ab":"wb");
#endif
            if(!file) {
              helpf(global->errors, "Can't open '%s'!\n", outfile);
              result = CURLE_WRITE_ERROR;
              goto quit_urls;
            }
            outs.fopened = TRUE;
            outs.stream = file;
            outs.init = config->resume_from;
          }
          else {
            outs.stream = NULL; /* open when needed */
          }
          outs.filename = outfile;
          outs.s_isreg = TRUE;
        }

        if(uploadfile && !stdin_upload(uploadfile)) {
          /*
           * We have specified a file to upload and it isn't "-".
           */
          struct_stat fileinfo;

          this_url = add_file_name_to_url(curl, this_url, uploadfile);
          if(!this_url) {
            result = CURLE_OUT_OF_MEMORY;
            goto show_error;
          }
          /* VMS Note:
           *
           * Reading binary from files can be a problem...  Only FIXED, VAR
           * etc WITHOUT implied CC will work Others need a \n appended to a
           * line
           *
           * - Stat gives a size but this is UNRELIABLE in VMS As a f.e. a
           * fixed file with implied CC needs to have a byte added for every
           * record processed, this can by derived from Filesize & recordsize
           * for VARiable record files the records need to be counted!  for
           * every record add 1 for linefeed and subtract 2 for the record
           * header for VARIABLE header files only the bare record data needs
           * to be considered with one appended if implied CC
           */
#ifdef __VMS
          /* Calculate the real upload site for VMS */
          infd = -1;
          if(stat(uploadfile, &fileinfo) == 0) {
            fileinfo.st_size = VmsSpecialSize(uploadfile, &fileinfo);
            switch (fileinfo.st_fab_rfm) {
            case FAB$C_VAR:
            case FAB$C_VFC:
            case FAB$C_STMCR:
              infd = open(uploadfile, O_RDONLY | O_BINARY);
              break;
            default:
              infd = open(uploadfile, O_RDONLY | O_BINARY,
                          "rfm=stmlf", "ctx=stm");
            }
          }
          if(infd == -1)
#else
          infd = open(uploadfile, O_RDONLY | O_BINARY);
          if((infd == -1) || fstat(infd, &fileinfo))
#endif
          {
            helpf(global->errors, "Can't open '%s'!\n", uploadfile);
            if(infd != -1) {
              close(infd);
              infd = STDIN_FILENO;
            }
            result = CURLE_READ_ERROR;
            goto quit_urls;
          }
          infdopen = TRUE;

          /* we ignore file size for char/block devices, sockets, etc. */
          if(S_ISREG(fileinfo.st_mode))
            uploadfilesize = fileinfo.st_size;

        }
        else if(uploadfile && stdin_upload(uploadfile)) {
          /* count to see if there are more than one auth bit set
             in the authtype field */
          int authbits = 0;
          int bitcheck = 0;
          while(bitcheck < 32) {
            if(config->authtype & (1UL << bitcheck++)) {
              authbits++;
              if(authbits > 1) {
                /* more than one, we're done! */
                break;
              }
            }
          }

          /*
           * If the user has also selected --anyauth or --proxy-anyauth
           * we should warn him/her.
           */
          if(config->proxyanyauth || (authbits>1)) {
            warnf(config->global,
                  "Using --anyauth or --proxy-anyauth with upload from stdin"
                  " involves a big risk of it not working. Use a temporary"
                  " file or a fixed auth type instead!\n");
          }

          DEBUGASSERT(infdopen == FALSE);
          DEBUGASSERT(infd == STDIN_FILENO);

          set_binmode(stdin);
          if(curlx_strequal(uploadfile, ".")) {
            if(curlx_nonblock((curl_socket_t)infd, TRUE) < 0)
              warnf(config->global,
                    "fcntl failed on fd=%d: %s\n", infd, strerror(errno));
          }
        }

        if(uploadfile && config->resume_from_current)
          config->resume_from = -1; /* -1 will then force get-it-yourself */

        if(output_expected(this_url, uploadfile) && outs.stream &&
           isatty(fileno(outs.stream)))
          /* we send the output to a tty, therefore we switch off the progress
             meter */
          global->noprogress = global->isatty = TRUE;
        else {
          /* progress meter is per download, so restore config
             values */
          global->noprogress = orig_noprogress;
          global->isatty = orig_isatty;
        }

        if(urlnum > 1 && !global->mute) {
          fprintf(global->errors, "\n[%lu/%lu]: %s --> %s\n",
                  li+1, urlnum, this_url, outfile ? outfile : "<stdout>");
          if(separator)
            printf("%s%s\n", CURLseparator, this_url);
        }
        if(httpgetfields) {
          char *urlbuffer;
          /* Find out whether the url contains a file name */
          const char *pc = strstr(this_url, "://");
          char sep = '?';
          if(pc)
            pc += 3;
          else
            pc = this_url;

          pc = strrchr(pc, '/'); /* check for a slash */

          if(pc) {
            /* there is a slash present in the URL */

            if(strchr(pc, '?'))
              /* Ouch, there's already a question mark in the URL string, we
                 then append the data with an ampersand separator instead! */
              sep='&';
          }
          /*
           * Then append ? followed by the get fields to the url.
           */
          if(pc)
            urlbuffer = aprintf("%s%c%s", this_url, sep, httpgetfields);
          else
            /* Append  / before the ? to create a well-formed url
               if the url contains a hostname only
            */
            urlbuffer = aprintf("%s/?%s", this_url, httpgetfields);

          if(!urlbuffer) {
            result = CURLE_OUT_OF_MEMORY;
            goto show_error;
          }

          Curl_safefree(this_url); /* free previous URL */
          this_url = urlbuffer; /* use our new URL instead! */
        }

        if(!global->errors)
          global->errors = stderr;

        if((!outfile || !strcmp(outfile, "-")) && !config->use_ascii) {
          /* We get the output to stdout and we have not got the ASCII/text
             flag, then set stdout to be binary */
          set_binmode(stdout);
        }

        if(config->tcp_nodelay)
          my_setopt(curl, CURLOPT_TCP_NODELAY, 1L);

        /* where to store */
        my_setopt(curl, CURLOPT_WRITEDATA, &outs);
        if(metalink || !config->use_metalink)
          /* what call to write */
          my_setopt(curl, CURLOPT_WRITEFUNCTION, tool_write_cb);
#ifdef USE_METALINK
        else
          /* Set Metalink specific write callback function to parse
             XML data progressively. */
          my_setopt(curl, CURLOPT_WRITEFUNCTION, metalink_write_cb);
#endif /* USE_METALINK */

        /* for uploads */
        input.fd = infd;
        input.config = config;
        /* Note that if CURLOPT_READFUNCTION is fread (the default), then
         * lib/telnet.c will Curl_poll() on the input file descriptor
         * rather then calling the READFUNCTION at regular intervals.
         * The circumstances in which it is preferable to enable this
         * behaviour, by omitting to set the READFUNCTION & READDATA options,
         * have not been determined.
         */
        my_setopt(curl, CURLOPT_READDATA, &input);
        /* what call to read */
        my_setopt(curl, CURLOPT_READFUNCTION, tool_read_cb);

        /* in 7.18.0, the CURLOPT_SEEKFUNCTION/DATA pair is taking over what
           CURLOPT_IOCTLFUNCTION/DATA pair previously provided for seeking */
        my_setopt(curl, CURLOPT_SEEKDATA, &input);
        my_setopt(curl, CURLOPT_SEEKFUNCTION, tool_seek_cb);

        if(config->recvpersecond)
          /* tell libcurl to use a smaller sized buffer as it allows us to
             make better sleeps! 7.9.9 stuff! */
          my_setopt(curl, CURLOPT_BUFFERSIZE, (long)config->recvpersecond);

        /* size of uploaded file: */
        if(uploadfilesize != -1)
          my_setopt(curl, CURLOPT_INFILESIZE_LARGE, uploadfilesize);
        my_setopt_str(curl, CURLOPT_URL, this_url);     /* what to fetch */
        my_setopt(curl, CURLOPT_NOPROGRESS, global->noprogress?1L:0L);
        if(config->no_body) {
          my_setopt(curl, CURLOPT_NOBODY, 1L);
          my_setopt(curl, CURLOPT_HEADER, 1L);
        }
        /* If --metalink is used, we ignore --include (headers in
           output) option because mixing headers to the body will
           confuse XML parser and/or hash check will fail. */
        else if(!config->use_metalink)
          my_setopt(curl, CURLOPT_HEADER, config->include_headers?1L:0L);

        if(config->xoauth2_bearer)
          my_setopt_str(curl, CURLOPT_XOAUTH2_BEARER, config->xoauth2_bearer);

#if !defined(CURL_DISABLE_PROXY)
        {
          /* TODO: Make this a run-time check instead of compile-time one. */

          my_setopt_str(curl, CURLOPT_PROXY, config->proxy);
          my_setopt_str(curl, CURLOPT_PROXYUSERPWD, config->proxyuserpwd);

          /* new in libcurl 7.3 */
          my_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, config->proxytunnel?1L:0L);

          /* new in libcurl 7.5 */
          if(config->proxy)
            my_setopt_enum(curl, CURLOPT_PROXYTYPE, (long)config->proxyver);

          /* new in libcurl 7.10 */
          if(config->socksproxy) {
            my_setopt_str(curl, CURLOPT_PROXY, config->socksproxy);
            my_setopt_enum(curl, CURLOPT_PROXYTYPE, (long)config->socksver);
          }

          /* new in libcurl 7.10.6 */
          if(config->proxyanyauth)
            my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
                              (long)CURLAUTH_ANY);
          else if(config->proxynegotiate)
            my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
                              (long)CURLAUTH_GSSNEGOTIATE);
          else if(config->proxyntlm)
            my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
                              (long)CURLAUTH_NTLM);
          else if(config->proxydigest)
            my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
                              (long)CURLAUTH_DIGEST);
          else if(config->proxybasic)
            my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
                              (long)CURLAUTH_BASIC);

          /* new in libcurl 7.19.4 */
          my_setopt(curl, CURLOPT_NOPROXY, config->noproxy);
        }
#endif

        my_setopt(curl, CURLOPT_FAILONERROR, config->failonerror?1L:0L);
        my_setopt(curl, CURLOPT_UPLOAD, uploadfile?1L:0L);
        my_setopt(curl, CURLOPT_DIRLISTONLY, config->dirlistonly?1L:0L);
        my_setopt(curl, CURLOPT_APPEND, config->ftp_append?1L:0L);

        if(config->netrc_opt)
          my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_OPTIONAL);
        else if(config->netrc || config->netrc_file)
          my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_REQUIRED);
        else
          my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_IGNORED);

        if(config->netrc_file)
          my_setopt(curl, CURLOPT_NETRC_FILE, config->netrc_file);

        my_setopt(curl, CURLOPT_TRANSFERTEXT, config->use_ascii?1L:0L);
        if(config->login_options)
          my_setopt_str(curl, CURLOPT_LOGIN_OPTIONS, config->login_options);
        my_setopt_str(curl, CURLOPT_USERPWD, config->userpwd);
        my_setopt_str(curl, CURLOPT_RANGE, config->range);
        my_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
        my_setopt(curl, CURLOPT_TIMEOUT_MS, (long)(config->timeout * 1000));

        if(built_in_protos & CURLPROTO_HTTP) {

          long postRedir = 0;

          my_setopt(curl, CURLOPT_FOLLOWLOCATION,
                    config->followlocation?1L:0L);
          my_setopt(curl, CURLOPT_UNRESTRICTED_AUTH,
                    config->unrestricted_auth?1L:0L);

          switch(config->httpreq) {
          case HTTPREQ_SIMPLEPOST:
            my_setopt_str(curl, CURLOPT_POSTFIELDS,
                          config->postfields);
            my_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE,
                      config->postfieldsize);
            break;
          case HTTPREQ_FORMPOST:
            my_setopt_httppost(curl, CURLOPT_HTTPPOST, config->httppost);
            break;
          default:
            break;
          }

          my_setopt_str(curl, CURLOPT_REFERER, config->referer);
          my_setopt(curl, CURLOPT_AUTOREFERER, config->autoreferer?1L:0L);
          my_setopt_str(curl, CURLOPT_USERAGENT, config->useragent);
          my_setopt_slist(curl, CURLOPT_HTTPHEADER, config->headers);

          /* new in libcurl 7.36.0 */
          if(config->proxyheaders) {
            my_setopt_slist(curl, CURLOPT_PROXYHEADER, config->proxyheaders);
            my_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_SEPARATE);
          }

          /* new in libcurl 7.5 */
          my_setopt(curl, CURLOPT_MAXREDIRS, config->maxredirs);

          /* new in libcurl 7.9.1 */
          if(config->httpversion)
            my_setopt_enum(curl, CURLOPT_HTTP_VERSION, config->httpversion);

          /* new in libcurl 7.10.6 (default is Basic) */
          if(config->authtype)
            my_setopt_bitmask(curl, CURLOPT_HTTPAUTH, (long)config->authtype);

          /* curl 7.19.1 (the 301 version existed in 7.18.2),
             303 was added in 7.26.0 */
          if(config->post301)
            postRedir |= CURL_REDIR_POST_301;
          if(config->post302)
            postRedir |= CURL_REDIR_POST_302;
          if(config->post303)
            postRedir |= CURL_REDIR_POST_303;
          my_setopt(curl, CURLOPT_POSTREDIR, postRedir);

          /* new in libcurl 7.21.6 */
          if(config->encoding)
            my_setopt_str(curl, CURLOPT_ACCEPT_ENCODING, "");

          /* new in libcurl 7.21.6 */
          if(config->tr_encoding)
            my_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1L);

        } /* (built_in_protos & CURLPROTO_HTTP) */

        my_setopt_str(curl, CURLOPT_FTPPORT, config->ftpport);
        my_setopt(curl, CURLOPT_LOW_SPEED_LIMIT,
                  config->low_speed_limit);
        my_setopt(curl, CURLOPT_LOW_SPEED_TIME, config->low_speed_time);
        my_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE,
                  config->sendpersecond);
        my_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE,
                  config->recvpersecond);

        if(config->use_resume)
          my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, config->resume_from);
        else
          my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, CURL_OFF_T_C(0));

        my_setopt_str(curl, CURLOPT_KEYPASSWD, config->key_passwd);

        if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {

          /* SSH and SSL private key uses same command-line option */
          /* new in libcurl 7.16.1 */
          my_setopt_str(curl, CURLOPT_SSH_PRIVATE_KEYFILE, config->key);
          /* new in libcurl 7.16.1 */
          my_setopt_str(curl, CURLOPT_SSH_PUBLIC_KEYFILE, config->pubkey);

          /* new in libcurl 7.17.1: SSH host key md5 checking allows us
             to fail if we are not talking to who we think we should */
          my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
                        config->hostpubmd5);
        }

        if(config->cacert)
          my_setopt_str(curl, CURLOPT_CAINFO, config->cacert);
        if(config->capath)
          my_setopt_str(curl, CURLOPT_CAPATH, config->capath);
        if(config->crlfile)
          my_setopt_str(curl, CURLOPT_CRLFILE, config->crlfile);

        if(config->pinnedpubkey)
          my_setopt_str(curl, CURLOPT_PINNEDPUBLICKEY, config->pinnedpubkey);

        if(curlinfo->features & CURL_VERSION_SSL) {
          my_setopt_str(curl, CURLOPT_SSLCERT, config->cert);
          my_setopt_str(curl, CURLOPT_SSLCERTTYPE, config->cert_type);
          my_setopt_str(curl, CURLOPT_SSLKEY, config->key);
          my_setopt_str(curl, CURLOPT_SSLKEYTYPE, config->key_type);

          if(config->insecure_ok) {
            my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
            my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
          }
          else {
            my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
            /* libcurl default is strict verifyhost -> 2L   */
            /* my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); */
          }

          if(config->verifystatus)
            my_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 1L);

          if(config->falsestart)
            my_setopt(curl, CURLOPT_SSL_FALSESTART, 1L);

          my_setopt_enum(curl, CURLOPT_SSLVERSION, config->ssl_version);
        }
        if(config->path_as_is)
          my_setopt(curl, CURLOPT_PATH_AS_IS, 1L);

        if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
          if(!config->insecure_ok) {
            char *home;
            char *file;
            result = CURLE_OUT_OF_MEMORY;
            home = homedir();
            if(home) {
              file = aprintf("%s/%sssh/known_hosts", home, DOT_CHAR);
              if(file) {
                /* new in curl 7.19.6 */
                result = res_setopt_str(curl, CURLOPT_SSH_KNOWNHOSTS, file);
                curl_free(file);
                if(result == CURLE_UNKNOWN_OPTION)
                  /* libssh2 version older than 1.1.1 */
                  result = CURLE_OK;
              }
              Curl_safefree(home);
            }
            if(result)
              goto show_error;
          }
        }

        if(config->no_body || config->remote_time) {
          /* no body or use remote time */
          my_setopt(curl, CURLOPT_FILETIME, 1L);
        }

        my_setopt(curl, CURLOPT_CRLF, config->crlf?1L:0L);
        my_setopt_slist(curl, CURLOPT_QUOTE, config->quote);
        my_setopt_slist(curl, CURLOPT_POSTQUOTE, config->postquote);
        my_setopt_slist(curl, CURLOPT_PREQUOTE, config->prequote);

#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
        if(config->cookie)
          my_setopt_str(curl, CURLOPT_COOKIE, config->cookie);

        if(config->cookiefile)
          my_setopt_str(curl, CURLOPT_COOKIEFILE, config->cookiefile);

        /* new in libcurl 7.9 */
        if(config->cookiejar)
          my_setopt_str(curl, CURLOPT_COOKIEJAR, config->cookiejar);

        /* new in libcurl 7.9.7 */
        my_setopt(curl, CURLOPT_COOKIESESSION, config->cookiesession?1L:0L);
#else
        if(config->cookie || config->cookiefile || config->cookiejar) {
          warnf(config->global, "cookie option(s) used even though cookie "
                "support is disabled!\n");
          return CURLE_NOT_BUILT_IN;
        }
#endif

        my_setopt_enum(curl, CURLOPT_TIMECONDITION, (long)config->timecond);
        my_setopt(curl, CURLOPT_TIMEVALUE, (long)config->condtime);
        my_setopt_str(curl, CURLOPT_CUSTOMREQUEST, config->customrequest);
        customrequest_helper(config, config->httpreq, config->customrequest);
        my_setopt(curl, CURLOPT_STDERR, global->errors);

        /* three new ones in libcurl 7.3: */
        my_setopt_str(curl, CURLOPT_INTERFACE, config->iface);
        my_setopt_str(curl, CURLOPT_KRBLEVEL, config->krblevel);

        progressbarinit(&progressbar, config);
        if((global->progressmode == CURL_PROGRESS_BAR) &&
           !global->noprogress && !global->mute) {
          /* we want the alternative style, then we have to implement it
             ourselves! */
          my_setopt(curl, CURLOPT_XFERINFOFUNCTION, tool_progress_cb);
          my_setopt(curl, CURLOPT_XFERINFODATA, &progressbar);
        }

        /* new in libcurl 7.24.0: */
        if(config->dns_servers)
          my_setopt_str(curl, CURLOPT_DNS_SERVERS, config->dns_servers);

        /* new in libcurl 7.33.0: */
        if(config->dns_interface)
          my_setopt_str(curl, CURLOPT_DNS_INTERFACE, config->dns_interface);
        if(config->dns_ipv4_addr)
          my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP4, config->dns_ipv4_addr);
        if(config->dns_ipv6_addr)
        my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP6, config->dns_ipv6_addr);

        /* new in libcurl 7.6.2: */
        my_setopt_slist(curl, CURLOPT_TELNETOPTIONS, config->telnet_options);

        /* new in libcurl 7.7: */
        my_setopt_str(curl, CURLOPT_RANDOM_FILE, config->random_file);
        my_setopt_str(curl, CURLOPT_EGDSOCKET, config->egd_file);
        my_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
                  (long)(config->connecttimeout * 1000));

        if(config->cipher_list)
          my_setopt_str(curl, CURLOPT_SSL_CIPHER_LIST, config->cipher_list);

        /* new in libcurl 7.9.2: */
        if(config->disable_epsv)
          /* disable it */
          my_setopt(curl, CURLOPT_FTP_USE_EPSV, 0L);

        /* new in libcurl 7.10.5 */
        if(config->disable_eprt)
          /* disable it */
          my_setopt(curl, CURLOPT_FTP_USE_EPRT, 0L);

        if(global->tracetype != TRACE_NONE) {
          my_setopt(curl, CURLOPT_DEBUGFUNCTION, tool_debug_cb);
          my_setopt(curl, CURLOPT_DEBUGDATA, config);
          my_setopt(curl, CURLOPT_VERBOSE, 1L);
        }

        /* new in curl 7.9.3 */
        if(config->engine) {
          result = res_setopt_str(curl, CURLOPT_SSLENGINE, config->engine);
          if(result)
            goto show_error;
          my_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1L);
        }

        /* new in curl 7.10.7, extended in 7.19.4 but this only sets 0 or 1 */
        my_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS,
                  config->ftp_create_dirs?1L:0L);

        /* new in curl 7.10.8 */
        if(config->max_filesize)
          my_setopt(curl, CURLOPT_MAXFILESIZE_LARGE,
                    config->max_filesize);

        if(4 == config->ip_version)
          my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        else if(6 == config->ip_version)
          my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
        else
          my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);

        /* new in curl 7.15.5 */
        if(config->ftp_ssl_reqd)
          my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);

        /* new in curl 7.11.0 */
        else if(config->ftp_ssl)
          my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);

        /* new in curl 7.16.0 */
        else if(config->ftp_ssl_control)
          my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_CONTROL);

        /* new in curl 7.16.1 */
        if(config->ftp_ssl_ccc)
          my_setopt_enum(curl, CURLOPT_FTP_SSL_CCC,
                         (long)config->ftp_ssl_ccc_mode);

        /* new in curl 7.19.4 */
        if(config->socks5_gssapi_service)
          my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_SERVICE,
                        config->socks5_gssapi_service);

        /* new in curl 7.19.4 */
        if(config->socks5_gssapi_nec)
          my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_NEC,
                        config->socks5_gssapi_nec);

        /* new in curl 7.43.0 */
        if(config->proxy_service_name)
          my_setopt_str(curl, CURLOPT_PROXY_SERVICE_NAME,
                        config->proxy_service_name);

        /* new in curl 7.43.0 */
        if(config->service_name)
          my_setopt_str(curl, CURLOPT_SERVICE_NAME,
                        config->service_name);

        /* curl 7.13.0 */
        my_setopt_str(curl, CURLOPT_FTP_ACCOUNT, config->ftp_account);

        my_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, config->ignorecl?1L:0L);

        /* curl 7.14.2 */
        my_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, config->ftp_skip_ip?1L:0L);

        /* curl 7.15.1 */
        my_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long)config->ftp_filemethod);

        /* curl 7.15.2 */
        if(config->localport) {
          my_setopt(curl, CURLOPT_LOCALPORT, (long)config->localport);
          my_setopt_str(curl, CURLOPT_LOCALPORTRANGE,
                        (long)config->localportrange);
        }

        /* curl 7.15.5 */
        my_setopt_str(curl, CURLOPT_FTP_ALTERNATIVE_TO_USER,
                      config->ftp_alternative_to_user);

        /* curl 7.16.0 */
        if(config->disable_sessionid)
          /* disable it */
          my_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE, 0L);

        /* curl 7.16.2 */
        if(config->raw) {
          my_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 0L);
          my_setopt(curl, CURLOPT_HTTP_TRANSFER_DECODING, 0L);
        }

        /* curl 7.17.1 */
        if(!config->nokeepalive) {
          my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
          if(config->alivetime != 0) {
#if !defined(TCP_KEEPIDLE) || !defined(TCP_KEEPINTVL)
            warnf(config->global, "Keep-alive functionality somewhat crippled "
                "due to missing support in your operating system!\n");
#endif
            my_setopt(curl, CURLOPT_TCP_KEEPIDLE, config->alivetime);
            my_setopt(curl, CURLOPT_TCP_KEEPINTVL, config->alivetime);
          }
        }
        else
          my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 0L);

        /* curl 7.20.0 */
        if(config->tftp_blksize)
          my_setopt(curl, CURLOPT_TFTP_BLKSIZE, config->tftp_blksize);

        if(config->mail_from)
          my_setopt_str(curl, CURLOPT_MAIL_FROM, config->mail_from);

        if(config->mail_rcpt)
          my_setopt_slist(curl, CURLOPT_MAIL_RCPT, config->mail_rcpt);

        /* curl 7.20.x */
        if(config->ftp_pret)
          my_setopt(curl, CURLOPT_FTP_USE_PRET, 1L);

        if(config->proto_present)
          my_setopt_flags(curl, CURLOPT_PROTOCOLS, config->proto);
        if(config->proto_redir_present)
          my_setopt_flags(curl, CURLOPT_REDIR_PROTOCOLS, config->proto_redir);

        if(config->content_disposition
           && (urlnode->flags & GETOUT_USEREMOTE)
           && (checkprefix("http://", this_url) ||
               checkprefix("https://", this_url)))
          hdrcbdata.honor_cd_filename = TRUE;
        else
          hdrcbdata.honor_cd_filename = FALSE;

        hdrcbdata.outs = &outs;
        hdrcbdata.heads = &heads;

        my_setopt(curl, CURLOPT_HEADERFUNCTION, tool_header_cb);
        my_setopt(curl, CURLOPT_HEADERDATA, &hdrcbdata);

        if(config->resolve)
          /* new in 7.21.3 */
          my_setopt_slist(curl, CURLOPT_RESOLVE, config->resolve);

        /* new in 7.21.4 */
        if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) {
          if(config->tls_username)
            my_setopt_str(curl, CURLOPT_TLSAUTH_USERNAME,
                          config->tls_username);
          if(config->tls_password)
            my_setopt_str(curl, CURLOPT_TLSAUTH_PASSWORD,
                          config->tls_password);
          if(config->tls_authtype)
            my_setopt_str(curl, CURLOPT_TLSAUTH_TYPE,
                          config->tls_authtype);
        }

        /* new in 7.22.0 */
        if(config->gssapi_delegation)
          my_setopt_str(curl, CURLOPT_GSSAPI_DELEGATION,
                        config->gssapi_delegation);

        /* new in 7.25.0 and 7.44.0 */
        {
          long mask = (config->ssl_allow_beast ? CURLSSLOPT_ALLOW_BEAST : 0) |
                      (config->ssl_no_revoke ? CURLSSLOPT_NO_REVOKE : 0);
          if(mask)
            my_setopt_bitmask(curl, CURLOPT_SSL_OPTIONS, mask);
        }

        if(config->mail_auth)
          my_setopt_str(curl, CURLOPT_MAIL_AUTH, config->mail_auth);

        /* new in 7.31.0 */
        if(config->sasl_ir)
          my_setopt(curl, CURLOPT_SASL_IR, 1L);

        if(config->nonpn) {
          my_setopt(curl, CURLOPT_SSL_ENABLE_NPN, 0L);
        }

        if(config->noalpn) {
          my_setopt(curl, CURLOPT_SSL_ENABLE_ALPN, 0L);
        }

        /* new in 7.40.0 */
        if(config->unix_socket_path)
          my_setopt_str(curl, CURLOPT_UNIX_SOCKET_PATH,
                        config->unix_socket_path);

        /* new in 7.45.0 */
        if(config->proto_default)
          my_setopt_str(curl, CURLOPT_DEFAULT_PROTOCOL, config->proto_default);

        /* initialize retry vars for loop below */
        retry_sleep_default = (config->retry_delay) ?
          config->retry_delay*1000L : RETRY_SLEEP_DEFAULT; /* ms */

        retry_numretries = config->req_retry;
        retry_sleep = retry_sleep_default; /* ms */
        retrystart = tvnow();

#ifndef CURL_DISABLE_LIBCURL_OPTION
        result = easysrc_perform();
        if(result) {
          goto show_error;
        }
#endif

        for(;;) {
#ifdef USE_METALINK
          if(!metalink && config->use_metalink) {
            /* If outs.metalink_parser is non-NULL, delete it first. */
            if(outs.metalink_parser)
              metalink_parser_context_delete(outs.metalink_parser);
            outs.metalink_parser = metalink_parser_context_new();
            if(outs.metalink_parser == NULL) {
              result = CURLE_OUT_OF_MEMORY;
              goto show_error;
            }
            fprintf(config->global->errors,
                    "Metalink: parsing (%s) metalink/XML...\n", this_url);
          }
          else if(metalink)
            fprintf(config->global->errors,
                    "Metalink: fetching (%s) from (%s)...\n",
                    mlfile->filename, this_url);
#endif /* USE_METALINK */

#ifdef CURLDEBUG
          if(config->test_event_based)
            result = curl_easy_perform_ev(curl);
          else
#endif
          result = curl_easy_perform(curl);

          if(!result && !outs.stream && !outs.bytes) {
            /* we have received no data despite the transfer was successful
               ==> force cration of an empty output file (if an output file
               was specified) */
            long cond_unmet = 0L;
            /* do not create (or even overwrite) the file in case we get no
               data because of unmet condition */
            curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &cond_unmet);
            if(!cond_unmet && !tool_create_output_file(&outs))
              result = CURLE_WRITE_ERROR;
          }

          if(outs.is_cd_filename && outs.stream && !global->mute &&
             outs.filename)
            printf("curl: Saved to filename '%s'\n", outs.filename);

          /* if retry-max-time is non-zero, make sure we haven't exceeded the
             time */
          if(retry_numretries &&
             (!config->retry_maxtime ||
              (tvdiff(tvnow(), retrystart) <
               config->retry_maxtime*1000L)) ) {
            enum {
              RETRY_NO,
              RETRY_TIMEOUT,
              RETRY_HTTP,
              RETRY_FTP,
              RETRY_LAST /* not used */
            } retry = RETRY_NO;
            long response;
            if((CURLE_OPERATION_TIMEDOUT == result) ||
               (CURLE_COULDNT_RESOLVE_HOST == result) ||
               (CURLE_COULDNT_RESOLVE_PROXY == result) ||
               (CURLE_FTP_ACCEPT_TIMEOUT == result))
              /* retry timeout always */
              retry = RETRY_TIMEOUT;
            else if((CURLE_OK == result) ||
                    (config->failonerror &&
                     (CURLE_HTTP_RETURNED_ERROR == result))) {
              /* If it returned OK. _or_ failonerror was enabled and it
                 returned due to such an error, check for HTTP transient
                 errors to retry on. */
              char *effective_url = NULL;
              curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
              if(effective_url &&
                 checkprefix("http", effective_url)) {
                /* This was HTTP(S) */
                curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);

                switch(response) {
                case 500: /* Internal Server Error */
                case 502: /* Bad Gateway */
                case 503: /* Service Unavailable */
                case 504: /* Gateway Timeout */
                  retry = RETRY_HTTP;
                  /*
                   * At this point, we have already written data to the output
                   * file (or terminal). If we write to a file, we must rewind
                   * or close/re-open the file so that the next attempt starts
                   * over from the beginning.
                   *
                   * TODO: similar action for the upload case. We might need
                   * to start over reading from a previous point if we have
                   * uploaded something when this was returned.
                   */
                  break;
                }
              }
            } /* if CURLE_OK */
            else if(result) {
              curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);

              if(response/100 == 4)
                /*
                 * This is typically when the FTP server only allows a certain
                 * amount of users and we are not one of them.  All 4xx codes
                 * are transient.
                 */
                retry = RETRY_FTP;
            }

            if(retry) {
              static const char * const m[]={
                NULL, "timeout", "HTTP error", "FTP error"
              };

              warnf(config->global, "Transient problem: %s "
                    "Will retry in %ld seconds. "
                    "%ld retries left.\n",
                    m[retry], retry_sleep/1000L, retry_numretries);

              tool_go_sleep(retry_sleep);
              retry_numretries--;
              if(!config->retry_delay) {
                retry_sleep *= 2;
                if(retry_sleep > RETRY_SLEEP_MAX)
                  retry_sleep = RETRY_SLEEP_MAX;
              }
              if(outs.bytes && outs.filename && outs.stream) {
                /* We have written data to a output file, we truncate file
                 */
                if(!global->mute)
                  fprintf(global->errors, "Throwing away %"
                          CURL_FORMAT_CURL_OFF_T " bytes\n",
                          outs.bytes);
                fflush(outs.stream);
                /* truncate file at the position where we started appending */
#ifdef HAVE_FTRUNCATE
                if(ftruncate( fileno(outs.stream), outs.init)) {
                  /* when truncate fails, we can't just append as then we'll
                     create something strange, bail out */
                  if(!global->mute)
                    fprintf(global->errors,
                            "failed to truncate, exiting\n");
                  result = CURLE_WRITE_ERROR;
                  goto quit_urls;
                }
                /* now seek to the end of the file, the position where we
                   just truncated the file in a large file-safe way */
                fseek(outs.stream, 0, SEEK_END);
#else
                /* ftruncate is not available, so just reposition the file
                   to the location we would have truncated it. This won't
                   work properly with large files on 32-bit systems, but
                   most of those will have ftruncate. */
                fseek(outs.stream, (long)outs.init, SEEK_SET);
#endif
                outs.bytes = 0; /* clear for next round */
              }
              continue; /* curl_easy_perform loop */
            }
          } /* if retry_numretries */
          else if(metalink) {
            /* Metalink: Decide to try the next resource or
               not. Basically, we want to try the next resource if
               download was not successful. */
            long response;
            if(CURLE_OK == result) {
              /* TODO We want to try next resource when download was
                 not successful. How to know that? */
              char *effective_url = NULL;
              curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
              if(effective_url &&
                 curlx_strnequal(effective_url, "http", 4)) {
                /* This was HTTP(S) */
                curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
                if(response != 200 && response != 206) {
                  metalink_next_res = 1;
                  fprintf(global->errors,
                          "Metalink: fetching (%s) from (%s) FAILED "
                          "(HTTP status code %d)\n",
                          mlfile->filename, this_url, response);
                }
              }
            }
            else {
              metalink_next_res = 1;
              fprintf(global->errors,
                      "Metalink: fetching (%s) from (%s) FAILED (%s)\n",
                      mlfile->filename, this_url,
                      (errorbuffer[0]) ?
                      errorbuffer : curl_easy_strerror(result));
            }
          }
          if(metalink && !metalink_next_res)
            fprintf(global->errors, "Metalink: fetching (%s) from (%s) OK\n",
                    mlfile->filename, this_url);

          /* In all ordinary cases, just break out of loop here */
          break; /* curl_easy_perform loop */

        }

        if((global->progressmode == CURL_PROGRESS_BAR) &&
           progressbar.calls)
          /* if the custom progress bar has been displayed, we output a
             newline here */
          fputs("\n", progressbar.out);

        if(config->writeout)
          ourWriteOut(curl, &outs, config->writeout);

        if(config->writeenv)
          ourWriteEnv(curl);

        /*
        ** Code within this loop may jump directly here to label 'show_error'
        ** in order to display an error message for CURLcode stored in 'res'
        ** variable and exit loop once that necessary writing and cleanup
        ** in label 'quit_urls' has been done.
        */

        show_error:

#ifdef __VMS
        if(is_vms_shell()) {
          /* VMS DCL shell behavior */
          if(!global->showerror)
            vms_show = VMSSTS_HIDE;
        }
        else
#endif
        if(result && global->showerror) {
          fprintf(global->errors, "curl: (%d) %s\n", result, (errorbuffer[0]) ?
                  errorbuffer : curl_easy_strerror(result));
          if(result == CURLE_SSL_CACERT)
            fprintf(global->errors, "%s%s",
                    CURL_CA_CERT_ERRORMSG1, CURL_CA_CERT_ERRORMSG2);
        }

        /* Fall through comment to 'quit_urls' label */

        /*
        ** Upon error condition and always that a message has already been
        ** displayed, code within this loop may jump directly here to label
        ** 'quit_urls' otherwise it should jump to 'show_error' label above.
        **
        ** When 'res' variable is _not_ CURLE_OK loop will exit once that
        ** all code following 'quit_urls' has been executed. Otherwise it
        ** will loop to the beginning from where it may exit if there are
        ** no more urls left.
        */

        quit_urls:

        /* Set file extended attributes */
        if(!result && config->xattr && outs.fopened && outs.stream) {
          int rc = fwrite_xattr(curl, fileno(outs.stream));
          if(rc)
            warnf(config->global, "Error setting extended attributes: %s\n",
                  strerror(errno));
        }

        /* Close the file */
        if(outs.fopened && outs.stream) {
          int rc = fclose(outs.stream);
          if(!result && rc) {
            /* something went wrong in the writing process */
            result = CURLE_WRITE_ERROR;
            fprintf(global->errors, "(%d) Failed writing body\n", result);
          }
        }
        else if(!outs.s_isreg && outs.stream) {
          /* Dump standard stream buffered data */
          int rc = fflush(outs.stream);
          if(!result && rc) {
            /* something went wrong in the writing process */
            result = CURLE_WRITE_ERROR;
            fprintf(global->errors, "(%d) Failed writing body\n", result);
          }
        }

#ifdef __AMIGA__
        if(!result && outs.s_isreg && outs.filename) {
          /* Set the url (up to 80 chars) as comment for the file */
          if(strlen(url) > 78)
            url[79] = '\0';
          SetComment(outs.filename, url);
        }
#endif

#ifdef HAVE_UTIME
        /* File time can only be set _after_ the file has been closed */
        if(!result && config->remote_time && outs.s_isreg && outs.filename) {
          /* Ask libcurl if we got a remote file time */
          long filetime = -1;
          curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
          if(filetime >= 0) {
            struct utimbuf times;
            times.actime = (time_t)filetime;
            times.modtime = (time_t)filetime;
            utime(outs.filename, &times); /* set the time we got */
          }
        }
#endif

#ifdef USE_METALINK
        if(!metalink && config->use_metalink && result == CURLE_OK) {
          int rv = parse_metalink(config, &outs, this_url);
          if(rv == 0)
            fprintf(config->global->errors, "Metalink: parsing (%s) OK\n",
                    this_url);
          else if(rv == -1)
            fprintf(config->global->errors, "Metalink: parsing (%s) FAILED\n",
                    this_url);
        }
        else if(metalink && result == CURLE_OK && !metalink_next_res) {
          int rv = metalink_check_hash(global, mlfile, outs.filename);
          if(rv == 0) {
            metalink_next_res = 1;
          }
        }
#endif /* USE_METALINK */

        /* No more business with this output struct */
        if(outs.alloc_filename)
          Curl_safefree(outs.filename);
#ifdef USE_METALINK
        if(outs.metalink_parser)
          metalink_parser_context_delete(outs.metalink_parser);
#endif /* USE_METALINK */
        memset(&outs, 0, sizeof(struct OutStruct));
        hdrcbdata.outs = NULL;

        /* Free loop-local allocated memory and close loop-local opened fd */

        Curl_safefree(outfile);
        Curl_safefree(this_url);

        if(infdopen)
          close(infd);

        if(metalink) {
          /* Should exit if error is fatal. */
          if(is_fatal_error(result)) {
            break;
          }
          if(!metalink_next_res)
            break;
          mlres = mlres->next;
          if(mlres == NULL)
            /* TODO If metalink_next_res is 1 and mlres is NULL,
             * set res to error code
             */
            break;
        }
        else
        if(urlnum > 1) {
          /* when url globbing, exit loop upon critical error */
          if(is_fatal_error(result))
            break;
        }
        else if(result)
          /* when not url globbing, exit loop upon any error */
          break;

      } /* loop to the next URL */

      /* Free loop-local allocated memory */

      Curl_safefree(uploadfile);

      if(urls) {
        /* Free list of remaining URLs */
        glob_cleanup(urls);
        urls = NULL;
      }

      if(infilenum > 1) {
        /* when file globbing, exit loop upon critical error */
        if(is_fatal_error(result))
          break;
      }
      else if(result)
        /* when not file globbing, exit loop upon any error */
        break;

    } /* loop to the next globbed upload file */

    /* Free loop-local allocated memory */

    Curl_safefree(outfiles);

    if(inglob) {
      /* Free list of globbed upload files */
      glob_cleanup(inglob);
      inglob = NULL;
    }

    /* Free this URL node data without destroying the
       the node itself nor modifying next pointer. */
    Curl_safefree(urlnode->url);
    Curl_safefree(urlnode->outfile);
    Curl_safefree(urlnode->infile);
    urlnode->flags = 0;

    /*
    ** Bail out upon critical errors
    */
    if(is_fatal_error(result))
      goto quit_curl;

  } /* for-loop through all URLs */

  /*
  ** Nested loops end here.
  */

  quit_curl:

  /* Reset the global config variables */
  global->noprogress = orig_noprogress;
  global->isatty = orig_isatty;

  /* Free function-local referenced allocated memory */
  Curl_safefree(httpgetfields);

  /* Free list of given URLs */
  clean_getout(config);

  hdrcbdata.heads = NULL;

  /* Close function-local opened file descriptors */
  if(heads.fopened && heads.stream)
    fclose(heads.stream);

  if(heads.alloc_filename)
    Curl_safefree(heads.filename);

  /* Release metalink related resources here */
  clean_metalink(config);

  return result;
}


static void clean_getout(struct Configurable *config)
{
  struct getout *node=config->url_list;
  struct getout *next;

  while(node) {
    next = node->next;
    if(node->url)
      free(node->url);
    if(node->outfile)
      free(node->outfile);
    if(node->infile)
      free(node->infile);
    free(node);

    node = next; /* GOTO next */
  }
}


static const char *param2text(int res)
{
  ParameterError error = (ParameterError)res;
  switch(error) {
  case PARAM_GOT_EXTRA_PARAMETER:
    return "had unsupported trailing garbage";
  case PARAM_OPTION_UNKNOWN:
    return "is unknown";
  case PARAM_OPTION_AMBIGUOUS:
    return "is ambiguous";
  case PARAM_REQUIRES_PARAMETER:
    return "requires parameter";
  case PARAM_BAD_USE:
    return "is badly used here";
  case PARAM_BAD_NUMERIC:
    return "expected a proper numerical parameter";
  case PARAM_LIBCURL_DOESNT_SUPPORT:
    return "the installed libcurl version doesn't support this";
  case PARAM_NO_MEM:
    return "out of memory";
  default:
    return "unknown error";
  }
}


static void dumpeasycode(struct Configurable *config)
{
  struct curl_slist *ptr = easycode;
  char *o = config->libcurl;

  if(o) {
    FILE *out;
    bool fopened = FALSE;
    if(strcmp(o, "-")) {
      out = fopen(o, "wt");
      fopened = TRUE;
    }
    else
      out= stdout;
    if(!out)
      warnf(config, "Failed to open %s to write libcurl code!\n", o);
    else {
      int i;
      const char *c;

      for(i=0; (c = srchead[i]); i++) {
        if(!memcmp((char *)c, "[m]", 3)) {
#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS > 32)
          fprintf(out, "#define _FILE_OFFSET_BITS %d "
                  "/* for curl_off_t magic */\n",
                  _FILE_OFFSET_BITS);
#endif
        }
        else
          fprintf(out, "%s\n", c);
      }

      while(ptr) {
        fprintf(out, "  %s\n", ptr->data);
        ptr = ptr->next;
      }
      fprintf(out,
              "}\n"
              "/* */\n");
      if(fopened)
        fclose(out);
    }
  }
  curl_slist_free_all(easycode);
}


char **__crt0_glob_function (char *arg)
{
  (void)arg;
  return (char**)0;
}


compresscontig(unsigned char* out, unsigned char* rgb, uint32 n)
{
	register int v, red = RED, green = GREEN, blue = BLUE;

	while (n-- > 0) {
		v = red*(*rgb++);
		v += green*(*rgb++);
		v += blue*(*rgb++);
		*out++ = v>>8;
	}
}


  virtual void handle_listing_chunk(RGWUserBuckets&& buckets) {
    /* The default implementation, used by e.g. S3, just generates a new
     * part of listing and sends it client immediately. Swift can behave
     * differently: when the reverse option is requested, all incoming
     * instances of RGWUserBuckets are buffered and finally reversed. */
    return send_response_data(buckets);
  }


uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }


void RGWGetClusterStat::execute()
{
  op_ret = this->store->get_rados_handle()->cluster_stat(stats_op);
}


RGWSetRequestPayment() : requester_pays(false) {}


void RGWInitMultipart::execute()
{
  bufferlist aclbl;
  map<string, bufferlist> attrs;
  rgw_obj obj;

  if (get_params() < 0)
    return;

  if (s->object.empty())
    return;

  policy.encode(aclbl);
  attrs[RGW_ATTR_ACL] = aclbl;

  populate_with_generic_attrs(s, attrs);

  /* select encryption mode */
  op_ret = prepare_encryption(attrs);
  if (op_ret != 0)
    return;

  op_ret = rgw_get_request_metadata(s->cct, s->info, attrs);
  if (op_ret < 0) {
    return;
  }

  do {
    char buf[33];
    gen_rand_alphanumeric(s->cct, buf, sizeof(buf) - 1);
    upload_id = MULTIPART_UPLOAD_ID_PREFIX; /* v2 upload id */
    upload_id.append(buf);

    string tmp_obj_name;
    RGWMPObj mp(s->object.name, upload_id);
    tmp_obj_name = mp.get_meta();

    obj.init_ns(s->bucket, tmp_obj_name, mp_ns);
    // the meta object will be indexed with 0 size, we c
    obj.set_in_extra_data(true);
    obj.index_hash_source = s->object.name;

    RGWRados::Object op_target(store, s->bucket_info, *static_cast<RGWObjectCtx *>(s->obj_ctx), obj);
    op_target.set_versioning_disabled(true); /* no versioning for multipart meta */

    RGWRados::Object::Write obj_op(&op_target);

    obj_op.meta.owner = s->owner.get_id();
    obj_op.meta.category = RGW_OBJ_CATEGORY_MULTIMETA;
    obj_op.meta.flags = PUT_OBJ_CREATE_EXCL;

    op_ret = obj_op.write_meta(0, 0, attrs);
  } while (op_ret == -EEXIST);
}


int RGWCopyObj::init_common()
{
  if (if_mod) {
    if (parse_time(if_mod, &mod_time) < 0) {
      op_ret = -EINVAL;
      return op_ret;
    }
    mod_ptr = &mod_time;
  }

  if (if_unmod) {
    if (parse_time(if_unmod, &unmod_time) < 0) {
      op_ret = -EINVAL;
      return op_ret;
    }
    unmod_ptr = &unmod_time;
  }

  bufferlist aclbl;
  dest_policy.encode(aclbl);
  emplace_attr(RGW_ATTR_ACL, std::move(aclbl));

  op_ret = rgw_get_request_metadata(s->cct, s->info, attrs);
  if (op_ret < 0) {
    return op_ret;
  }
  populate_with_generic_attrs(s, attrs);

  return 0;
}


void RGWPutACLs::execute()
{
  bufferlist bl;

  RGWAccessControlPolicy_S3 *policy = NULL;
  RGWACLXMLParser_S3 parser(s->cct);
  RGWAccessControlPolicy_S3 new_policy(s->cct);
  stringstream ss;
  char *new_data = NULL;
  rgw_obj obj;

  op_ret = 0; /* XXX redundant? */

  if (!parser.init()) {
    op_ret = -EINVAL;
    return;
  }

  RGWAccessControlPolicy* const existing_policy = \
    (s->object.empty() ? s->bucket_acl.get() : s->object_acl.get());

  owner = existing_policy->get_owner();

  op_ret = get_params();
  if (op_ret < 0) {
    if (op_ret == -ERANGE) {
      ldout(s->cct, 4) << "The size of request xml data is larger than the max limitation, data size = "
                       << s->length << dendl;
      op_ret = -ERR_MALFORMED_XML;
      s->err.message = "The XML you provided was larger than the maximum " +
                       std::to_string(s->cct->_conf->rgw_max_put_param_size) +
                       " bytes allowed.";
    }
    return;
  }

  ldout(s->cct, 15) << "read len=" << len << " data=" << (data ? data : "") << dendl;

  if (!s->canned_acl.empty() && len) {
    op_ret = -EINVAL;
    return;
  }

  if (!s->canned_acl.empty() || s->has_acl_header) {
    op_ret = get_policy_from_state(store, s, ss);
    if (op_ret < 0)
      return;

    new_data = strdup(ss.str().c_str());
    free(data);
    data = new_data;
    len = ss.str().size();
  }

  if (!parser.parse(data, len, 1)) {
    op_ret = -EINVAL;
    return;
  }
  policy = static_cast<RGWAccessControlPolicy_S3 *>(parser.find_first("AccessControlPolicy"));
  if (!policy) {
    op_ret = -EINVAL;
    return;
  }

  const RGWAccessControlList& req_acl = policy->get_acl();
  const multimap<string, ACLGrant>& req_grant_map = req_acl.get_grant_map();
#define ACL_GRANTS_MAX_NUM      100
  int max_num = s->cct->_conf->rgw_acl_grants_max_num;
  if (max_num < 0) {
    max_num = ACL_GRANTS_MAX_NUM;
  }

  int grants_num = req_grant_map.size();
  if (grants_num > max_num) {
    ldout(s->cct, 4) << "An acl can have up to "
                     << max_num
                     << " grants, request acl grants num: "
                     << grants_num << dendl;
    op_ret = -ERR_MALFORMED_ACL_ERROR;
    s->err.message = "The request is rejected, because the acl grants number you requested is larger than the maximum "
                     + std::to_string(max_num)
                     + " grants allowed in an acl.";
    return;
  }

  // forward bucket acl requests to meta master zone
  if (s->object.empty() && !store->is_meta_master()) {
    bufferlist in_data;
    // include acl data unless it was generated from a canned_acl
    if (s->canned_acl.empty()) {
      in_data.append(data, len);
    }
    op_ret = forward_request_to_master(s, NULL, store, in_data, NULL);
    if (op_ret < 0) {
      ldout(s->cct, 20) << __func__ << " forward_request_to_master returned ret=" << op_ret << dendl;
      return;
    }
  }

  if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
    ldout(s->cct, 15) << "Old AccessControlPolicy";
    policy->to_xml(*_dout);
    *_dout << dendl;
  }

  op_ret = policy->rebuild(store, &owner, new_policy);
  if (op_ret < 0)
    return;

  if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
    ldout(s->cct, 15) << "New AccessControlPolicy:";
    new_policy.to_xml(*_dout);
    *_dout << dendl;
  }

  new_policy.encode(bl);
  map<string, bufferlist> attrs;

  if (!s->object.empty()) {
    obj = rgw_obj(s->bucket, s->object);
    store->set_atomic(s->obj_ctx, obj);
    //if instance is empty, we should modify the latest object
    op_ret = modify_obj_attr(store, s, obj, RGW_ATTR_ACL, bl);
  } else {
    attrs = s->bucket_attrs;
    attrs[RGW_ATTR_ACL] = bl;
    op_ret = rgw_bucket_set_attrs(store, s->bucket_info, attrs, &s->bucket_info.objv_tracker);
  }
  if (op_ret == -ECANCELED) {
    op_ret = 0; /* lost a race, but it's ok because acls are immutable */
  }
}


  void operator()(const std::chrono::seconds v) const {
    out << v.count();
  }


static inline void encode_delete_at_attr(boost::optional<ceph::real_time> delete_at,
					map<string, bufferlist>& attrs)
{
  if (delete_at == boost::none) {
    return;
  }

  bufferlist delatbl;
  encode(*delete_at, delatbl);
  attrs[RGW_ATTR_DELETE_AT] = delatbl;
} /* encode_delete_at_attr */


virtual bool need_object_expiration() { return false; }


  uint32_t op_mask() override {
    return RGW_OP_TYPE_WRITE;
  }


RGWRESTMgr* RGWRESTMgr::get_resource_mgr(struct req_state* const s,
                                         const std::string& uri,
                                         std::string* const out_uri)
{
  *out_uri = uri;

  multimap<size_t, string>::reverse_iterator iter;

  for (iter = resources_by_size.rbegin(); iter != resources_by_size.rend(); ++iter) {
    string& resource = iter->second;
    if (uri.compare(0, iter->first, resource) == 0 &&
	(uri.size() == iter->first ||
	 uri[iter->first] == '/')) {
      std::string suffix = uri.substr(iter->first);
      return resource_mgrs[resource]->get_resource_mgr(s, suffix, out_uri);
    }
  }

  if (default_mgr) {
    return default_mgr->get_resource_mgr_as_default(s, uri, out_uri);
  }

  return this;
}


virtual bool supports_account_metadata() { return false; }


void RGWPutBucketPolicy::send_response()
{
  if (op_ret) {
    set_req_state_err(s, op_ret);
  }
  dump_errno(s);
  end_header(s);
}


RGWOpType get_type() override { return RGW_OP_PUT_METADATA_BUCKET; }


  virtual uint64_t get_default_max() const {
    return 1000;
  }


void RGWConfigBucketMetaSearch::execute()
{
  op_ret = get_params();
  if (op_ret < 0) {
    ldout(s->cct, 20) << "NOTICE: get_params() returned ret=" << op_ret << dendl;
    return;
  }

  s->bucket_info.mdsearch_config = mdsearch_config;

  op_ret = store->put_bucket_instance_info(s->bucket_info, false, real_time(), &s->bucket_attrs);
  if (op_ret < 0) {
    ldout(s->cct, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket.name << " returned err=" << op_ret << dendl;
    return;
  }
}


int RGWPutMetadataAccount::init_processing()
{
  /* First, go to the base class. At the time of writing the method was
   * responsible only for initializing the quota. This isn't necessary
   * here as we are touching metadata only. I'm putting this call only
   * for the future. */
  op_ret = RGWOp::init_processing();
  if (op_ret < 0) {
    return op_ret;
  }

  op_ret = get_params();
  if (op_ret < 0) {
    return op_ret;
  }

  op_ret = rgw_get_user_attrs_by_uid(store, s->user->user_id, orig_attrs,
                                     &acct_op_tracker);
  if (op_ret < 0) {
    return op_ret;
  }

  if (has_policy) {
    bufferlist acl_bl;
    policy.encode(acl_bl);
    attrs.emplace(RGW_ATTR_ACL, std::move(acl_bl));
  }

  op_ret = rgw_get_request_metadata(s->cct, s->info, attrs, false);
  if (op_ret < 0) {
    return op_ret;
  }
  prepare_add_del_attrs(orig_attrs, rmattr_names, attrs);
  populate_with_generic_attrs(s, attrs);

  /* Try extract the TempURL-related stuff now to allow verify_permission
   * evaluate whether we need FULL_CONTROL or not. */
  filter_out_temp_url(attrs, rmattr_names, temp_url_keys);

  /* The same with quota except a client needs to be reseller admin. */
  op_ret = filter_out_quota_info(attrs, rmattr_names, new_quota,
                                 &new_quota_extracted);
  if (op_ret < 0) {
    return op_ret;
  }

  return 0;
}


void RGWPutLC::pre_exec()
{
  rgw_bucket_object_pre_exec(s);
}


int RGWOp::read_bucket_cors()
{
  bufferlist bl;

  map<string, bufferlist>::iterator aiter = s->bucket_attrs.find(RGW_ATTR_CORS);
  if (aiter == s->bucket_attrs.end()) {
    ldout(s->cct, 20) << "no CORS configuration attr found" << dendl;
    cors_exist = false;
    return 0; /* no CORS configuration found */
  }

  cors_exist = true;

  bl = aiter->second;

  bufferlist::iterator iter = bl.begin();
  try {
    bucket_cors.decode(iter);
  } catch (buffer::error& err) {
    ldout(s->cct, 0) << "ERROR: could not decode policy, caught buffer::error" << dendl;
    return -EIO;
  }
  if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
    RGWCORSConfiguration_S3 *s3cors = static_cast<RGWCORSConfiguration_S3 *>(&bucket_cors);
    ldout(s->cct, 15) << "Read RGWCORSConfiguration";
    s3cors->to_xml(*_dout);
    *_dout << dendl;
  }
  return 0;
}


static inline void complete_etag(MD5& hash, string *etag)
{
  char etag_buf[CEPH_CRYPTO_MD5_DIGESTSIZE];
  char etag_buf_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 16];

  hash.Final((unsigned char *)etag_buf);
  buf_to_hex((const unsigned char *)etag_buf, CEPH_CRYPTO_MD5_DIGESTSIZE,
	    etag_buf_str);

  *etag = etag_buf_str;
} /* complete_etag */


int RGWBulkUploadOp::verify_permission()
{
  if (s->auth.identity->is_anonymous()) {
    return -EACCES;
  }

  if (! verify_user_permission(s, RGW_PERM_WRITE)) {
    return -EACCES;
  }

  if (s->user->user_id.tenant != s->bucket_tenant) {
    ldout(s->cct, 10) << "user cannot create a bucket in a different tenant"
                      << " (user_id.tenant=" << s->user->user_id.tenant
                      << " requested=" << s->bucket_tenant << ")"
                      << dendl;
    return -EACCES;
  }

  if (s->user->max_buckets < 0) {
    return -EPERM;
  }

  return 0;
}


void RGWPostObj::execute()
{
  RGWPutObjDataProcessor *filter = nullptr;
  boost::optional<RGWPutObj_Compress> compressor;
  CompressorRef plugin;
  char supplied_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];

  /* Read in the data from the POST form. */
  op_ret = get_params();
  if (op_ret < 0) {
    return;
  }

  op_ret = verify_params();
  if (op_ret < 0) {
    return;
  }

  if (s->iam_policy) {
    auto e = s->iam_policy->eval(s->env, *s->auth.identity,
				 rgw::IAM::s3PutObject,
				 rgw_obj(s->bucket, s->object));
    if (e == Effect::Deny) {
      op_ret = -EACCES;
      return;
    } else if (e == Effect::Pass && !verify_bucket_permission_no_policy(s, RGW_PERM_WRITE)) {
      op_ret = -EACCES;
      return;
    }
  } else if (!verify_bucket_permission_no_policy(s, RGW_PERM_WRITE)) {
    op_ret = -EACCES;
    return;
  }

  /* Start iteration over data fields. It's necessary as Swift's FormPost
   * is capable to handle multiple files in single form. */
  do {
    std::unique_ptr<RGWPutObjDataProcessor> encrypt;
    char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
    unsigned char m[CEPH_CRYPTO_MD5_DIGESTSIZE];
    MD5 hash;
    ceph::buffer::list bl, aclbl;
    int len = 0;

    op_ret = store->check_quota(s->bucket_owner.get_id(),
                                s->bucket,
                                user_quota,
                                bucket_quota,
                                s->content_length);
    if (op_ret < 0) {
      return;
    }

    op_ret = store->check_bucket_shards(s->bucket_info, s->bucket, bucket_quota);
    if (op_ret < 0) {
      return;
    }

    if (supplied_md5_b64) {
      char supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1];
      ldout(s->cct, 15) << "supplied_md5_b64=" << supplied_md5_b64 << dendl;
      op_ret = ceph_unarmor(supplied_md5_bin, &supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1],
                            supplied_md5_b64, supplied_md5_b64 + strlen(supplied_md5_b64));
      ldout(s->cct, 15) << "ceph_armor ret=" << op_ret << dendl;
      if (op_ret != CEPH_CRYPTO_MD5_DIGESTSIZE) {
        op_ret = -ERR_INVALID_DIGEST;
        return;
      }

      buf_to_hex((const unsigned char *)supplied_md5_bin, CEPH_CRYPTO_MD5_DIGESTSIZE, supplied_md5);
      ldout(s->cct, 15) << "supplied_md5=" << supplied_md5 << dendl;
    }

    RGWPutObjProcessor_Atomic processor(*static_cast<RGWObjectCtx *>(s->obj_ctx),
                                        s->bucket_info,
                                        s->bucket,
                                        get_current_filename(),
                                        /* part size */
                                        s->cct->_conf->rgw_obj_stripe_size,
                                        s->req_id,
                                        s->bucket_info.versioning_enabled());
    processor.set_olh_epoch(0);
    /* No filters by default. */
    filter = &processor;

    op_ret = processor.prepare(store, nullptr);
    if (op_ret < 0) {
      return;
    }

    op_ret = get_encrypt_filter(&encrypt, filter);
    if (op_ret < 0) {
      return;
    }
    if (encrypt != nullptr) {
      filter = encrypt.get();
    } else {
      const auto& compression_type = store->get_zone_params().get_compression_type(
          s->bucket_info.placement_rule);
      if (compression_type != "none") {
        plugin = Compressor::create(s->cct, compression_type);
        if (!plugin) {
          ldout(s->cct, 1) << "Cannot load plugin for compression type "
                           << compression_type << dendl;
        } else {
          compressor.emplace(s->cct, plugin, filter);
          filter = &*compressor;
        }
      }
    }

    bool again;
    do {
      ceph::bufferlist data;
      len = get_data(data, again);

      if (len < 0) {
        op_ret = len;
        return;
      }

      if (!len) {
        break;
      }

      hash.Update((const unsigned char *)data.c_str(), data.length());
      op_ret = put_data_and_throttle(filter, data, ofs, false);

      ofs += len;

      if (ofs > max_len) {
        op_ret = -ERR_TOO_LARGE;
        return;
      }
    } while (again);

    {
      bufferlist flush;
      op_ret = put_data_and_throttle(filter, flush, ofs, false);
    }

    if (len < min_len) {
      op_ret = -ERR_TOO_SMALL;
      return;
    }

    s->obj_size = ofs;

    op_ret = store->check_quota(s->bucket_owner.get_id(), s->bucket,
                                user_quota, bucket_quota, s->obj_size);
    if (op_ret < 0) {
      return;
    }

    op_ret = store->check_bucket_shards(s->bucket_info, s->bucket, bucket_quota);
    if (op_ret < 0) {
      return;
    }

    hash.Final(m);
    buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);

    etag = calc_md5;

    if (supplied_md5_b64 && strcmp(calc_md5, supplied_md5)) {
      op_ret = -ERR_BAD_DIGEST;
      return;
    }

    bl.append(etag.c_str(), etag.size());
    emplace_attr(RGW_ATTR_ETAG, std::move(bl));

    policy.encode(aclbl);
    emplace_attr(RGW_ATTR_ACL, std::move(aclbl));

    const std::string content_type = get_current_content_type();
    if (! content_type.empty()) {
      ceph::bufferlist ct_bl;
      ct_bl.append(content_type.c_str(), content_type.size() + 1);
      emplace_attr(RGW_ATTR_CONTENT_TYPE, std::move(ct_bl));
    }

    if (compressor && compressor->is_compressed()) {
      ceph::bufferlist tmp;
      RGWCompressionInfo cs_info;
      cs_info.compression_type = plugin->get_type_name();
      cs_info.orig_size = s->obj_size;
      cs_info.blocks = move(compressor->get_compression_blocks());
      encode(cs_info, tmp);
      emplace_attr(RGW_ATTR_COMPRESSION, std::move(tmp));
    }

    op_ret = processor.complete(s->obj_size, etag, nullptr, real_time(),
                                attrs, (delete_at ? *delete_at : real_time()));
  } while (is_next_file_to_upload());
}


void rgw_add_to_iam_environment(rgw::IAM::Environment& e, std::string_view key, std::string_view val){
  // This variant just adds non empty key pairs to IAM env., values can be empty
  // in certain cases like tagging
  if (!key.empty())
    e.emplace(key,val);
}


void RGWSetBucketWebsite::pre_exec()
{
  rgw_bucket_object_pre_exec(s);
}


RGWOpType get_type() override { return RGW_OP_GET_BUCKET_LOGGING; }


  virtual int get_decrypt_filter(std::unique_ptr<RGWGetObj_Filter>* filter,
                                 RGWGetObj_Filter* cb,
                                 map<string, bufferlist>& attrs,
                                 bufferlist* manifest_bl) {
    *filter = nullptr;
    return 0;
  }


int RGWPutMetadataBucket::verify_permission()
{
  if (!verify_bucket_permission_no_policy(s, RGW_PERM_WRITE)) {
    return -EACCES;
  }

  return 0;
}


RGWOpType get_type() override { return RGW_OP_DELETE_CORS; }


void RGWGetCORS::execute()
{
  op_ret = read_bucket_cors();
  if (op_ret < 0)
    return ;

  if (!cors_exist) {
    dout(2) << "No CORS configuration set yet for this bucket" << dendl;
    op_ret = -ENOENT;
    return;
  }
}


int RGWPutBucketPolicy::verify_permission()
{
  if (!verify_bucket_permission(s, rgw::IAM::s3PutBucketPolicy)) {
    return -EACCES;
  }

  return 0;
}


int RGWHandler_REST::read_permissions(RGWOp* op_obj)
{
  bool only_bucket = false;

  switch (s->op) {
  case OP_HEAD:
  case OP_GET:
    only_bucket = false;
    break;
  case OP_PUT:
  case OP_POST:
  case OP_COPY:
    /* is it a 'multi-object delete' request? */
    if (s->info.args.exists("delete")) {
      only_bucket = true;
      break;
    }
    if (is_obj_update_op()) {
      only_bucket = false;
      break;
    }
    /* is it a 'create bucket' request? */
    if (op_obj->get_type() == RGW_OP_CREATE_BUCKET)
      return 0;
    only_bucket = true;
    break;
  case OP_DELETE:
    if (!s->info.args.exists("tagging")){
      only_bucket = true;
    }
    break;
  case OP_OPTIONS:
    only_bucket = true;
    break;
  default:
    return -EINVAL;
  }

  return do_read_permissions(op_obj, only_bucket);
}


  ~RGWPutLC() override {
    free(data);
  }


  void operator()(double v) const {
    out << std::fixed << v << std::defaultfloat;
  }


int RGWGetObj::verify_permission()
{
  obj = rgw_obj(s->bucket, s->object);
  store->set_atomic(s->obj_ctx, obj);
  if (get_data) {
    store->set_prefetch_data(s->obj_ctx, obj);
  }

  if (torrent.get_flag()) {
    if (obj.key.instance.empty()) {
      action = rgw::IAM::s3GetObjectTorrent;
    } else {
      action = rgw::IAM::s3GetObjectVersionTorrent;
    }
  } else {
    if (obj.key.instance.empty()) {
      action = rgw::IAM::s3GetObject;
    } else {
      action = rgw::IAM::s3GetObjectVersion;
    }
    if (s->iam_policy && s->iam_policy->has_partial_conditional(S3_EXISTING_OBJTAG))
      rgw_iam_add_existing_objtags(store, s, obj, action);
  }

  if (!verify_object_permission(s, action)) {
    return -EACCES;
  }

  return 0;
}


uint32_t op_mask() override { return RGW_OP_TYPE_READ; }


static int rgw_iam_add_existing_objtags(RGWRados* store, struct req_state* s, rgw_obj& obj, std::uint64_t action){
  map <string, bufferlist> attrs;
  store->set_atomic(s->obj_ctx, obj);
  int op_ret = get_obj_attrs(store, s, obj, attrs);
  if (op_ret < 0)
    return op_ret;
  auto tags = attrs.find(RGW_ATTR_TAGS);
  if (tags != attrs.end()){
    return rgw_iam_add_tags_from_bl(s, tags->second);
  }
  return 0;
}


void dump_errno(int http_ret, string& out) {
  stringstream ss;

  ss <<  http_ret << " " << http_status_names[http_ret];
  out = ss.str();
}


void abort_early(struct req_state *s, RGWOp* op, int err_no,
		RGWHandler* handler)
{
  string error_content("");
  if (!s->formatter) {
    s->formatter = new JSONFormatter;
    s->format = RGW_FORMAT_JSON;
  }

  // op->error_handler is responsible for calling it's handler error_handler
  if (op != NULL) {
    int new_err_no;
    new_err_no = op->error_handler(err_no, &error_content);
    ldout(s->cct, 20) << "op->ERRORHANDLER: err_no=" << err_no
		      << " new_err_no=" << new_err_no << dendl;
    err_no = new_err_no;
  } else if (handler != NULL) {
    int new_err_no;
    new_err_no = handler->error_handler(err_no, &error_content);
    ldout(s->cct, 20) << "handler->ERRORHANDLER: err_no=" << err_no
		      << " new_err_no=" << new_err_no << dendl;
    err_no = new_err_no;
  }

  // If the error handler(s) above dealt with it completely, they should have
  // returned 0. If non-zero, we need to continue here.
  if (err_no) {
    // Watch out, we might have a custom error state already set!
    if (!s->err.http_ret || s->err.http_ret == 200) {
      set_req_state_err(s, err_no);
    }

    if (s->err.http_ret == 404 && !s->redirect_zone_endpoint.empty()) {
      s->err.http_ret = 301;
      err_no = -ERR_PERMANENT_REDIRECT;
      build_redirect_url(s, s->redirect_zone_endpoint, &s->redirect);
    }

    dump_errno(s);
    dump_bucket_from_state(s);
    if (err_no == -ERR_PERMANENT_REDIRECT || err_no == -ERR_WEBSITE_REDIRECT) {
      string dest_uri;
      if (!s->redirect.empty()) {
        dest_uri = s->redirect;
      } else if (!s->zonegroup_endpoint.empty()) {
        build_redirect_url(s, s->zonegroup_endpoint, &dest_uri);
      }

      if (!dest_uri.empty()) {
        dump_redirect(s, dest_uri);
      }
    }

    if (!error_content.empty()) {
      /*
       * TODO we must add all error entries as headers here:
       * when having a working errordoc, then the s3 error fields are
       * rendered as HTTP headers, e.g.:
       *   x-amz-error-code: NoSuchKey
       *   x-amz-error-message: The specified key does not exist.
       *   x-amz-error-detail-Key: foo
       */
      end_header(s, op, NULL, error_content.size(), false, true);
      RESTFUL_IO(s)->send_body(error_content.c_str(), error_content.size());
    } else {
      end_header(s, op);
    }
  }
  perfcounter->inc(l_rgw_failed_req);
}


  const string name() override {
    return "get_health_check";
  }


void RGWGetHealthCheck::execute()
{
  if (!g_conf->rgw_healthcheck_disabling_path.empty() &&
      (::access(g_conf->rgw_healthcheck_disabling_path.c_str(), F_OK) == 0)) {
    /* Disabling path specified & existent in the filesystem. */
    op_ret = -ERR_SERVICE_UNAVAILABLE; /* 503 */
  } else {
    op_ret = 0; /* 200 OK */
  }
}


  virtual int flush() {
    if (next) {
      return next->flush();
    }
    return 0;
  }


int dump_body(struct req_state* const s, const std::string& str)
{
  return dump_body(s, str.c_str(), str.length());
}


  RGWOptionsCORS() : rule(NULL), origin(NULL),
                     req_hdrs(NULL), req_meth(NULL) {
  }


void rgw_flush_formatter_and_reset(struct req_state *s, Formatter *formatter)
{
  std::ostringstream oss;
  formatter->output_footer();
  formatter->flush(oss);
  std::string outs(oss.str());
  if (!outs.empty() && s->op != OP_HEAD) {
    dump_body(s, outs);
  }

  s->formatter->reset();
}


void RGWGetBucketWebsite::pre_exec()
{
  rgw_bucket_object_pre_exec(s);
}


    int unlock() {
      return lock.unlock(&ioctx, oid);
    }


  RGWDeleteMultiObj() {
    max_to_delete = 1000;
    len = 0;
    data = NULL;
    quiet = false;
    status_dumped = false;
  }


  virtual int get_encrypt_filter(std::unique_ptr<RGWPutObjDataProcessor> *filter, RGWPutObjDataProcessor* cb) {
    *filter = nullptr;
    return 0;
  }


int RGWPostObj::verify_permission()
{
  return 0;
}


void dump_errno(struct req_state *s, int http_ret)
{
  dump_status(s, http_ret, http_status_names[http_ret]);
}


bool RGWBulkDelete::Deleter::delete_single(const acct_path_t& path)
{
  auto& obj_ctx = *static_cast<RGWObjectCtx *>(s->obj_ctx);

  RGWBucketInfo binfo;
  map<string, bufferlist> battrs;
  ACLOwner bowner;

  int ret = store->get_bucket_info(obj_ctx, s->user->user_id.tenant,
                                   path.bucket_name, binfo, nullptr,
                                   &battrs);
  if (ret < 0) {
    goto binfo_fail;
  }

  if (!verify_permission(binfo, battrs, bowner)) {
    ret = -EACCES;
    goto auth_fail;
  }

  if (!path.obj_key.empty()) {
    rgw_obj obj(binfo.bucket, path.obj_key);
    obj_ctx.obj.set_atomic(obj);

    RGWRados::Object del_target(store, binfo, obj_ctx, obj);
    RGWRados::Object::Delete del_op(&del_target);

    del_op.params.bucket_owner = binfo.owner;
    del_op.params.versioning_status = binfo.versioning_status();
    del_op.params.obj_owner = bowner;

    ret = del_op.delete_obj();
    if (ret < 0) {
      goto delop_fail;
    }
  } else {
    RGWObjVersionTracker ot;
    ot.read_version = binfo.ep_objv;

    ret = store->delete_bucket(binfo, ot);
    if (0 == ret) {
      ret = rgw_unlink_bucket(store, binfo.owner, binfo.bucket.tenant,
                              binfo.bucket.name, false);
      if (ret < 0) {
        ldout(s->cct, 0) << "WARNING: failed to unlink bucket: ret=" << ret
                         << dendl;
      }
    }
    if (ret < 0) {
      goto delop_fail;
    }

    if (!store->is_meta_master()) {
      bufferlist in_data;
      ret = forward_request_to_master(s, &ot.read_version, store, in_data,
                                      nullptr);
      if (ret < 0) {
        if (ret == -ENOENT) {
          /* adjust error, we want to return with NoSuchBucket and not
           * NoSuchKey */
          ret = -ERR_NO_SUCH_BUCKET;
        }
        goto delop_fail;
      }
    }
  }

  num_deleted++;
  return true;

binfo_fail:
    if (-ENOENT == ret) {
      ldout(store->ctx(), 20) << "cannot find bucket = " << path.bucket_name << dendl;
      num_unfound++;
    } else {
      ldout(store->ctx(), 20) << "cannot get bucket info, ret = " << ret
                              << dendl;

      fail_desc_t failed_item = {
        .err  = ret,
        .path = path
      };
      failures.push_back(failed_item);
    }
    return false;

auth_fail:
    ldout(store->ctx(), 20) << "wrong auth for " << path << dendl;
    {
      fail_desc_t failed_item = {
        .err  = ret,
        .path = path
      };
      failures.push_back(failed_item);
    }
    return false;

delop_fail:
    if (-ENOENT == ret) {
      ldout(store->ctx(), 20) << "cannot find entry " << path << dendl;
      num_unfound++;
    } else {
      fail_desc_t failed_item = {
        .err  = ret,
        .path = path
      };
      failures.push_back(failed_item);
    }
    return false;
}


int RGWPostObj_ObjStore::get_params()
{
  if (s->expect_cont) {
    /* OK, here it really gets ugly. With POST, the params are embedded in the
     * request body, so we need to continue before being able to actually look
     * at them. This diverts from the usual request flow. */
    dump_continue(s);
    s->expect_cont = false;
  }

  std::string req_content_type_str = s->info.env->get("CONTENT_TYPE", "");
  std::string req_content_type;
  std::map<std::string, std::string> params;
  parse_boundary_params(req_content_type_str, req_content_type, params);

  if (req_content_type.compare("multipart/form-data") != 0) {
    err_msg = "Request Content-Type is not multipart/form-data";
    return -EINVAL;
  }

  if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
    ldout(s->cct, 20) << "request content_type_str="
		      << req_content_type_str << dendl;
    ldout(s->cct, 20) << "request content_type params:" << dendl;

    for (const auto& pair : params) {
      ldout(s->cct, 20) << " " << pair.first << " -> " << pair.second
			<< dendl;
    }
  }

  const auto iter = params.find("boundary");
  if (std::end(params) == iter) {
    err_msg = "Missing multipart boundary specification";
    return -EINVAL;
  }

  /* Create the boundary. */
  boundary = "--";
  boundary.append(iter->second);

  return 0;
}


int RGWListBucket::parse_max_keys()
{
  // Bound max value of max-keys to configured value for security
  // Bound min value of max-keys to '0'
  // Some S3 clients explicitly send max-keys=0 to detect if the bucket is
  // empty without listing any items.
  return parse_value_and_bound(max_keys, max, 0,
			s->cct->_conf->get_val<uint64_t>("rgw_max_listing_results"),
			default_max);
}


  void set_get_data(bool get_data) {
    this->get_data = get_data;
  }


static bool rgw_find_host_in_domains(const string& host, string *domain, string *subdomain, set<string> valid_hostnames_set)
{
  set<string>::iterator iter;
  /** TODO, Future optimization
   * store hostnames_set elements _reversed_, and look for a prefix match,
   * which is much faster than a suffix match.
   */
  for (iter = valid_hostnames_set.begin(); iter != valid_hostnames_set.end(); ++iter) {
    size_t pos;
    if (!str_ends_with(host, *iter, &pos))
      continue;

    if (pos == 0) {
      *domain = host;
      subdomain->clear();
    } else {
      if (host[pos - 1] != '.') {
	continue;
      }

      *domain = host.substr(pos);
      *subdomain = host.substr(0, pos - 1);
    }
    return true;
  }
  return false;
}


static int filter_out_quota_info(std::map<std::string, bufferlist>& add_attrs,
                                 const std::set<std::string>& rmattr_names,
                                 RGWQuotaInfo& quota,
                                 bool * quota_extracted = nullptr)
{
  bool extracted = false;

  /* Put new limit on max objects. */
  auto iter = add_attrs.find(RGW_ATTR_QUOTA_NOBJS);
  std::string err;
  if (std::end(add_attrs) != iter) {
    quota.max_objects =
      static_cast<int64_t>(strict_strtoll(iter->second.c_str(), 10, &err));
    if (!err.empty()) {
      return -EINVAL;
    }
    add_attrs.erase(iter);
    extracted = true;
  }

  /* Put new limit on bucket (container) size. */
  iter = add_attrs.find(RGW_ATTR_QUOTA_MSIZE);
  if (iter != add_attrs.end()) {
    quota.max_size =
      static_cast<int64_t>(strict_strtoll(iter->second.c_str(), 10, &err));
    if (!err.empty()) {
      return -EINVAL;
    }
    add_attrs.erase(iter);
    extracted = true;
  }

  for (const auto& name : rmattr_names) {
    /* Remove limit on max objects. */
    if (name.compare(RGW_ATTR_QUOTA_NOBJS) == 0) {
      quota.max_objects = -1;
      extracted = true;
    }

    /* Remove limit on max bucket size. */
    if (name.compare(RGW_ATTR_QUOTA_MSIZE) == 0) {
      quota.max_size = -1;
      extracted = true;
    }
  }

  /* Swift requries checking on raw usage instead of the 4 KiB rounded one. */
  quota.check_on_raw = true;
  quota.enabled = quota.max_size > 0 || quota.max_objects > 0;

  if (quota_extracted) {
    *quota_extracted = extracted;
  }

  return 0;
}


const string name() override { return "put_bucket_metadata"; }


const string name() override { return "set_bucket_website"; }


void RGWAbortMultipart::pre_exec()
{
  rgw_bucket_object_pre_exec(s);
}


int RGWPostObj_ObjStore::read_with_boundary(ceph::bufferlist& bl,
                                            uint64_t max,
                                            const bool check_crlf,
                                            bool& reached_boundary,
                                            bool& done)
{
  uint64_t cl = max + 2 + boundary.size();

  if (max > in_data.length()) {
    uint64_t need_to_read = cl - in_data.length();

    bufferptr bp(need_to_read);

    const auto read_len = recv_body(s, bp.c_str(), need_to_read);
    if (read_len < 0) {
      return read_len;
    }
    in_data.append(bp, 0, read_len);
  }

  done = false;
  int skip;
  const int index = index_of(in_data, cl, boundary, check_crlf,
                             reached_boundary, skip);
  if (index >= 0) {
    max = index;
  }

  if (max > in_data.length()) {
    max = in_data.length();
  }

  bl.substr_of(in_data, 0, max);

  ceph::bufferlist new_read_data;

  /*
   * now we need to skip boundary for next time, also skip any crlf, or
   * check to see if it's the last final boundary (marked with "--" at the end
   */
  if (reached_boundary) {
    int left = in_data.length() - max;
    if (left < skip + 2) {
      int need = skip + 2 - left;
      bufferptr boundary_bp(need);
      const int r = recv_body(s, boundary_bp.c_str(), need);
      if (r < 0) {
        return r;
      }
      in_data.append(boundary_bp);
    }
    max += skip; // skip boundary for next time
    if (in_data.length() >= max + 2) {
      const char *data = in_data.c_str();
      if (is_crlf(data + max)) {
	max += 2;
      } else {
	if (*(data + max) == '-' &&
	    *(data + max + 1) == '-') {
	  done = true;
	  max += 2;
	}
      }
    }
  }

  new_read_data.substr_of(in_data, max, in_data.length() - max);
  in_data = new_read_data;

  return 0;
}


RGWOpType get_type() override { return RGW_OP_OPTIONS_CORS; }


  AlignedStreamGetter(const size_t position,
                      const size_t length,
                      const size_t alignment,
                      U&& decoratee)
    : DecoratedStreamGetter(std::forward<U>(decoratee)),
      position(position),
      length(length),
      alignment(alignment) {
  }


int RGWCompleteMultipart::verify_permission()
{
  if (s->iam_policy) {
    auto e = s->iam_policy->eval(s->env, *s->auth.identity,
				 rgw::IAM::s3PutObject,
				 rgw_obj(s->bucket, s->object));
    if (e == Effect::Allow) {
      return 0;
    } else if (e == Effect::Deny) {
      return -EACCES;
    }
  }

  if (!verify_bucket_permission_no_policy(s, RGW_PERM_WRITE)) {
    return -EACCES;
  }

  return 0;
}


void dump_header(struct req_state* const s,
                 const boost::string_ref& name,
                 const long long val)
{
  char buf[32];
  const auto len = snprintf(buf, sizeof(buf), "%lld", val);

  return dump_header(s, name, boost::string_ref(buf, len));
}


void RGWPostObj_ObjStore::parse_boundary_params(const std::string& params_str,
                                                std::string& first,
                                                std::map<std::string,
                                                std::string>& params)
{
  size_t pos = params_str.find(';');
  if (std::string::npos == pos) {
    first = rgw_trim_whitespace(params_str);
    return;
  }

  first = rgw_trim_whitespace(params_str.substr(0, pos));
  pos++;

  while (pos < params_str.size()) {
    size_t end = params_str.find(';', pos);
    if (std::string::npos == end) {
      end = params_str.size();
    }

    std::string param = params_str.substr(pos, end - pos);
    size_t eqpos = param.find('=');

    if (std::string::npos != eqpos) {
      std::string param_name = rgw_trim_whitespace(param.substr(0, eqpos));
      std::string val = rgw_trim_quotes(param.substr(eqpos + 1));
      params[std::move(param_name)] = std::move(val);
    } else {
      params[rgw_trim_whitespace(param)] = "";
    }

    pos = end + 1;
  }
}


  virtual int retarget(RGWOp* op, RGWOp** new_op) {
    *new_op = op;
    return 0;
  }


int RGWCompleteMultipart_ObjStore::get_params()
{
  upload_id = s->info.args.get("uploadId");

  if (upload_id.empty()) {
    op_ret = -ENOTSUP;
    return op_ret;
  }

#define COMPLETE_MULTIPART_MAX_LEN (1024 * 1024) /* api defines max 10,000 parts, this should be enough */
  op_ret = rgw_rest_read_all_input(s, &data, &len, COMPLETE_MULTIPART_MAX_LEN);
  if (op_ret < 0)
    return op_ret;

  return 0;
}


static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf,
			struct page *page, gfp_t gfp)
{
	struct vm_area_struct *vma = vmf->vma;
	struct mem_cgroup *memcg;
	pgtable_t pgtable;
	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
	vm_fault_t ret = 0;

	VM_BUG_ON_PAGE(!PageCompound(page), page);

	if (mem_cgroup_try_charge_delay(page, vma->vm_mm, gfp, &memcg, true)) {
		put_page(page);
		count_vm_event(THP_FAULT_FALLBACK);
		return VM_FAULT_FALLBACK;
	}

	pgtable = pte_alloc_one(vma->vm_mm, haddr);
	if (unlikely(!pgtable)) {
		ret = VM_FAULT_OOM;
		goto release;
	}

	clear_huge_page(page, vmf->address, HPAGE_PMD_NR);
	/*
	 * The memory barrier inside __SetPageUptodate makes sure that
	 * clear_huge_page writes become visible before the set_pmd_at()
	 * write.
	 */
	__SetPageUptodate(page);

	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
	if (unlikely(!pmd_none(*vmf->pmd))) {
		goto unlock_release;
	} else {
		pmd_t entry;

		ret = check_stable_address_space(vma->vm_mm);
		if (ret)
			goto unlock_release;

		/* Deliver the page fault to userland */
		if (userfaultfd_missing(vma)) {
			vm_fault_t ret2;

			spin_unlock(vmf->ptl);
			mem_cgroup_cancel_charge(page, memcg, true);
			put_page(page);
			pte_free(vma->vm_mm, pgtable);
			ret2 = handle_userfault(vmf, VM_UFFD_MISSING);
			VM_BUG_ON(ret2 & VM_FAULT_FALLBACK);
			return ret2;
		}

		entry = mk_huge_pmd(page, vma->vm_page_prot);
		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
		page_add_new_anon_rmap(page, vma, haddr, true);
		mem_cgroup_commit_charge(page, memcg, false, true);
		lru_cache_add_active_or_unevictable(page, vma);
		pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable);
		set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
		add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR);
		mm_inc_nr_ptes(vma->vm_mm);
		spin_unlock(vmf->ptl);
		count_vm_event(THP_FAULT_ALLOC);
	}

	return 0;
unlock_release:
	spin_unlock(vmf->ptl);
release:
	if (pgtable)
		pte_free(vma->vm_mm, pgtable);
	mem_cgroup_cancel_charge(page, memcg, true);
	put_page(page);
	return ret;

}