2.74 xs_curl.h
  1/* copyright (c) 2022 - 2025 grunfink et al. / MIT license */
  2
  3#ifndef _XS_CURL_H
  4
  5#define _XS_CURL_H
  6
  7xs_dict *xs_http_request(const char *method, const char *url,
  8                        const xs_dict *headers,
  9                        const xs_str *body, int b_size, int *status,
 10                        xs_str **payload, int *p_size, int timeout);
 11
 12const char *xs_curl_strerr(int errnum);
 13
 14#ifdef XS_IMPLEMENTATION
 15
 16#include <curl/curl.h>
 17
 18static size_t _header_callback(char *buffer, size_t size,
 19                               size_t nitems, xs_dict **userdata)
 20{
 21    xs_dict *headers = *userdata;
 22    xs *l;
 23
 24    /* get the line */
 25    l = xs_str_new(NULL);
 26    l = xs_append_m(l, buffer, size * nitems);
 27    l = xs_strip_i(l);
 28
 29    /* only the HTTP/x 200 line and the last one doesn't have ': ' */
 30    if (xs_str_in(l, ": ") != -1) {
 31        xs *knv = xs_split_n(l, ": ", 1);
 32
 33        xs_tolower_i((xs_str *)xs_list_get(knv, 0));
 34
 35        headers = xs_dict_set(headers, xs_list_get(knv, 0), xs_list_get(knv, 1));
 36    }
 37    else
 38    if (xs_startswith(l, "HTTP/"))
 39        headers = xs_dict_set(headers, "_proto", l);
 40
 41    *userdata = headers;
 42
 43    return nitems * size;
 44}
 45
 46
 47struct _payload_data {
 48    char *data;
 49    int size;
 50    int offset;
 51};
 52
 53static int _data_callback(void *buffer, size_t size,
 54                          size_t nitems, struct _payload_data *pd)
 55{
 56    int sz = size * nitems;
 57
 58    /* open space */
 59    pd->size += sz;
 60    pd->data = xs_realloc(pd->data, _xs_blk_size(pd->size + 1));
 61
 62    /* copy data */
 63    memcpy(pd->data + pd->offset, buffer, sz);
 64    pd->offset += sz;
 65
 66    return sz;
 67}
 68
 69
 70static int _post_callback(char *buffer, size_t size,
 71                          size_t nitems, struct _payload_data *pd)
 72{
 73    /* size of data left */
 74    int sz = pd->size - pd->offset;
 75
 76    /* if it's still bigger than the provided space, trim */
 77    if (sz > (int) (size * nitems))
 78        sz = size * nitems;
 79
 80    memcpy(buffer, pd->data + pd->offset, sz);
 81
 82    /* skip sent data */
 83    pd->offset += sz;
 84
 85    return sz;
 86}
 87
 88
 89xs_dict *xs_http_request(const char *method, const char *url,
 90                        const xs_dict *headers,
 91                        const xs_str *body, int b_size, int *status,
 92                        xs_str **payload, int *p_size, int timeout)
 93/* does an HTTP request */
 94{
 95    xs_dict *response;
 96    CURL *curl;
 97    struct curl_slist *list = NULL;
 98    const xs_str *k;
 99    const xs_val *v;
100    long lstatus = 0;
101    struct _payload_data pd;
102
103    response = xs_dict_new();
104
105    curl = curl_easy_init();
106
107    curl_easy_setopt(curl, CURLOPT_URL, url);
108
109    if (timeout <= 0)
110        timeout = 8;
111
112    curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long) timeout);
113
114#ifdef FORCE_HTTP_1_1
115    /* force HTTP/1.1 */
116    curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
117#endif
118
119    /* obey redirections */
120    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
121
122    /* store response headers here */
123    curl_easy_setopt(curl, CURLOPT_HEADERDATA,     &response);
124    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, _header_callback);
125
126    struct _payload_data ipd = { NULL, 0, 0 };
127    curl_easy_setopt(curl, CURLOPT_WRITEDATA,      &ipd);
128    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,  _data_callback);
129
130    if (strcmp(method, "POST") == 0 || strcmp(method, "PUT") == 0) {
131        CURLoption curl_method = method[1] == 'O' ? CURLOPT_POST : CURLOPT_UPLOAD;
132        curl_easy_setopt(curl, curl_method, 1L);
133
134        if (body != NULL) {
135            if (b_size <= 0)
136                b_size = xs_size(body);
137
138            /* add the content-length header */
139            curl_easy_setopt(curl, curl_method == CURLOPT_POST ? CURLOPT_POSTFIELDSIZE : CURLOPT_INFILESIZE, b_size);
140
141            pd.data = (char *)body;
142            pd.size = b_size;
143            pd.offset = 0;
144
145            curl_easy_setopt(curl, CURLOPT_READDATA,     &pd);
146            curl_easy_setopt(curl, CURLOPT_READFUNCTION, _post_callback);
147        }
148    }
149
150    /* fill the request headers */
151    xs_dict_foreach(headers, k, v) {
152        xs *h = xs_fmt("%s: %s", k, v);
153
154        list = curl_slist_append(list, h);
155    }
156
157    /* disable server support for 100-continue */
158    list = curl_slist_append(list, "Expect:");
159
160    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
161
162    /* do it */
163    CURLcode cc = curl_easy_perform(curl);
164
165    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &lstatus);
166
167    curl_easy_cleanup(curl);
168
169    curl_slist_free_all(list);
170
171    if (status != NULL) {
172        if (lstatus == 0) {
173            /* set the timeout error to a fake HTTP status, or propagate as is */
174            if (cc == CURLE_OPERATION_TIMEDOUT)
175                lstatus = 599;
176            else
177                lstatus = -cc;
178        }
179
180        *status = (int) lstatus;
181    }
182
183    if (p_size != NULL)
184        *p_size = ipd.size;
185
186    if (payload != NULL) {
187        *payload = ipd.data;
188
189        /* add an asciiz just in case (but not touching p_size) */
190        if (ipd.data != NULL)
191            ipd.data[ipd.size] = '\0';
192    }
193    else
194        xs_free(ipd.data);
195
196    return response;
197}
198
199
200const char *xs_curl_strerr(int errnum)
201{
202    CURLcode cc = errnum < 0 ? -errnum : errnum;
203
204    return curl_easy_strerror(cc);
205}
206
207
208#endif /* XS_IMPLEMENTATION */
209
210#endif /* _XS_CURL_H */