cryptnox-pos 1.0.0
Standalone USDC payment terminal firmware (ESP32 + Cryptnox smart card)
Loading...
Searching...
No Matches
form_parse.h
Go to the documentation of this file.
1/*
2 * SPDX-License-Identifier: LGPL-3.0-or-later
3 * Copyright (c) 2026 Cryptnox SA
4 */
5
15
16#ifndef FORM_PARSE_H
17#define FORM_PARSE_H
18
19#include <stddef.h>
20#include <stdio.h>
21#include <string.h>
22
24static inline int form_hexval(char c)
25{
26 if ((c >= '0') && (c <= '9')) { return c - '0'; }
27 if ((c >= 'a') && (c <= 'f')) { return (c - 'a') + 10; }
28 if ((c >= 'A') && (c <= 'F')) { return (c - 'A') + 10; }
29 return -1;
30}
31
46static inline size_t form_field(const char *body, const char *key,
47 char *out, size_t n)
48{
49 if ((out == NULL) || (n == 0U)) { return 0U; }
50 out[0] = '\0';
51 if ((body == NULL) || (key == NULL)) { return 0U; }
52
53 char pat[32];
54 (void)snprintf(pat, sizeof(pat), "%s=", key);
55 const size_t patlen = strlen(pat);
56
57 /* Anchored at the body start or just after an '&', so a field called
58 * "wifipass" cannot answer a lookup for "pass". */
59 const char *p = body;
60 while (p != NULL) {
61 if ((strncmp(p, pat, patlen) == 0) && ((p == body) || (p[-1] == '&'))) {
62 p += patlen;
63 break;
64 }
65 p = strchr(p, '&');
66 if (p != NULL) { p++; }
67 }
68 if (p == NULL) { return 0U; }
69
70 size_t w = 0U;
71 while ((*p != '\0') && (*p != '&') && (w < (n - 1U))) {
72 if (*p == '+') {
73 out[w++] = ' ';
74 p++;
75 } else if (*p == '%') {
76 const int hi = (p[1] != '\0') ? form_hexval(p[1]) : -1;
77 const int lo = ((hi >= 0) && (p[2] != '\0')) ? form_hexval(p[2]) : -1;
78 /* Malformed escape: stop rather than guess. A truncated value is
79 * rejected by the caller's own checks; a guessed one might not be. */
80 if (lo < 0) { break; }
81 out[w++] = static_cast<char>((hi << 4) | lo);
82 p += 3;
83 } else {
84 out[w++] = *p++;
85 }
86 }
87 out[w] = '\0';
88 return w;
89}
90
91#endif /* FORM_PARSE_H */
static size_t form_field(const char *body, const char *key, char *out, size_t n)
Pull one field out of a urlencoded body, percent-decoding it.
Definition form_parse.h:46
static int form_hexval(char c)
Hex nibble value, or -1 if c is not a hex digit.
Definition form_parse.h:24