Skip to content

cURL Command Builder — C source

Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.

This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.

/* curl-builder — structured input → copy-paste curl command + reverse parser.
 * C port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
 * Composes a copy-paste curl command from structured input; also parses an
 * existing command back into the structure (round-trip). Values are POSIX
 * single-quoted (' → '\'') — safe for POSIX shells. Fixed flag order: method
 * (-X) → headers (-H, insertion order) → auth (-u) → data (-d) → booleans
 * (-I -k -L --compressed) → the URL last. Never aborts — errors travel in
 * result.error (NULL on success). Ownership: build_curl_command's command
 * and error are malloc'd — release with curl_builder_free_build; a parse
 * tree is released whole with curl_builder_free_parse. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { const char *key, *value; } CurlHeader;
typedef struct { const char *user, *password; } CurlAuth;

typedef struct {
    const char *url, *method;   /* method NULL = GET */
    CurlHeader *headers;        /* insertion order kept */
    size_t nheaders;
    const char *data;           /* NULL or "" → omitted */
    CurlAuth *auth;             /* NULL = absent */
    int head_only, insecure, follow_redirects, compressed;
} CurlRequest;

typedef struct { char *command, *error; } CurlBuildResult;

typedef struct {
    CurlRequest request;        /* strings + arrays malloc'd */
    char **unknown_flags;       /* flags the parser does not model */
    size_t nunknown;
} ParsedCurl;

typedef struct { ParsedCurl *parsed; char *error; } CurlParseResult;

static const char *const METHODS[] = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", 0};

/* ---- small helpers ---- */

typedef struct { char *buf; size_t len, cap; } Str;

static void str_putn(Str *s, const char *t, size_t n) {
    if (s->len + n + 1 > s->cap) {
        s->cap = s->cap ? s->cap : 64;
        while (s->len + n + 1 > s->cap) s->cap *= 2;
        s->buf = (char *)realloc(s->buf, s->cap);
    }
    memcpy(s->buf + s->len, t, n);
    s->len += n;
}

static char *dup_n(const char *s, size_t n) {
    char *p = (char *)malloc(n + 1);
    memcpy(p, s, n);
    p[n] = '\0';
    return p;
}

static char *xstrdup(const char *s) { return dup_n(s, strlen(s)); }

static char *msg3(const char *a, const char *m, const char *b) {
    size_t n = strlen(a) + strlen(m) + strlen(b) + 1;
    char *p = (char *)malloc(n);
    snprintf(p, n, "%s%s%s", a, m, b);
    return p;
}

/* POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
static char *shell_quote(const char *v) {
    size_t n = strlen(v), q = 0, i, j = 0;
    char *out;
    for (i = 0; i < n; i++) q += v[i] == '\'';
    out = (char *)malloc(n + 2 + q * 3 + 1);
    out[j++] = '\'';
    for (i = 0; i < n; i++) {
        if (v[i] == '\'') { memcpy(out + j, "'\\''", 4); j += 4; }
        else out[j++] = v[i];
    }
    out[j++] = '\'';
    out[j] = '\0';
    return out;
}

static const char *bounds(const char *s, const char *e, const char **end) {
    while (s < e && isspace((unsigned char)*s)) s++;
    while (e > s && isspace((unsigned char)e[-1])) e--;
    *end = e;
    return s;
}

static int hdr_char(unsigned char c) {
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
}

/** Build the curl command. URL required; method/header names validated. */
CurlBuildResult build_curl_command(const CurlRequest *req) {
    CurlBuildResult r = {0};
    const char *ue, *u = bounds(req->url, req->url + strlen(req->url), &ue);
    const char *rm = req->method ? req->method : "GET";
    size_t ulen = (size_t)(ue - u), ml = strlen(rm), i;
    char method[64], *url;
    Str s = {0};
    if (!ulen) { r.error = xstrdup("A URL is required"); return r; }
    url = dup_n(u, ulen);
    if (!(strncmp(url, "https://", 8) == 0 || strncmp(url, "http://", 7) == 0 ||
          url[0] == '/' || url[0] == '$')) {
        r.error = xstrdup("URL must start with http://, https://, / or $ (a variable)");
        free(url);
        return r;
    }
    if (ml >= sizeof method) ml = sizeof method - 1;
    for (i = 0; i < ml; i++) method[i] = (char)toupper((unsigned char)rm[i]);
    method[ml] = '\0';
    for (i = 0; METHODS[i]; i++)
        if (strcmp(METHODS[i], method) == 0) break;
    if (!METHODS[i]) {
        r.error = msg3("unsupported method ", rm, " (use GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)");
        free(url);
        return r;
    }
    for (i = 0; i < req->nheaders; i++) {
        const char *k = req->headers[i].key;
        int bad = !*k;
        for (; *k && !bad; k++)
            if (!hdr_char((unsigned char)*k)) bad = 1;
        if (bad) {
            r.error = msg3("invalid header name \"", req->headers[i].key,
                           "\" (letters, digits and hyphens only)");
            free(url);
            return r;
        }
    }
    str_putn(&s, "curl", 4);
    if (strcmp(method, "GET") != 0) { str_putn(&s, " -X ", 4); str_putn(&s, method, ml); }
    for (i = 0; i < req->nheaders; i++) {
        char *cat = msg3(req->headers[i].key, ": ", req->headers[i].value);
        char *q = shell_quote(cat);
        str_putn(&s, " -H ", 4); str_putn(&s, q, strlen(q));
        free(cat); free(q);
    }
    if (req->auth) {
        char *cat = msg3(req->auth->user, ":", req->auth->password);
        char *q = shell_quote(cat);
        str_putn(&s, " -u ", 4); str_putn(&s, q, strlen(q));
        free(cat); free(q);
    }
    if (req->data && req->data[0]) {
        char *q = shell_quote(req->data);
        str_putn(&s, " -d ", 4); str_putn(&s, q, strlen(q));
        free(q);
    }
    if (req->head_only) str_putn(&s, " -I", 3);
    if (req->insecure) str_putn(&s, " -k", 3);
    if (req->follow_redirects) str_putn(&s, " -L", 3);
    if (req->compressed) str_putn(&s, " --compressed", 13);
    {
        char *q = shell_quote(url);
        str_putn(&s, " ", 1);
        str_putn(&s, q, strlen(q));
        free(q);
    }
    free(url);
    if (!s.buf) { r.command = xstrdup(""); return r; }
    s.buf[s.len] = '\0';
    r.command = s.buf;
    return r;
}

/* ---- shell word-split respecting single and double quotes ---- */

typedef struct { char **items; size_t len, cap; } Words;

static void words_push(Words *w, char *s) {
    if (w->len == w->cap) {
        w->cap = w->cap ? w->cap * 2 : 8;
        w->items = (char **)realloc(w->items, w->cap * sizeof *w->items);
    }
    w->items[w->len++] = s;
}

static void free_words(Words *w) {
    size_t i;
    for (i = 0; i < w->len; i++) free(w->items[i]);
    free(w->items);
}

static Words split_words(const char *line) {
    Words w = {0};
    Str cur = {0};
    char quote = 0;
    int has = 0;
    for (const char *p = line; ; p++) {
        char ch = *p;
        int fin = ch == '\0';
        if (fin || (!quote && (ch == ' ' || ch == '\t'))) {
            if (cur.len || has) words_push(&w, dup_n(cur.buf ? cur.buf : "", cur.len));
            cur.len = 0;
            has = 0;
            if (fin) break;
            continue;
        }
        if (quote) {
            if (ch == quote) quote = 0;
            else str_putn(&cur, &ch, 1);
        } else if (ch == '\'' || ch == '"') {
            quote = ch;
            has = 1;
        } else {
            str_putn(&cur, &ch, 1);
            has = 1;
        }
    }
    free(cur.buf);
    return w;
}

static void free_parsed(ParsedCurl *pc) {
    size_t i;
    if (!pc) return;
    for (i = 0; i < pc->nunknown; i++) free(pc->unknown_flags[i]);
    free(pc->unknown_flags);
    for (i = 0; i < pc->request.nheaders; i++) {
        free((void *)pc->request.headers[i].key);
        free((void *)pc->request.headers[i].value);
    }
    free((void *)pc->request.headers);
    free((void *)pc->request.url);
    free((void *)pc->request.method);
    free((void *)pc->request.data);
    if (pc->request.auth) {
        free((void *)pc->request.auth->user);
        free((void *)pc->request.auth->password);
        free(pc->request.auth);
    }
    free(pc);
}

