]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib-http: http_client_request_add_header() - Replace existing header
authorTimo Sirainen <timo.sirainen@open-xchange.com>
Mon, 27 May 2019 14:47:16 +0000 (17:47 +0300)
committerMartti Rannanjärvi <martti.rannanjarvi@open-xchange.com>
Tue, 11 Jun 2019 10:49:11 +0000 (13:49 +0300)
If header with the same key already exists, just replace the value.
HTTP supports having multiple headers with the same key only when they
can be rewritten into a single comma-separated header. So practically
there's no reason for lib-http to need to support adding multiple
headers. Replacing an existing value is more useful generally.

src/lib-http/http-client-request.c
src/lib-http/http-client.h

index e50d0d551575bce4bd25c300059bdc632dc55b9c..6847b327b0823e3cc00850559a0cbf9c7f01c1cf 100644 (file)
@@ -364,6 +364,8 @@ http_client_request_lookup_header_pos(struct http_client_request *req,
 void http_client_request_add_header(struct http_client_request *req,
                                    const char *key, const char *value)
 {
+       size_t key_pos, value_pos, next_pos;
+
        i_assert(req->state == HTTP_REQUEST_STATE_NEW ||
                 /* allow calling for retries */
                 req->state == HTTP_REQUEST_STATE_GOT_RESPONSE ||
@@ -410,7 +412,14 @@ void http_client_request_add_header(struct http_client_request *req,
        }
        if (req->headers == NULL)
                req->headers = str_new(default_pool, 256);
-       str_printfa(req->headers, "%s: %s\r\n", key, value);
+       if (!http_client_request_lookup_header_pos(req, key, &key_pos,
+                                                  &value_pos, &next_pos))
+               str_printfa(req->headers, "%s: %s\r\n", key, value);
+       else {
+               /* don't delete CRLF */
+               size_t old_value_len = next_pos - value_pos - 2;
+               str_replace(req->headers, value_pos, old_value_len, value);
+       }
 }
 
 void http_client_request_remove_header(struct http_client_request *req,
index bc63cc1bf9afab34095251b341a0312662794776..74733502a7e780fe19d80a312396862513f68ea6 100644 (file)
@@ -280,7 +280,8 @@ void http_client_request_set_urgent(struct http_client_request *req);
 void http_client_request_set_preserve_exact_reason(struct http_client_request *req);
 
 /* add a custom header to the request. This can override headers that are
-   otherwise created implicitly. */
+   otherwise created implicitly. If the same header key was already added,
+   the value is replaced. */
 void http_client_request_add_header(struct http_client_request *req,
                                    const char *key, const char *value);
 /* remove a header added earlier. This has no influence on implicitly created