/** Parse a curl command line back into a request (best effort, ordered). */
CurlParseResult parse_curl_command(const char *line) {
    CurlParseResult r = {0};
    const char *p = line, *e = line + strlen(line);
    ParsedCurl *pc;
    char *url = 0, *method = 0, *data = 0, *user = 0, *pass = 0;
    char *t;
    size_t tn, hn = 0, i;
    Words words = {0};
    while (p < e && isspace((unsigned char)*p)) p++;
    while (e > p && isspace((unsigned char)e[-1])) e--;
    t = (char *)malloc((size_t)(e - p) + 1);
    for (tn = 0; p < e; p++) { /* TS: replace(/\\\n/g, ' ') */
        if (*p == '\\' && p + 1 < e && p[1] == '\n') { t[tn++] = ' '; p++; }
        else t[tn++] = *p;
    }
    t[tn] = '\0';
    words = split_words(t);
    free(t);
    if (!words.len) { r.error = xstrdup("A command is required"); free_words(&words); return r; }
    if (strcmp(words.items[0], "curl") != 0) {
        r.error = xstrdup("command must start with curl");
        free_words(&words);
        return r;
    }
    pc = (ParsedCurl *)calloc(1, sizeof *pc);
    pc->request.headers = (CurlHeader *)calloc(words.len, sizeof(CurlHeader));
    pc->unknown_flags = (char **)calloc(words.len, sizeof(char *));
    for (i = 1; i < words.len; i++) {
        const char *w = words.items[i], *raw, *at;
        if (!strcmp(w, "-X") || !strcmp(w, "--request")) {
            if (i + 1 < words.len) { free(method); method = xstrdup(words.items[++i]); }
        } else if (!strcmp(w, "-H") || !strcmp(w, "--header")) {
            if (i + 1 < words.len) {
                const char *kb, *ke, *vb, *ve;
                raw = words.items[++i];
                at = strchr(raw, ':');
                if (at && at != raw) {
                    kb = bounds(raw, at, &ke);
                    vb = bounds(at + 1, raw + strlen(raw), &ve);
                    pc->request.headers[hn].key = dup_n(kb, (size_t)(ke - kb));
                    pc->request.headers[hn].value = dup_n(vb, (size_t)(ve - vb));
                    hn++;
                }
            }
        } else if (!strcmp(w, "-u") || !strcmp(w, "--user")) {
            if (i + 1 < words.len) {
                raw = words.items[++i];
                at = strchr(raw, ':');
                free(user); free(pass);
                if (at) { user = dup_n(raw, (size_t)(at - raw)); pass = xstrdup(at + 1); }
                else { user = xstrdup(raw); pass = xstrdup(""); }
            }
        } else if (!strcmp(w, "-d") || !strcmp(w, "--data")) {
            if (i + 1 < words.len) { free(data); data = xstrdup(words.items[++i]); }
        }
        else if (!strcmp(w, "-I") || !strcmp(w, "--head")) pc->request.head_only = 1;
        else if (!strcmp(w, "-k") || !strcmp(w, "--insecure")) pc->request.insecure = 1;
        else if (!strcmp(w, "-L") || !strcmp(w, "--location")) pc->request.follow_redirects = 1;
        else if (!strcmp(w, "--compressed")) pc->request.compressed = 1;
        else if (w[0] == '-') pc->unknown_flags[pc->nunknown++] = xstrdup(w);
        else { free(url); url = xstrdup(w); }
    }
    free_words(&words);
    if (user) {
        CurlAuth *a = (CurlAuth *)malloc(sizeof *a);
        a->user = user;
        a->password = pass;
        pc->request.auth = a;
    }
    pc->request.nheaders = hn;
    pc->request.url = url;
    pc->request.method = method;
    pc->request.data = data;
    if (!url) r.error = xstrdup("no URL found in command");
    else r.parsed = pc;
    if (r.error) free_parsed(pc);
    return r;
}

void curl_builder_free_build(CurlBuildResult *r) {
    free(r->command);
    free(r->error);
    r->command = r->error = 0;
}

void curl_builder_free_parse(CurlParseResult *r) {
    free_parsed(r->parsed);
    free(r->error);
    r->parsed = 0;
    r->error = 0;
}

/* Example:
 * shell_quote("it's") → '\'it'\''s\''
 * CurlRequest req = {.url = "https://api.example.com", .method = "post",
 *                    .headers = (CurlHeader[]){{"X-Tag", "it's"}}, .nheaders = 1,
 *                    .data = "k=v"};
 * build_curl_command(&req).command
 * → curl -X POST -H 'X-Tag: it'\''s' -d 'k=v' 'https://api.example.com' */

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →