sagui.h 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2021 Silvio Clecio <[email protected]>
  11. *
  12. * Sagui library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * Sagui library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with Sagui library; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. /**
  27. * \mainpage
  28. * \li \ref sg_api
  29. */
  30. /** \defgroup sg_api API reference
  31. * The API reference grouped by feature.
  32. **/
  33. #ifndef SAGUI_H
  34. #define SAGUI_H
  35. #ifdef __cplusplus
  36. extern "C" {
  37. #endif
  38. #include <stdio.h>
  39. #include <stddef.h>
  40. #include <stdbool.h>
  41. #include <stdint.h>
  42. #include <stdarg.h>
  43. #include <string.h>
  44. #include <time.h>
  45. #ifndef SG_EXTERN
  46. #ifdef _WIN32
  47. #ifdef BUILDING_LIBSAGUI
  48. #define SG_EXTERN __declspec(dllexport) extern
  49. #else /* _WIN32 */
  50. #define SG_EXTERN __declspec(dllimport) extern
  51. #endif /* _WIN32 */
  52. #else /* BUILDING_LIBSAGUI */
  53. #define SG_EXTERN extern
  54. #endif /* BUILDING_LIBSAGUI */
  55. #endif /* SG_EXTERN */
  56. #ifndef __SG_UNUSED
  57. #define __SG_UNUSED __attribute__((unused))
  58. #endif /* __SG_UNUSED */
  59. #ifndef __SG_MALLOC
  60. #define __SG_MALLOC __attribute__((malloc))
  61. #endif /* __SG_MALLOC */
  62. #ifndef __SG_FORMAT
  63. #define __SG_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  64. #endif /* __SG_FORMAT */
  65. #define SG_VERSION_MAJOR 3
  66. #define SG_VERSION_MINOR 4
  67. #define SG_VERSION_PATCH 0
  68. #define SG_VERSION_HEX \
  69. ((SG_VERSION_MAJOR << 16) | (SG_VERSION_MINOR << 8) | (SG_VERSION_PATCH))
  70. #define SG_ERR_SIZE 256
  71. /**
  72. * \ingroup sg_api
  73. * \defgroup sg_utils Utilities
  74. * All utility functions of the library.
  75. * \{
  76. */
  77. /**
  78. * Callback signature used to override the function which allocates a new
  79. * memory space.
  80. * \param[in] size Memory size to be allocated.
  81. * \return Pointer of the allocated memory.
  82. * \retval NULL If size is `0` or no memory space.
  83. */
  84. typedef void *(*sg_malloc_func)(size_t size);
  85. /**
  86. * Callback signature used to override the function which reallocates an
  87. * existing memory block.
  88. * \param[in] ptr Pointer of the memory to be reallocated.
  89. * \param[in] size Memory size to be reallocated.
  90. * \return Pointer of the reallocated memory.
  91. */
  92. typedef void *(*sg_realloc_func)(void *ptr, size_t size);
  93. /**
  94. * Callback signature used to override the function which frees a memory space
  95. * previously allocated by #sg_malloc(), #sg_alloc() or #sg_realloc().
  96. * \param[in] ptr Pointer of the memory to be freed.
  97. */
  98. typedef void (*sg_free_func)(void *ptr);
  99. /**
  100. * Callback signature used to override the function which returns the value of
  101. * `x` raised to the power of `y`.
  102. * \param[in] x Floating point base value.
  103. * \param[in] y Floating point power value.
  104. * \return Value of `x` raised to the power of `y`.
  105. */
  106. typedef double (*sg_pow_func)(double x, double y);
  107. /**
  108. * Callback signature used to override the function which returns the remainder
  109. * of `x` divided by `y`.
  110. * \param[in] x Floating point value with the division numerator.
  111. * \param[in] y Floating point value with the division denominator.
  112. * \return Remainder of `x` divided by `y`.
  113. */
  114. typedef double (*sg_fmod_func)(double x, double y);
  115. /**
  116. * Callback signature used by functions that handle errors.
  117. * \param[out] cls User-defined closure.
  118. * \param[out] err Error message.
  119. */
  120. typedef void (*sg_err_cb)(void *cls, const char *err);
  121. /**
  122. * Callback signature used by functions that write streams.
  123. * \param[out] handle Stream handle.
  124. * \param[out] offset Current stream offset.
  125. * \param[out] buf Current buffer to be written.
  126. * \param[out] size Size of the current buffer to be written.
  127. * \return Total written buffer.
  128. */
  129. typedef ssize_t (*sg_write_cb)(void *handle, uint64_t offset, const char *buf,
  130. size_t size);
  131. /**
  132. * Callback signature used by functions that read streams.
  133. * \param[out] handle Stream handle.
  134. * \param[out] offset Current stream offset.
  135. * \param[out] buf Current read buffer.
  136. * \param[out] size Size of the current read buffer.
  137. * \return Total read buffer.
  138. */
  139. typedef ssize_t (*sg_read_cb)(void *handle, uint64_t offset, char *buf,
  140. size_t size);
  141. /**
  142. * Callback signature used by functions that free streams.
  143. * \param[out] handle Stream handle.
  144. */
  145. typedef void (*sg_free_cb)(void *handle);
  146. /**
  147. * Callback signature used by functions that save streams.
  148. * \param[out] handle Stream handle.
  149. * \param[out] overwritten Overwrite an already existed stream.
  150. * \retval 0 Success.
  151. * \retval E<ERROR> User-defined error to abort the saving.
  152. */
  153. typedef int (*sg_save_cb)(void *handle, bool overwritten);
  154. /**
  155. * Callback signature used by functions that save streams. It allows to specify
  156. * the destination file path.
  157. * \param[out] handle Stream handle.
  158. * \param[out] path Absolute path to store the stream.
  159. * \param[out] overwritten Overwrite an already existed stream.
  160. * \retval 0 Success.
  161. * \retval E<ERROR> User-defined error to abort the saving.
  162. */
  163. typedef int (*sg_save_as_cb)(void *handle, const char *path, bool overwritten);
  164. /**
  165. * Returns the library version number.
  166. * \return Library version packed into a single integer.
  167. */
  168. SG_EXTERN unsigned int sg_version(void);
  169. /**
  170. * Returns the library version number as string in the format
  171. * `<MAJOR>.<MINOR>.<PATCH>`.
  172. * \return Library version packed into a null-terminated string.
  173. */
  174. SG_EXTERN const char *sg_version_str(void);
  175. /**
  176. * Overrides the standard functions
  177. * [malloc(3)](https://linux.die.net/man/3/malloc),
  178. * [realloc(3)](https://linux.die.net/man/3/realloc) and
  179. * [free(3)](https://linux.die.net/man/3/free) set by default in the memory
  180. * manager.
  181. * \param[in] malloc_func Reference to override the function `malloc()`.
  182. * \param[in] realloc_func Reference to override the function `realloc()`.
  183. * \param[in] free_func Reference to override the function `free()`.
  184. * \retval 0 Success.
  185. * \retval EINVAL Invalid argument.
  186. * \note It must be called before any other Sagui function or after all
  187. * resources have been freed.
  188. */
  189. SG_EXTERN int sg_mm_set(sg_malloc_func malloc_func,
  190. sg_realloc_func realloc_func, sg_free_func free_func);
  191. /**
  192. * Allocates a new memory space.
  193. * \param[in] size Memory size to be allocated.
  194. * \return Pointer of the allocated memory.
  195. * \retval NULL If size is `0` or no memory space.
  196. * \note Equivalent to [malloc(3)](https://linux.die.net/man/3/malloc).
  197. */
  198. SG_EXTERN void *sg_malloc(size_t size) __SG_MALLOC;
  199. /**
  200. * Allocates a new zero-initialized memory space.
  201. * \param[in] size Memory size to be allocated.
  202. * \return Pointer of the zero-initialized allocated memory.
  203. * \retval NULL If size is `0` or no memory space.
  204. */
  205. SG_EXTERN void *sg_alloc(size_t size) __SG_MALLOC;
  206. /**
  207. * Reallocates an existing memory block.
  208. * \param[in] ptr Pointer of the memory to be reallocated.
  209. * \param[in] size Memory size to be reallocated.
  210. * \return Pointer of the reallocated memory.
  211. * \note Equivalent to [realloc(3)](https://linux.die.net/man/3/realloc).
  212. */
  213. SG_EXTERN void *sg_realloc(void *ptr, size_t size) __SG_MALLOC;
  214. /**
  215. * Frees a memory space previously allocated by #sg_malloc(), #sg_alloc() or
  216. * #sg_realloc().
  217. * \param[in] ptr Pointer of the memory to be freed.
  218. * \note Equivalent to [free(3)](https://linux.die.net/man/3/free).
  219. */
  220. SG_EXTERN void sg_free(void *ptr);
  221. /**
  222. * Overrides the standard functions [pow(3)](https://linux.die.net/man/3/pow)
  223. * and [fmod(3)](https://linux.die.net/man/3/fmod) set by default in the math
  224. * manager.
  225. * \param[in] pow_func Reference to override the function `pow()`.
  226. * \param[in] fmod_func Reference to override the function `fmod()`.
  227. * \retval 0 Success.
  228. * \retval EINVAL Invalid argument.
  229. * \note It must be called before any other Sagui function or after all
  230. * resources have been freed.
  231. */
  232. SG_EXTERN int sg_math_set(sg_pow_func pow_func, sg_fmod_func fmod_func);
  233. /**
  234. * Returns string describing an error number.
  235. * \param[in] errnum Error number.
  236. * \param[in,out] errmsg Pointer of a string to store the error message.
  237. * \param[in] errlen Length of the error message.
  238. * \return Pointer to \pr{errmsg}.
  239. */
  240. SG_EXTERN char *sg_strerror(int errnum, char *errmsg, size_t errlen);
  241. /**
  242. * Checks if a string is a HTTP post method.
  243. * \param[in] method Null-terminated string.
  244. * \retval true If \pr{method} is `POST`, `PUT`, `DELETE` or `OPTIONS`.
  245. */
  246. SG_EXTERN bool sg_is_post(const char *method);
  247. /**
  248. * Extracts the entry-point of a path or resource. For example, given a path
  249. * `/api1/customer`, the part considered as entry-point is `/api1`.
  250. * \param path Path as a null-terminated string.
  251. * \return Entry-point as a null-terminated string.
  252. * \retval NULL If no memory space is available.
  253. * \warning The caller must free the returned value.
  254. */
  255. SG_EXTERN char *sg_extract_entrypoint(const char *path) __SG_MALLOC;
  256. /**
  257. * Returns the system temporary directory.
  258. * \return Temporary directory as a null-terminated string.
  259. * \retval NULL If no memory space is available.
  260. * \warning The caller must free the returned value.
  261. */
  262. SG_EXTERN char *sg_tmpdir(void) __SG_MALLOC;
  263. /**
  264. * Indicates the end-of-read processed in #sg_httpres_sendstream().
  265. * \param[in] err `true` to return a value indicating a stream reading error.
  266. * \return Value to end a stream reading.
  267. */
  268. SG_EXTERN ssize_t sg_eor(bool err);
  269. /**
  270. * Obtains the IP of a socket handle (e.g. the one returned by
  271. * #sg_httpreq_client()) into a null-terminated string.
  272. * \param[in] socket Socket handle.
  273. * \param[out] buf Pointer of the string to store the IP.
  274. * \param[in] size Size of the string to store the IP.
  275. * \retval 0 Success.
  276. * \retval EINVAL Invalid argument.
  277. * \retval EAFNOSUPPORT Address family not supported by protocol.
  278. * \retval ENOSPC No space left on device.
  279. */
  280. SG_EXTERN int sg_ip(const void *socket, char *buf, size_t size);
  281. /** \} */
  282. /**
  283. * \ingroup sg_api
  284. * \defgroup sg_str String
  285. * String handle and its related functions.
  286. * \{
  287. */
  288. /**
  289. * Handle for the string structure used to represent a HTML body, POST payload
  290. * and more.
  291. * \struct sg_str
  292. */
  293. struct sg_str;
  294. /**
  295. * Creates a new zero-initialized string handle.
  296. * \return String handle.
  297. * \retval NULL If no memory space is available.
  298. */
  299. SG_EXTERN struct sg_str *sg_str_new(void) __SG_MALLOC;
  300. /**
  301. * Frees the string handle previously allocated by #sg_str_new().
  302. * \param[in] str Pointer of the string handle to be freed.
  303. */
  304. SG_EXTERN void sg_str_free(struct sg_str *str);
  305. /**
  306. * Writes a null-terminated string to the string handle \pr{str}. All strings
  307. * previously written are kept.
  308. * \param[in] str String handle.
  309. * \param[in] val String to be written.
  310. * \param[in] len Length of the string to be written.
  311. * \retval 0 Success.
  312. * \retval EINVAL Invalid argument.
  313. */
  314. SG_EXTERN int sg_str_write(struct sg_str *str, const char *val, size_t len);
  315. /**
  316. * Prints a null-terminated formatted string from the argument list to the
  317. * string handle \pr{str}.
  318. * \param[in] str String handle.
  319. * \param[in] fmt Formatted string (following the same
  320. * [`printf()`](https://linux.die.net/man/3/printf) format specification).
  321. * \param[in] ap Arguments list (handled by
  322. * [`va_start()`](https://linux.die.net/man/3/va_start)/
  323. * [`va_end()`](https://linux.die.net/man/3/va_end)).
  324. * \retval 0 Success.
  325. * \retval EINVAL Invalid argument.
  326. */
  327. SG_EXTERN int sg_str_printf_va(struct sg_str *str, const char *fmt, va_list ap);
  328. /**
  329. * Prints a null-terminated formatted string to the string handle \pr{str}. All
  330. * strings previously written are kept.
  331. * \param[in] str String handle.
  332. * \param[in] fmt Formatted string (following the same
  333. * [`printf()`](https://linux.die.net/man/3/printf) format specification).
  334. * \param[in] ... Additional arguments (following the same
  335. * [`printf()`](https://linux.die.net/man/3/printf) arguments specification).
  336. * \retval 0 Success.
  337. * \retval EINVAL Invalid argument.
  338. */
  339. SG_EXTERN int sg_str_printf(struct sg_str *str, const char *fmt, ...)
  340. __SG_FORMAT(2, 3);
  341. /**
  342. * Returns the null-terminated string content from the string handle \pr{str}.
  343. * \param[in] str String handle.
  344. * \return Content as a null-terminated string.
  345. * \retval NULL If the \pr{str} is null and set the `errno` to `EINVAL`.
  346. */
  347. SG_EXTERN const char *sg_str_content(struct sg_str *str);
  348. /**
  349. * Returns the total string length from the handle \pr{str}.
  350. * \param[in] str String handle.
  351. * \return Total string length.
  352. * \retval EINVAL Invalid argument.
  353. */
  354. SG_EXTERN size_t sg_str_length(struct sg_str *str);
  355. /**
  356. * Clears all existing content in the string handle \pr{str}.
  357. * \param[in] str String handle.
  358. * \retval 0 Success.
  359. * \retval EINVAL Invalid argument.
  360. */
  361. SG_EXTERN int sg_str_clear(struct sg_str *str);
  362. /** \} */
  363. /**
  364. * \ingroup sg_api
  365. * \defgroup sg_strmap String map
  366. * String map handle and its related functions.
  367. * \{
  368. */
  369. /**
  370. * Handle for hash table that maps name-value pairs. It is useful to represent
  371. * posting fields, query-string parameter, client cookies and more.
  372. * \struct sg_strmap
  373. */
  374. struct sg_strmap;
  375. /**
  376. * Callback signature used by #sg_strmap_iter() to iterate pairs of strings.
  377. * \param[out] cls User-defined closure.
  378. * \param[out] pair Current iterated pair.
  379. * \retval 0 Success.
  380. * \retval E<ERROR> User-defined error to stop pairs iteration.
  381. */
  382. typedef int (*sg_strmap_iter_cb)(void *cls, struct sg_strmap *pair);
  383. /**
  384. * Callback signature used by #sg_strmap_sort() to sort pairs of strings.
  385. * \param[out] cls User-defined closure.
  386. * \param[out] pair_a Current left pair (A).
  387. * \param[out] pair_b Current right pair (B).
  388. * \retval -1 A < B.
  389. * \retval 0 A == B.
  390. * \retval 1 A > B.
  391. */
  392. typedef int (*sg_strmap_sort_cb)(void *cls, struct sg_strmap *pair_a,
  393. struct sg_strmap *pair_b);
  394. /**
  395. * Returns a name from the \pr{pair}.
  396. * \param[in] pair Pair of name-value.
  397. * \return Name as a null-terminated string.
  398. * \retval NULL If the \pr{pair} is null and set the `errno` to `EINVAL`.
  399. */
  400. SG_EXTERN const char *sg_strmap_name(struct sg_strmap *pair);
  401. /**
  402. * Returns a value from the \pr{pair}.
  403. * \param[in] pair Pair of name-value.
  404. * \return Value as a null-terminated string.
  405. * \retval NULL If the \pr{pair} is null and set the `errno` to `EINVAL`.
  406. */
  407. SG_EXTERN const char *sg_strmap_val(struct sg_strmap *pair);
  408. /**
  409. * Adds a pair of name-value to the string \pr{map}.
  410. * \param[in,out] map Pairs map pointer to add a new pair.
  411. * \param[in] name Pair name.
  412. * \param[in] val Pair value.
  413. * \retval 0 Success.
  414. * \retval EINVAL Invalid argument.
  415. * \retval ENOMEM Out of memory.
  416. * \note It cannot check if a name already exists in a pair added to the
  417. * \pr{map}, then the uniqueness must be managed by the application.
  418. */
  419. SG_EXTERN int sg_strmap_add(struct sg_strmap **map, const char *name,
  420. const char *val);
  421. /**
  422. * Sets a pair of name-value to the string \pr{map}.
  423. * \param[in,out] map Pairs map pointer to set a new pair.
  424. * \param[in] name Pair name.
  425. * \param[in] val Pair value.
  426. * \retval 0 Success.
  427. * \retval EINVAL Invalid argument.
  428. * \retval ENOMEM Out of memory.
  429. * \note If a name already exists in a pair previously added into the \pr{map},
  430. * then the function replaces its value, otherwise it is added as a new pair.
  431. */
  432. SG_EXTERN int sg_strmap_set(struct sg_strmap **map, const char *name,
  433. const char *val);
  434. /**
  435. * Finds a pair by name.
  436. * \param[in] map Pairs map.
  437. * \param[in] name Name to find the pair.
  438. * \param[in,out] pair Pointer of the variable to store the found pair.
  439. * \retval 0 Success.
  440. * \retval EINVAL Invalid argument.
  441. * \retval ENOENT Pair not found.
  442. * \retval ENOMEM Out of memory.
  443. */
  444. SG_EXTERN int sg_strmap_find(struct sg_strmap *map, const char *name,
  445. struct sg_strmap **pair);
  446. /**
  447. * Gets a pair by name and returns the value.
  448. * \param[in] map Pairs map.
  449. * \param[in] name Name to get the pair.
  450. * \return Pair value as a null-terminated string.
  451. * \retval NULL If \pr{map} or \pr{name} is null or pair is not found.
  452. */
  453. SG_EXTERN const char *sg_strmap_get(struct sg_strmap *map, const char *name);
  454. /**
  455. * Removes a pair by name.
  456. * \param[in] map Pointer to the pairs map.
  457. * \param[in] name Name to find and then remove the pair.
  458. * \retval 0 Success.
  459. * \retval EINVAL Invalid argument.
  460. * \retval ENOENT Pair already removed.
  461. * \retval ENOMEM Out of memory.
  462. */
  463. SG_EXTERN int sg_strmap_rm(struct sg_strmap **map, const char *name);
  464. /**
  465. * Iterates over pairs map.
  466. * \param[in] map Pairs map.
  467. * \param[in] cb Callback to iterate the pairs.
  468. * \param[in,out] cls User-specified value.
  469. * \retval 0 Success.
  470. * \retval EINVAL Invalid argument.
  471. * \return Callback result when it is different from `0`.
  472. */
  473. SG_EXTERN int sg_strmap_iter(struct sg_strmap *map, sg_strmap_iter_cb cb,
  474. void *cls);
  475. /**
  476. * Sorts the pairs map.
  477. * \param[in,out] map Pointer to the pairs map.
  478. * \param[in] cb Callback to sort the pairs.
  479. * \param[in,out] cls User-specified value.
  480. * \retval 0 Success.
  481. * \retval EINVAL Invalid argument.
  482. */
  483. SG_EXTERN int sg_strmap_sort(struct sg_strmap **map, sg_strmap_sort_cb cb,
  484. void *cls);
  485. /**
  486. * Counts the total pairs in the map.
  487. * \param[in] map Pairs map.
  488. * \return Total of pairs.
  489. * \retval 0 If the list is empty or null.
  490. */
  491. SG_EXTERN unsigned int sg_strmap_count(struct sg_strmap *map);
  492. /**
  493. * Returns the next pair in the map.
  494. * \param[in,out] next Pointer to the next pair.
  495. * \retval 0 Success.
  496. * \retval EINVAL Invalid argument.
  497. */
  498. SG_EXTERN int sg_strmap_next(struct sg_strmap **next);
  499. /**
  500. * Cleans the entire map.
  501. * \param[in,out] map Pointer to the pairs map.
  502. */
  503. SG_EXTERN void sg_strmap_cleanup(struct sg_strmap **map);
  504. /** \} */
  505. /**
  506. * \ingroup sg_api
  507. * \defgroup sg_httpsrv HTTP server
  508. * Fast event-driven HTTP server.
  509. * \{
  510. */
  511. /**
  512. * Handle for the HTTP basic authentication.
  513. * \struct sg_httpauth
  514. */
  515. struct sg_httpauth;
  516. /**
  517. * Handle for the upload handling. It is used to represent a single upload or a
  518. * list of uploads.
  519. * \struct sg_httpupld
  520. */
  521. struct sg_httpupld;
  522. /**
  523. * Handle for the request handling. It contains headers, cookies, query-string,
  524. * fields, payloads, uploads and other data sent by the client.
  525. * \struct sg_httpreq
  526. */
  527. struct sg_httpreq;
  528. /**
  529. * Handle for the response handling. It dispatches headers, contents, binaries,
  530. * files and other data to the client.
  531. * \struct sg_httpres
  532. */
  533. struct sg_httpres;
  534. /**
  535. * Handle for the fast event-driven HTTP server.
  536. * \struct sg_httpsrv
  537. */
  538. struct sg_httpsrv;
  539. /**
  540. * Callback signature used to handle client connection events.
  541. * \param[out] cls User-defined closure.
  542. * \param[out] client Socket handle of the client.
  543. * \param[in,out] closed Indicates if the client is connected allowing to
  544. * close it.
  545. */
  546. typedef void (*sg_httpsrv_cli_cb)(void *cls, const void *client, bool *closed);
  547. /**
  548. * Callback signature used to grant or deny the user access to the server
  549. * resources.
  550. * \param[out] cls User-defined closure.
  551. * \param[out] auth Authentication handle.
  552. * \param[out] req Request handle.
  553. * \param[out] res Response handle.
  554. * \retval true Grants the user access.
  555. * \retval false Denies the user access.
  556. */
  557. typedef bool (*sg_httpauth_cb)(void *cls, struct sg_httpauth *auth,
  558. struct sg_httpreq *req, struct sg_httpres *res);
  559. /**
  560. * Callback signature used to handle uploaded files and/or fields.
  561. * \param[out] cls User-defined closure.
  562. * \param[in,out] handle Stream handle pointer.
  563. * \param[out] dir Directory to store the uploaded files.
  564. * \param[out] field Posted field.
  565. * \param[out] name Uploaded file name.
  566. * \param[out] mime Uploaded file content-type (e.g.: `text/plain`, `image/png`,
  567. * `application/json` etc.).
  568. * \param[out] encoding Uploaded file transfer-encoding (e.g.: `chunked`,
  569. * `deflate`, `gzip` etc.).
  570. * \retval 0 Success.
  571. * \retval E<ERROR> User-defined error to refuse the upload.
  572. */
  573. typedef int (*sg_httpupld_cb)(void *cls, void **handle, const char *dir,
  574. const char *field, const char *name,
  575. const char *mime, const char *encoding);
  576. /**
  577. * Callback signature used to iterate uploaded files.
  578. * \param[out] cls User-defined closure.
  579. * \param[out] upld Current upload item.
  580. * \retval 0 Success.
  581. * \retval E<ERROR> User-defined error to stop list iteration.
  582. */
  583. typedef int (*sg_httpuplds_iter_cb)(void *cls, struct sg_httpupld *upld);
  584. /**
  585. * Callback signature used to handle requests and responses.
  586. * \param[out] cls User-defined closure.
  587. * \param[out] req Request handle.
  588. * \param[out] res Response handle.
  589. */
  590. typedef void (*sg_httpreq_cb)(void *cls, struct sg_httpreq *req,
  591. struct sg_httpres *res);
  592. /**
  593. * Sets the authentication protection space (realm).
  594. * \param[in] auth Authentication handle.
  595. * \param[in] realm Realm string.
  596. * \retval 0 Success.
  597. * \retval EINVAL Invalid argument.
  598. * \retval EALREADY Realm already set.
  599. * \retval ENOMEM Out of memory.
  600. */
  601. SG_EXTERN int sg_httpauth_set_realm(struct sg_httpauth *auth,
  602. const char *realm);
  603. /**
  604. * Gets the authentication protection space (realm).
  605. * \param[in] auth Authentication handle.
  606. * \return Realm as a null-terminated string.
  607. * \retval NULL If \pr{auth} is null and set the `errno` to `EINVAL`.
  608. */
  609. SG_EXTERN const char *sg_httpauth_realm(struct sg_httpauth *auth);
  610. /**
  611. * Deny the authentication sending the reason to the user.
  612. * \param[in] auth Authentication handle.
  613. * \param[in] reason Denial reason.
  614. * \param[in] content_type Content type.
  615. * \param[in] status HTTP status code.
  616. * \retval 0 Success.
  617. * \retval EINVAL Invalid argument.
  618. * \retval EALREADY Already denied.
  619. * \retval ENOMEM Out of memory.
  620. */
  621. SG_EXTERN int sg_httpauth_deny2(struct sg_httpauth *auth, const char *reason,
  622. const char *content_type, unsigned int status);
  623. /**
  624. * Deny the authentication sending the reason to the user.
  625. * \param[in] auth Authentication handle.
  626. * \param[in] reason Denial reason.
  627. * \param[in] content_type Content type.
  628. * \retval 0 Success.
  629. * \retval EINVAL Invalid argument.
  630. * \retval EALREADY Already denied.
  631. * \retval ENOMEM Out of memory.
  632. */
  633. SG_EXTERN int sg_httpauth_deny(struct sg_httpauth *auth, const char *reason,
  634. const char *content_type);
  635. /**
  636. * Cancels the authentication loop while the user is trying to access
  637. * the server.
  638. * \param[in] auth Authentication handle.
  639. * \retval 0 Success.
  640. * \retval EINVAL Invalid argument.
  641. */
  642. SG_EXTERN int sg_httpauth_cancel(struct sg_httpauth *auth);
  643. /**
  644. * Returns the authentication user.
  645. * \param[in] auth Authentication handle.
  646. * \return User as a null-terminated string.
  647. * \retval NULL If \pr{auth} is null and set the `errno` to `EINVAL`.
  648. */
  649. SG_EXTERN const char *sg_httpauth_usr(struct sg_httpauth *auth);
  650. /**
  651. * Returns the authentication password.
  652. * \param[in] auth Authentication handle.
  653. * \return Password as a null-terminated string.
  654. * \retval NULL If \pr{auth} is null and set the `errno` to `EINVAL`.
  655. */
  656. SG_EXTERN const char *sg_httpauth_pwd(struct sg_httpauth *auth);
  657. /**
  658. * Iterates over all the upload items in the \pr{uplds} list.
  659. * \param[in] uplds Uploads list handle.
  660. * \param[in] cb Callback to iterate over upload items.
  661. * \param[in] cls User-defined closure.
  662. * \retval 0 Success.
  663. * \retval EINVAL Invalid argument.
  664. * \retval E<ERROR> User-defined error to abort the list iteration.
  665. */
  666. SG_EXTERN int sg_httpuplds_iter(struct sg_httpupld *uplds,
  667. sg_httpuplds_iter_cb cb, void *cls);
  668. /**
  669. * Gets the next upload item starting from the first item pointer \pr{upld}.
  670. * \param[in,out] upld Next upload item starting from the first item pointer.
  671. * \retval 0 Success.
  672. * \retval EINVAL Invalid argument.
  673. */
  674. SG_EXTERN int sg_httpuplds_next(struct sg_httpupld **upld);
  675. /**
  676. * Counts the total upload items in the list \pr{uplds}.
  677. * \param[in] uplds Uploads list.
  678. * \return Total of items.
  679. * \retval 0 If the list is empty or null.
  680. */
  681. SG_EXTERN unsigned int sg_httpuplds_count(struct sg_httpupld *uplds);
  682. /**
  683. * Returns the stream handle of the upload handle \pr{upld}.
  684. * \param[in] upld Upload handle.
  685. * \return Stream handle.
  686. * \retval NULL If \pr{upld} is null and set the `errno` to `EINVAL`.
  687. */
  688. SG_EXTERN void *sg_httpupld_handle(struct sg_httpupld *upld);
  689. /**
  690. * Returns the directory of the upload handle \pr{upld}.
  691. * \param[in] upld Upload handle.
  692. * \return Upload directory as a null-terminated string.
  693. * \retval NULL If \pr{upld} is null and set the `errno` to `EINVAL`.
  694. */
  695. SG_EXTERN const char *sg_httpupld_dir(struct sg_httpupld *upld);
  696. /**
  697. * Returns the field of the upload handle \pr{upld}.
  698. * \param[in] upld Upload handle.
  699. * \return Upload field as a null-terminated string.
  700. * \retval NULL If \pr{upld} is null and set the `errno` to `EINVAL`.
  701. */
  702. SG_EXTERN const char *sg_httpupld_field(struct sg_httpupld *upld);
  703. /**
  704. * Returns the name of the upload handle \pr{upld}.
  705. * \param[in] upld Upload handle.
  706. * \return Upload name as a null-terminated string.
  707. * \retval NULL If \pr{upld} is null and set the `errno` to `EINVAL`.
  708. */
  709. SG_EXTERN const char *sg_httpupld_name(struct sg_httpupld *upld);
  710. /**
  711. * Returns the MIME (content-type) of the upload.
  712. * \param[in] upld Upload handle.
  713. * \return Upload MIME as a null-terminated string.
  714. * \retval NULL If \pr{upld} is null and set the `errno` to `EINVAL`.
  715. */
  716. SG_EXTERN const char *sg_httpupld_mime(struct sg_httpupld *upld);
  717. /**
  718. * Returns the encoding (transfer-encoding) of the upload.
  719. * \param[in] upld Upload handle.
  720. * \return Upload encoding as a null-terminated string.
  721. * \retval NULL If \pr{upld} is null and set the `errno` to `EINVAL`.
  722. */
  723. SG_EXTERN const char *sg_httpupld_encoding(struct sg_httpupld *upld);
  724. /**
  725. * Returns the size of the upload.
  726. * \param[in] upld Upload handle.
  727. * \return Upload size into `uint64`. If \pr{upld} is null, set the `errno` to
  728. * `EINVAL`.
  729. */
  730. SG_EXTERN uint64_t sg_httpupld_size(struct sg_httpupld *upld);
  731. /**
  732. * Saves the uploaded file defining the destination path by upload name and
  733. * directory.
  734. * \param[in] upld Upload handle.
  735. * \param[in] overwritten Overwrite upload file if it exists.
  736. * \retval 0 Success.
  737. * \retval EINVAL Invalid argument.
  738. * \retval EEXIST File already exists (if \pr{overwritten} is `false`).
  739. * \retval EISDIR Destination file is a directory.
  740. */
  741. SG_EXTERN int sg_httpupld_save(struct sg_httpupld *upld, bool overwritten);
  742. /**
  743. * Saves the uploaded file allowing to define the destination path.
  744. * \param[in] upld Upload handle.
  745. * \param[in] path Absolute destination path.
  746. * \param[in] overwritten Overwrite upload file if it exists.
  747. * \retval 0 Success.
  748. * \retval EINVAL Invalid argument.
  749. * \retval EEXIST File already exists (if \pr{overwritten} is `true`).
  750. * \retval EISDIR Destination file is a directory.
  751. */
  752. SG_EXTERN int sg_httpupld_save_as(struct sg_httpupld *upld, const char *path,
  753. bool overwritten);
  754. /**
  755. * Returns the server instance.
  756. * \param[in] req Request handle.
  757. * \return Reference to the server instance.
  758. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`
  759. */
  760. SG_EXTERN struct sg_httpsrv *sg_httpreq_srv(struct sg_httpreq *req);
  761. /**
  762. * Returns the client headers into #sg_strmap map.
  763. * \param[in] req Request handle.
  764. * \return Reference to the client headers map.
  765. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`
  766. * \note The headers map is automatically freed by the library.
  767. */
  768. SG_EXTERN struct sg_strmap **sg_httpreq_headers(struct sg_httpreq *req);
  769. /**
  770. * Returns the client cookies into #sg_strmap map.
  771. * \param[in] req Request handle.
  772. * \return Reference to the client cookies map.
  773. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`
  774. * \note The cookies map is automatically freed by the library.
  775. */
  776. SG_EXTERN struct sg_strmap **sg_httpreq_cookies(struct sg_httpreq *req);
  777. /**
  778. * Returns the query-string into #sg_strmap map.
  779. * \param[in] req Request handle.
  780. * \return Reference to the query-string map.
  781. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`
  782. * \note The query-string map is automatically freed by the library.
  783. */
  784. SG_EXTERN struct sg_strmap **sg_httpreq_params(struct sg_httpreq *req);
  785. /**
  786. * Returns the fields of a HTML form into #sg_strmap map.
  787. * \param[in] req Request handle.
  788. * \return Reference to the form fields map.
  789. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`
  790. * \note The form fields map is automatically freed by the library.
  791. */
  792. SG_EXTERN struct sg_strmap **sg_httpreq_fields(struct sg_httpreq *req);
  793. /**
  794. * Returns the HTTP version.
  795. * \param[in] req Request handle.
  796. * \return HTTP version as a null-terminated string.
  797. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  798. */
  799. SG_EXTERN const char *sg_httpreq_version(struct sg_httpreq *req);
  800. /**
  801. * Returns the HTTP method.
  802. * \param[in] req Request handle.
  803. * \return HTTP method as a null-terminated string.
  804. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  805. */
  806. SG_EXTERN const char *sg_httpreq_method(struct sg_httpreq *req);
  807. /**
  808. * Returns the path component.
  809. * \param[in] req Request handle.
  810. * \return Path component as a null-terminated string.
  811. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  812. */
  813. SG_EXTERN const char *sg_httpreq_path(struct sg_httpreq *req);
  814. /**
  815. * Returns the posting payload into a #sg_str instance.
  816. * \param[in] req Request handle.
  817. * \return Instance of the payload.
  818. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  819. * \note The form payload instance is automatically freed by the library.
  820. */
  821. SG_EXTERN struct sg_str *sg_httpreq_payload(struct sg_httpreq *req);
  822. /**
  823. * Checks if the client is uploading data.
  824. * \param[in] req Request handle.
  825. * \retval true If the client is uploading data, `false` otherwise. If \pr{req}
  826. * is null, set the `errno` to `EINVAL`.
  827. */
  828. SG_EXTERN bool sg_httpreq_is_uploading(struct sg_httpreq *req);
  829. /**
  830. * Returns the list of the uploaded files.
  831. * \param[in] req Request handle.
  832. * \return List of the uploaded files.
  833. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  834. * \note The uploads list is automatically freed by the library.
  835. */
  836. SG_EXTERN struct sg_httpupld *sg_httpreq_uploads(struct sg_httpreq *req);
  837. /**
  838. * Gets the socket handle of the client.
  839. * \param[in] req Request handle.
  840. * \return Socket address of the client.
  841. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  842. */
  843. SG_EXTERN const void *sg_httpreq_client(struct sg_httpreq *req);
  844. #ifdef SG_HTTPS_SUPPORT
  845. /**
  846. * Returns the [GnuTLS](https://gnutls.org) session handle.
  847. * \param[in] req Request handle.
  848. * \retval 0 Success.
  849. * \retval EINVAL Invalid argument.
  850. */
  851. SG_EXTERN void *sg_httpreq_tls_session(struct sg_httpreq *req);
  852. #endif /* SG_HTTPS_SUPPORT */
  853. /**
  854. * Isolates a request from the main event loop to an own dedicated thread,
  855. * bringing it back when the request finishes.
  856. * \param[in] req Request handle.
  857. * \param[in] cb Callback to handle requests and responses isolated from the
  858. * main event loop.
  859. * \param[in] cls User-defined closure.
  860. * \retval 0 Success.
  861. * \retval EINVAL Invalid argument.
  862. * \retval ENOMEM Out of memory.
  863. * \retval E<ERROR> Any returned error from the OS threading library.
  864. * \note Isolated requests will not time out.
  865. * \note While a request is isolated, the library will not detect disconnects
  866. * by the client.
  867. */
  868. SG_EXTERN int sg_httpreq_isolate(struct sg_httpreq *req, sg_httpreq_cb cb,
  869. void *cls);
  870. /**
  871. * Sets user data to the request handle.
  872. * \param[in] req Request handle.
  873. * \param[in] data User data pointer.
  874. * \retval 0 Success.
  875. * \retval EINVAL Invalid argument.
  876. */
  877. SG_EXTERN int sg_httpreq_set_user_data(struct sg_httpreq *req, void *data);
  878. /**
  879. * Gets user data from the request handle.
  880. * \param[in] req Request handle.
  881. * \return User data pointer.
  882. * \retval NULL If \pr{req} is null and set the `errno` to `EINVAL`.
  883. */
  884. SG_EXTERN void *sg_httpreq_user_data(struct sg_httpreq *req);
  885. /**
  886. * Returns the server headers into #sg_strmap map.
  887. * \param[in] res Response handle.
  888. * \return Reference to the server headers map.
  889. * \retval NULL If \pr{res} is null and set the `errno` to `EINVAL`
  890. * \note The headers map is automatically freed by the library.
  891. */
  892. SG_EXTERN struct sg_strmap **sg_httpres_headers(struct sg_httpres *res);
  893. /**
  894. * Sets server cookie to the response handle.
  895. * \param[in] res Response handle.
  896. * \param[in] name Cookie name.
  897. * \param[in] val Cookie value.
  898. * \retval 0 Success.
  899. * \retval EINVAL Invalid argument.
  900. * \retval ENOMEM Out of memory.
  901. */
  902. SG_EXTERN int sg_httpres_set_cookie(struct sg_httpres *res, const char *name,
  903. const char *val);
  904. /**
  905. * Sends a null-terminated string content to the client.
  906. * \param[in] res Response handle.
  907. * \param[in] val Null-terminated string.
  908. * \param[in] content_type Content type.
  909. * \param[in] status HTTP status code.
  910. * \retval 0 Success.
  911. * \retval EINVAL Invalid argument.
  912. * \retval EALREADY Operation already in progress.
  913. * \retval ENOMEM Out of memory.
  914. */
  915. #define sg_httpres_send(res, val, content_type, status) \
  916. sg_httpres_sendbinary((res), (void *) (val), \
  917. (((val) != NULL) ? strlen((val)) : 0), (content_type), \
  918. (status))
  919. /**
  920. * Sends a binary content to the client.
  921. * \param[in] res Response handle.
  922. * \param[in] buf Binary content.
  923. * \param[in] size Content size.
  924. * \param[in] content_type Content type.
  925. * \param[in] status HTTP status code.
  926. * \retval 0 Success.
  927. * \retval EINVAL Invalid argument.
  928. * \retval EALREADY Operation already in progress.
  929. * \retval ENOMEM Out of memory.
  930. */
  931. SG_EXTERN int sg_httpres_sendbinary(struct sg_httpres *res, void *buf,
  932. size_t size, const char *content_type,
  933. unsigned int status);
  934. /**
  935. * Offers a file as download.
  936. * \param[in] res Response handle.
  937. * \param[in] filename Path of the file to be sent.
  938. * \param[in] status HTTP status code.
  939. * \retval 0 Success.
  940. * \retval EINVAL Invalid argument.
  941. * \retval EALREADY Operation already in progress.
  942. * \retval EISDIR Is a directory.
  943. * \retval EBADF Bad file number.
  944. * \retval ENOMEM Out of memory.
  945. */
  946. #define sg_httpres_download(res, filename, status) \
  947. sg_httpres_sendfile2((res), 0, 0, 0, (filename), "attachment", (status))
  948. /**
  949. * Sends a file to be rendered.
  950. * \param[in] res Response handle.
  951. * \param[in] filename Path of the file to be sent.
  952. * \param[in] status HTTP status code.
  953. * \retval 0 Success.
  954. * \retval EINVAL Invalid argument.
  955. * \retval EALREADY Operation already in progress.
  956. * \retval EISDIR Is a directory.
  957. * \retval EBADF Bad file number.
  958. * \retval ENOMEM Out of memory.
  959. */
  960. #define sg_httpres_render(res, filename, status) \
  961. sg_httpres_sendfile2((res), 0, 0, 0, (filename), "inline", (status))
  962. /**
  963. * Sends a file to the client.
  964. * \param[in] res Response handle.
  965. * \param[in] size Size of the file to be sent. Use zero to calculate
  966. * automatically.
  967. * \param[in] max_size Maximum allowed file size. Use zero for no limit.
  968. * \param[in] offset Offset to start reading from in the file to be sent.
  969. * \param[in] filename Path of the file to be sent.
  970. * \param[in] disposition Content disposition as a null-terminated string
  971. * (attachment or inline).
  972. * \param[in] status HTTP status code.
  973. * \retval 0 Success.
  974. * \retval EINVAL Invalid argument.
  975. * \retval EALREADY Operation already in progress.
  976. * \retval EISDIR Is a directory.
  977. * \retval EBADF Bad file number.
  978. * \retval EFBIG File too large.
  979. * \retval ENOMEM Out of memory.
  980. * \warning The parameter `disposition` is not checked internally, thus any
  981. * non-`NULL` value is passed directly to the header `Content-Disposition`.
  982. */
  983. SG_EXTERN int sg_httpres_sendfile2(struct sg_httpres *res, uint64_t size,
  984. uint64_t max_size, uint64_t offset,
  985. const char *filename,
  986. const char *disposition,
  987. unsigned int status);
  988. /**
  989. * Sends a file to the client.
  990. * \param[in] res Response handle.
  991. * \param[in] size Size of the file to be sent. Use zero to calculate
  992. * automatically.
  993. * \param[in] max_size Maximum allowed file size. Use zero for no limit.
  994. * \param[in] offset Offset to start reading from in the file to be sent.
  995. * \param[in] filename Path of the file to be sent.
  996. * \param[in] downloaded If `true` it offers the file as download.
  997. * \param[in] status HTTP status code.
  998. * \retval 0 Success.
  999. * \retval EINVAL Invalid argument.
  1000. * \retval EALREADY Operation already in progress.
  1001. * \retval EISDIR Is a directory.
  1002. * \retval EBADF Bad file number.
  1003. * \retval EFBIG File too large.
  1004. * \retval ENOMEM Out of memory.
  1005. */
  1006. SG_EXTERN int sg_httpres_sendfile(struct sg_httpres *res, uint64_t size,
  1007. uint64_t max_size, uint64_t offset,
  1008. const char *filename, bool downloaded,
  1009. unsigned int status);
  1010. /**
  1011. * Sends a stream to the client.
  1012. * \param[in] res Response handle.
  1013. * \param[in] size Size of the stream.
  1014. * \param[in] read_cb Callback to read data from stream handle.
  1015. * \param[in] handle Stream handle.
  1016. * \param[in] free_cb Callback to free the stream handle.
  1017. * \param[in] status HTTP status code.
  1018. * \retval 0 Success.
  1019. * \retval EINVAL Invalid argument.
  1020. * \retval EALREADY Operation already in progress.
  1021. * \retval ENOMEM Out of memory.
  1022. * \note Use `size = 0` if the stream size is unknown.
  1023. */
  1024. SG_EXTERN int sg_httpres_sendstream(struct sg_httpres *res, uint64_t size,
  1025. sg_read_cb read_cb, void *handle,
  1026. sg_free_cb free_cb, unsigned int status);
  1027. #ifdef SG_HTTP_COMPRESSION
  1028. /**
  1029. * Compresses a null-terminated string content and sends it to the client. The
  1030. * compression is done by zlib library using the DEFLATE compression algorithm.
  1031. * \param[in] res Response handle.
  1032. * \param[in] val Null-terminated string.
  1033. * \param[in] content_type Content type.
  1034. * \param[in] status HTTP status code.
  1035. * \retval 0 Success.
  1036. * \retval EINVAL Invalid argument.
  1037. * \retval ENOMEM Out of memory.
  1038. * \retval ENOBUFS No buffer space available.
  1039. * \retval EALREADY Operation already in progress.
  1040. * \retval Z_<ERROR> zlib error as negative number.
  1041. * \note When compression succeeds, the header `Content-Encoding: deflate` is
  1042. * automatically added to the response.
  1043. */
  1044. #define sg_httpres_zsend(res, val, content_type, status) \
  1045. sg_httpres_zsendbinary((res), (void *) (val), \
  1046. (((val) != NULL) ? strlen((val)) : 0), \
  1047. (content_type), (status))
  1048. /**
  1049. * Compresses a binary content and sends it to the client. The compression is
  1050. * done by zlib library using the DEFLATE compression algorithm.
  1051. * \param[in] res Response handle.
  1052. * \param[in] level Compression level (1..9 or -1 for default).
  1053. * \param[in] buf Binary content.
  1054. * \param[in] size Content size.
  1055. * \param[in] content_type Content type.
  1056. * \param[in] status HTTP status code.
  1057. * \retval 0 Success.
  1058. * \retval EINVAL Invalid argument.
  1059. * \retval ENOMEM Out of memory.
  1060. * \retval ENOBUFS No buffer space available.
  1061. * \retval EALREADY Operation already in progress.
  1062. * \retval Z_<ERROR> zlib error as negative number.
  1063. * \note When compression succeeds, the header `Content-Encoding: deflate` is
  1064. * automatically added to the response.
  1065. */
  1066. SG_EXTERN int sg_httpres_zsendbinary2(struct sg_httpres *res, int level,
  1067. void *buf, size_t size,
  1068. const char *content_type,
  1069. unsigned int status);
  1070. /**
  1071. * Compresses a binary content and sends it to the client. The compression is
  1072. * done by zlib library using the DEFLATE compression algorithm.
  1073. * \param[in] res Response handle.
  1074. * \param[in] buf Binary content.
  1075. * \param[in] size Content size.
  1076. * \param[in] content_type Content type.
  1077. * \param[in] status HTTP status code.
  1078. * \retval 0 Success.
  1079. * \retval EINVAL Invalid argument.
  1080. * \retval ENOMEM Out of memory.
  1081. * \retval ENOBUFS No buffer space available.
  1082. * \retval EALREADY Operation already in progress.
  1083. * \retval Z_<ERROR> zlib error as negative number.
  1084. * \note When compression succeeds, the header `Content-Encoding: deflate` is
  1085. * automatically added to the response.
  1086. */
  1087. SG_EXTERN int sg_httpres_zsendbinary(struct sg_httpres *res, void *buf,
  1088. size_t size, const char *content_type,
  1089. unsigned int status);
  1090. /**
  1091. * Compresses a stream and sends it to the client. The compression is done by
  1092. * zlib library using the DEFLATE compression algorithm.
  1093. * \param[in] res Response handle.
  1094. * \param[in] level Compression level (1..9 or -1 for default).
  1095. * \param[in] size Size of the stream.
  1096. * \param[in] read_cb Callback to read data from stream handle.
  1097. * \param[in] handle Stream handle.
  1098. * \param[in] free_cb Callback to free the stream handle.
  1099. * \param[in] status HTTP status code.
  1100. * \retval 0 Success.
  1101. * \retval EINVAL Invalid argument.
  1102. * \retval EALREADY Operation already in progress.
  1103. * \retval ENOMEM Out of memory.
  1104. * \retval Z_<ERROR> zlib error as negative number.
  1105. * \note When compression succeeds, the header `Content-Encoding: deflate` is
  1106. * automatically added to the response.
  1107. */
  1108. SG_EXTERN int sg_httpres_zsendstream2(struct sg_httpres *res, int level,
  1109. uint64_t size, sg_read_cb read_cb,
  1110. void *handle, sg_free_cb free_cb,
  1111. unsigned int status);
  1112. /**
  1113. * Compresses a stream and sends it to the client. The compression is done by
  1114. * zlib library using the DEFLATE compression algorithm.
  1115. * \param[in] res Response handle.
  1116. * \param[in] read_cb Callback to read data from stream handle.
  1117. * \param[in] handle Stream handle.
  1118. * \param[in] free_cb Callback to free the stream handle.
  1119. * \param[in] status HTTP status code.
  1120. * \retval 0 Success.
  1121. * \retval EINVAL Invalid argument.
  1122. * \retval EALREADY Operation already in progress.
  1123. * \retval ENOMEM Out of memory.
  1124. * \retval Z_<ERROR> zlib error as negative number.
  1125. * \note When compression succeeds, the header `Content-Encoding: deflate` is
  1126. * automatically added to the response.
  1127. */
  1128. SG_EXTERN int sg_httpres_zsendstream(struct sg_httpres *res, sg_read_cb read_cb,
  1129. void *handle, sg_free_cb free_cb,
  1130. unsigned int status);
  1131. /**
  1132. * Compresses a file in Gzip format and offers it as download. The compression
  1133. * is done by zlib library using the DEFLATE compression algorithm.
  1134. * \param[in] res Response handle.
  1135. * \param[in] filename Path of the file to be compressed and sent.
  1136. * \param[in] status HTTP status code.
  1137. * \retval 0 Success.
  1138. * \retval EINVAL Invalid argument.
  1139. * \retval EALREADY Operation already in progress.
  1140. * \retval EISDIR Is a directory.
  1141. * \retval EBADF Bad file number.
  1142. * \retval ENOMEM Out of memory.
  1143. * \retval Z_<ERROR> zlib error as negative number.
  1144. * \note When compression succeeds, the header `Content-Encoding: gzip` is
  1145. * automatically added to the response.
  1146. */
  1147. #define sg_httpres_zdownload(res, filename, status) \
  1148. sg_httpres_zsendfile2((res), 1, 0, 0, 0, (filename), "attachment", (status))
  1149. /**
  1150. * Compresses a file in Gzip format and sends it to be rendered. The
  1151. * compression is done by zlib library using the DEFLATE compression algorithm.
  1152. * \param[in] res Response handle.
  1153. * \param[in] filename Path of the file to be sent.
  1154. * \param[in] status HTTP status code.
  1155. * \retval 0 Success.
  1156. * \retval EINVAL Invalid argument.
  1157. * \retval EALREADY Operation already in progress.
  1158. * \retval EISDIR Is a directory.
  1159. * \retval EBADF Bad file number.
  1160. * \retval ENOMEM Out of memory.
  1161. * \retval Z_<ERROR> zlib error as negative number.
  1162. * \note When compression succeeds, the header `Content-Encoding: gzip` is
  1163. * automatically added to the response.
  1164. */
  1165. #define sg_httpres_zrender(res, filename, status) \
  1166. sg_httpres_zsendfile2((res), 1, 0, 0, 0, (filename), "inline", (status))
  1167. /**
  1168. * Compresses a file in Gzip format and sends it to the client. The compression
  1169. * is done by zlib library using the DEFLATE compression algorithm.
  1170. * \param[in] res Response handle.
  1171. * \param[in] level Compression level (1..9 or -1 for default).
  1172. * \param[in] size Size of the file to be sent. Use zero to calculate
  1173. * automatically.
  1174. * \param[in] max_size Maximum allowed file size. Use zero for no limit.
  1175. * \param[in] offset Offset to start reading from in the file to be sent.
  1176. * \param[in] filename Path of the file to be sent.
  1177. * \param[in] disposition Content disposition as a null-terminated string
  1178. * (attachment or inline).
  1179. * \param[in] status HTTP status code.
  1180. * \retval 0 Success.
  1181. * \retval EINVAL Invalid argument.
  1182. * \retval EALREADY Operation already in progress.
  1183. * \retval EISDIR Is a directory.
  1184. * \retval EBADF Bad file number.
  1185. * \retval EFBIG File too large.
  1186. * \retval ENOMEM Out of memory.
  1187. * \retval Z_<ERROR> zlib error as negative number.
  1188. * \note When compression succeeds, the header `Content-Encoding: gzip` is
  1189. * automatically added to the response.
  1190. * \warning The parameter `disposition` is not checked internally, thus any
  1191. * non-`NULL` value is passed directly to the header `Content-Disposition`.
  1192. */
  1193. SG_EXTERN int sg_httpres_zsendfile2(struct sg_httpres *res, int level,
  1194. uint64_t size, uint64_t max_size,
  1195. uint64_t offset, const char *filename,
  1196. const char *disposition,
  1197. unsigned int status);
  1198. /**
  1199. * Compresses a file in Gzip format and sends it to the client. The compression
  1200. * is done by zlib library using the DEFLATE compression algorithm.
  1201. * \param[in] res Response handle.
  1202. * \param[in] size Size of the file to be sent. Use zero to calculate
  1203. * automatically.
  1204. * \param[in] max_size Maximum allowed file size. Use zero for no limit.
  1205. * \param[in] offset Offset to start reading from in the file to be sent.
  1206. * \param[in] filename Path of the file to be sent.
  1207. * \param[in] downloaded If `true` it offers the file as download.
  1208. * \param[in] status HTTP status code.
  1209. * \retval 0 Success.
  1210. * \retval EINVAL Invalid argument.
  1211. * \retval EALREADY Operation already in progress.
  1212. * \retval EISDIR Is a directory.
  1213. * \retval EBADF Bad file number.
  1214. * \retval EFBIG File too large.
  1215. * \retval ENOMEM Out of memory.
  1216. * \retval Z_<ERROR> zlib error as negative number.
  1217. * \note When compression succeeds, the header `Content-Encoding: gzip` is
  1218. * automatically added to the response.
  1219. */
  1220. SG_EXTERN int sg_httpres_zsendfile(struct sg_httpres *res, uint64_t size,
  1221. uint64_t max_size, uint64_t offset,
  1222. const char *filename, bool downloaded,
  1223. unsigned int status);
  1224. #endif /* SG_HTTP_COMPRESSION */
  1225. /**
  1226. * Resets status and internal buffers of the response handle preserving all
  1227. * headers and cookies.
  1228. * \param[in] res Response handle.
  1229. * \retval 0 Success.
  1230. * \retval EINVAL Invalid argument.
  1231. */
  1232. SG_EXTERN int sg_httpres_reset(struct sg_httpres *res);
  1233. /**
  1234. * Clears all headers, cookies, status and internal buffers of the response
  1235. * handle.
  1236. * \param[in] res Response handle.
  1237. * \retval 0 Success.
  1238. * \retval EINVAL Invalid argument.
  1239. */
  1240. SG_EXTERN int sg_httpres_clear(struct sg_httpres *res);
  1241. /**
  1242. * Checks if the response is empty.
  1243. * \param[in] res Response handle.
  1244. * \retval true If the response is empty, `false` otherwise. If \pr{res}
  1245. * is null, set the `errno` to `EINVAL`.
  1246. */
  1247. SG_EXTERN bool sg_httpres_is_empty(struct sg_httpres *res);
  1248. /**
  1249. * Creates a new HTTP server handle.
  1250. * \param[in] auth_cb Callback to grant/deny user access to the server
  1251. * resources.
  1252. * \param[in] req_cb Callback to handle requests and responses.
  1253. * \param[in] err_cb Callback to handle server errors.
  1254. * \param[in] cls User-defined closure.
  1255. * \return New HTTP server handle.
  1256. * \retval NULL
  1257. * - If no memory space is available.
  1258. * - If the \pr{req_cb} or \pr{err_cb} is null and set the `errno` to
  1259. * `EINVAL`.
  1260. * - If a threading operation fails and set its error to `errno`.
  1261. */
  1262. SG_EXTERN struct sg_httpsrv *sg_httpsrv_new2(sg_httpauth_cb auth_cb,
  1263. sg_httpreq_cb req_cb,
  1264. sg_err_cb err_cb,
  1265. void *cls) __SG_MALLOC;
  1266. /**
  1267. * Creates a new HTTP server handle.
  1268. * \param[in] cb Callback to handle requests and responses.
  1269. * \param[in] cls User-defined closure.
  1270. * \return New HTTP server handle.
  1271. * \retval NULL
  1272. * - If the \pr{cb} is null and set the `errno` to `EINVAL`.
  1273. * - If a threading operation fails and set its error to `errno`.
  1274. */
  1275. SG_EXTERN struct sg_httpsrv *sg_httpsrv_new(sg_httpreq_cb cb,
  1276. void *cls) __SG_MALLOC;
  1277. /**
  1278. * Frees the server handle previously allocated by #sg_httpsrv_new() or
  1279. * #sg_httpsrv_new2().
  1280. * \param[in] srv Pointer of the server to be freed.
  1281. * \note If the server is running it stops before being freed.
  1282. */
  1283. SG_EXTERN void sg_httpsrv_free(struct sg_httpsrv *srv);
  1284. #ifdef SG_HTTPS_SUPPORT
  1285. /**
  1286. * Starts the HTTPS server.
  1287. * \param[in] srv Server handle.
  1288. * \param[in] key Memory pointer for the private key (key.pem) to be used by
  1289. * the HTTPS server.
  1290. * \param[in] pwd Password for the private key.
  1291. * \param[in] cert Memory pointer for the certificate (cert.pem) to be used by
  1292. * the HTTPS server.
  1293. * \param[in] trust Memory pointer for the certificate (ca.pem) to be used by
  1294. * the HTTPS server for client authentication.
  1295. * \param[in] dhparams Memory pointer for the Diffie Hellman parameters (dh.pem)
  1296. * to be used by the HTTPS server for key exchange.
  1297. * \param[in] priorities Memory pointer specifying the cipher algorithm.
  1298. * Default: `"NORMAL"`.
  1299. * \param[in] port Port for listening to connections.
  1300. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1301. * server creates one thread per connection.
  1302. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1303. * null, set the `errno` to `EINVAL`.
  1304. * \note If port is `0`, the operating system will assign an unused port
  1305. * randomly.
  1306. */
  1307. SG_EXTERN bool sg_httpsrv_tls_listen3(struct sg_httpsrv *srv, const char *key,
  1308. const char *pwd, const char *cert,
  1309. const char *trust, const char *dhparams,
  1310. const char *priorities, uint16_t port,
  1311. bool threaded);
  1312. /**
  1313. * Starts the HTTPS server.
  1314. * \param[in] srv Server handle.
  1315. * \param[in] key Memory pointer for the private key (key.pem) to be used by
  1316. * the HTTPS server.
  1317. * \param[in] pwd Password for the private key.
  1318. * \param[in] cert Memory pointer for the certificate (cert.pem) to be used by
  1319. * the HTTPS server.
  1320. * \param[in] trust Memory pointer for the certificate (ca.pem) to be used by
  1321. * the HTTPS server for client authentication.
  1322. * \param[in] dhparams Memory pointer for the Diffie Hellman parameters (dh.pem)
  1323. * to be used by the HTTPS server for key exchange.
  1324. * \param[in] port Port for listening to connections.
  1325. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1326. * server creates one thread per connection.
  1327. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1328. * null, set the `errno` to `EINVAL`.
  1329. * \note If port is `0`, the operating system will assign an unused port
  1330. * randomly.
  1331. */
  1332. SG_EXTERN bool sg_httpsrv_tls_listen2(struct sg_httpsrv *srv, const char *key,
  1333. const char *pwd, const char *cert,
  1334. const char *trust, const char *dhparams,
  1335. uint16_t port, bool threaded);
  1336. /**
  1337. * Starts the HTTPS server.
  1338. * \param[in] srv Server handle.
  1339. * \param[in] key Memory pointer for the private key (key.pem) to be used by
  1340. * the HTTPS server.
  1341. * \param[in] cert Memory pointer for the certificate (cert.pem) to be used by
  1342. * the HTTPS server.
  1343. * \param[in] port Port for listening to connections.
  1344. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1345. * server creates one thread per connection.
  1346. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1347. * null, set the `errno` to `EINVAL`.
  1348. * \note If port is `0`, the operating system will assign an unused port
  1349. * randomly.
  1350. */
  1351. SG_EXTERN bool sg_httpsrv_tls_listen(struct sg_httpsrv *srv, const char *key,
  1352. const char *cert, uint16_t port,
  1353. bool threaded);
  1354. #endif /* SG_HTTPS_SUPPORT */
  1355. /**
  1356. * Starts the HTTP server.
  1357. * \param[in] srv Server handle.
  1358. * \param[in] port Port for listening to connections.
  1359. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1360. * server creates one thread per connection.
  1361. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1362. * null, set the `errno` to `EINVAL`.
  1363. * \note If port is `0`, the operating system will randomly assign an unused
  1364. * port.
  1365. */
  1366. SG_EXTERN bool sg_httpsrv_listen(struct sg_httpsrv *srv, uint16_t port,
  1367. bool threaded);
  1368. /**
  1369. * Stops the server not to accept new connections.
  1370. * \param[in] srv Server handle.
  1371. * \retval 0 If the server is stopped.
  1372. * \retval EINVAL Invalid argument.
  1373. * \retval EALREADY Already shut down.
  1374. */
  1375. SG_EXTERN int sg_httpsrv_shutdown(struct sg_httpsrv *srv);
  1376. /**
  1377. * Returns the server listening port.
  1378. * \param[in] srv Server handle.
  1379. * \return Server listening port, `0` otherwise. If \pr{srv} is null, set the
  1380. * `errno` to `EINVAL`.
  1381. */
  1382. SG_EXTERN uint16_t sg_httpsrv_port(struct sg_httpsrv *srv);
  1383. /**
  1384. * Checks if the server was started in threaded mode.
  1385. * \param[in] srv Server handle.
  1386. * \retval true If the server is in threaded mode, `false` otherwise. If
  1387. * \pr{srv} is null, set the `errno` to `EINVAL`.
  1388. */
  1389. SG_EXTERN bool sg_httpsrv_is_threaded(struct sg_httpsrv *srv);
  1390. /**
  1391. * Sets the server callback for client connection events.
  1392. * \param[in] srv Server handle.
  1393. * \param[in] cb Callback to handle client events.
  1394. * \param[in] cls User-defined closure.
  1395. * \retval 0 Success.
  1396. * \retval EINVAL Invalid argument.
  1397. */
  1398. SG_EXTERN int sg_httpsrv_set_cli_cb(struct sg_httpsrv *srv,
  1399. sg_httpsrv_cli_cb cb, void *cls);
  1400. /**
  1401. * Sets the server uploading callbacks.
  1402. * \param[in] srv Server handle.
  1403. * \param[in] cb Callback to handle uploaded files and/or fields.
  1404. * \param[in] cls User-defined closure.
  1405. * \param[in] write_cb Callback to write the stream of the uploaded files.
  1406. * \param[in] free_cb Callback to free stream of the uploaded files.
  1407. * \param[in] save_cb Callback to save the uploaded files.
  1408. * \param[in] save_as_cb Callback to save the uploaded files defining their
  1409. * path.
  1410. * \retval 0 Success.
  1411. * \retval EINVAL Invalid argument.
  1412. */
  1413. SG_EXTERN int sg_httpsrv_set_upld_cbs(struct sg_httpsrv *srv, sg_httpupld_cb cb,
  1414. void *cls, sg_write_cb write_cb,
  1415. sg_free_cb free_cb, sg_save_cb save_cb,
  1416. sg_save_as_cb save_as_cb);
  1417. /**
  1418. * Sets the directory to save the uploaded files.
  1419. * \param[in] srv Server handle.
  1420. * \param[in] dir Directory as a null-terminated string.
  1421. * \retval 0 Success.
  1422. * \retval EINVAL Invalid argument.
  1423. */
  1424. SG_EXTERN int sg_httpsrv_set_upld_dir(struct sg_httpsrv *srv, const char *dir);
  1425. /**
  1426. * Gets the directory of the uploaded files.
  1427. * \param[in] srv Server handle.
  1428. * \return Directory as a null-terminated string.
  1429. * \retval NULL If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1430. */
  1431. SG_EXTERN const char *sg_httpsrv_upld_dir(struct sg_httpsrv *srv);
  1432. /**
  1433. * Sets a size to the post buffering.
  1434. * \param[in] srv Server handle.
  1435. * \param[in] size Post buffering size.
  1436. * \retval 0 Success.
  1437. * \retval EINVAL Invalid argument.
  1438. */
  1439. SG_EXTERN int sg_httpsrv_set_post_buf_size(struct sg_httpsrv *srv, size_t size);
  1440. /**
  1441. * Gets the size of the post buffering.
  1442. * \param[in] srv Server handle.
  1443. * \return Post buffering size.
  1444. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1445. */
  1446. SG_EXTERN size_t sg_httpsrv_post_buf_size(struct sg_httpsrv *srv);
  1447. /**
  1448. * Sets a limit to the total payload.
  1449. * \param[in] srv Server handle.
  1450. * \param[in] limit Payload total limit. Use zero for no limit.
  1451. * \retval 0 Success.
  1452. * \retval EINVAL Invalid argument.
  1453. */
  1454. SG_EXTERN int sg_httpsrv_set_payld_limit(struct sg_httpsrv *srv, size_t limit);
  1455. /**
  1456. * Gets the limit of the total payload.
  1457. * \param[in] srv Server handle.
  1458. * \return Payload total limit.
  1459. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1460. */
  1461. SG_EXTERN size_t sg_httpsrv_payld_limit(struct sg_httpsrv *srv);
  1462. /**
  1463. * Sets a limit to the total uploads.
  1464. * \param[in] srv Server handle.
  1465. * \param[in] limit Uploads total limit. Use zero for no limit.
  1466. * \retval 0 Success.
  1467. * \retval EINVAL Invalid argument.
  1468. */
  1469. SG_EXTERN int sg_httpsrv_set_uplds_limit(struct sg_httpsrv *srv,
  1470. uint64_t limit);
  1471. /**
  1472. * Gets the limit of the total uploads.
  1473. * \param[in] srv Server handle.
  1474. * \return Uploads total limit.
  1475. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1476. */
  1477. SG_EXTERN uint64_t sg_httpsrv_uplds_limit(struct sg_httpsrv *srv);
  1478. /**
  1479. * Sets the size for the thread pool.
  1480. * \param[in] srv Server handle.
  1481. * \param[in] size Thread pool size. Size greater than 1 enables the thread
  1482. * pooling.
  1483. * \retval 0 Success.
  1484. * \retval EINVAL Invalid argument.
  1485. */
  1486. SG_EXTERN int sg_httpsrv_set_thr_pool_size(struct sg_httpsrv *srv,
  1487. unsigned int size);
  1488. /**
  1489. * Gets the size of the thread pool.
  1490. * \param[in] srv Server handle.
  1491. * \return Thread pool size.
  1492. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1493. */
  1494. SG_EXTERN unsigned int sg_httpsrv_thr_pool_size(struct sg_httpsrv *srv);
  1495. /**
  1496. * Sets the inactivity time to a client to get time out.
  1497. * \param[in] srv Server handle.
  1498. * \param[in] timeout Timeout (in seconds). Use zero for infinity timeout. Default: 15 seconds.
  1499. * \retval 0 Success.
  1500. * \retval EINVAL Invalid argument.
  1501. */
  1502. SG_EXTERN int sg_httpsrv_set_con_timeout(struct sg_httpsrv *srv,
  1503. unsigned int timeout);
  1504. /**
  1505. * Gets the inactivity time to a client to get time out.
  1506. * \param[in] srv Server handle.
  1507. * \return Timeout (in seconds).
  1508. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1509. */
  1510. SG_EXTERN unsigned int sg_httpsrv_con_timeout(struct sg_httpsrv *srv);
  1511. /**
  1512. * Sets the limit of concurrent connections.
  1513. * \param[in] srv Server handle.
  1514. * \param[in] limit Concurrent connections limit. Use zero for no limit.
  1515. * \retval 0 Success.
  1516. * \retval EINVAL Invalid argument.
  1517. */
  1518. SG_EXTERN int sg_httpsrv_set_con_limit(struct sg_httpsrv *srv,
  1519. unsigned int limit);
  1520. /**
  1521. * Gets the limit of concurrent connections.
  1522. * \param[in] srv Server handle.
  1523. * \return Concurrent connections limit.
  1524. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1525. */
  1526. SG_EXTERN unsigned int sg_httpsrv_con_limit(struct sg_httpsrv *srv);
  1527. /**
  1528. * Returns the MHD instance.
  1529. * \param[in] srv Server handle.
  1530. * \return MHD instance.
  1531. * \return NULL If the server is shut down.
  1532. * \retval NULL If \pr{srv} is null and set the `errno` to `EINVAL`.
  1533. */
  1534. SG_EXTERN void *sg_httpsrv_handle(struct sg_httpsrv *srv);
  1535. /** \} */
  1536. #ifdef SG_PATH_ROUTING
  1537. /**
  1538. * \ingroup sg_api
  1539. * \defgroup sg_routing Path routing
  1540. * High-performance path routing.
  1541. * \{
  1542. */
  1543. /**
  1544. * Handle for the entry-point handling. It defines an entry-point to a path or
  1545. * resource. For example, given a path `/api1/customer`, the part considered as
  1546. * entry-point is `/api1`.
  1547. * \struct sg_entrypoint
  1548. */
  1549. struct sg_entrypoint;
  1550. /**
  1551. * Returns the name of the entry-point handle \pr{entrypoint}.
  1552. * \param[in] entrypoint Entry-point handle.
  1553. * \return Entry-point name as a null-terminated string.
  1554. * \retval NULL If the \pr{entrypoint} is null and set the `errno` to `EINVAL`.
  1555. */
  1556. SG_EXTERN const char *sg_entrypoint_name(struct sg_entrypoint *entrypoint);
  1557. /**
  1558. * Sets user data to the entry-point handle.
  1559. * \param[in] entrypoint Entry-point handle.
  1560. * \param[in] data User data pointer.
  1561. * \retval 0 Success.
  1562. * \retval EINVAL Invalid argument.
  1563. */
  1564. SG_EXTERN int sg_entrypoint_set_user_data(struct sg_entrypoint *entrypoint,
  1565. void *data);
  1566. /**
  1567. * Gets user data from the entry-point handle.
  1568. * \param[in] entrypoint Entry-point handle.
  1569. * \return User data pointer.
  1570. * \retval NULL If \pr{entrypoint} is null and set the `errno` to `EINVAL`.
  1571. */
  1572. SG_EXTERN void *sg_entrypoint_user_data(struct sg_entrypoint *entrypoint);
  1573. /**
  1574. * Handle for the entry-point list. It is used to create a list of entry-point
  1575. * #sg_entrypoint.
  1576. * \struct sg_entrypoints
  1577. */
  1578. struct sg_entrypoints;
  1579. /**
  1580. * Callback signature used by #sg_entrypoints_iter() to iterate entry-point
  1581. * items.
  1582. * \param[out] cls User-defined closure.
  1583. * \param[out] pair Current iterated entry-point.
  1584. * \retval 0 Success.
  1585. * \retval E<ERROR> User-defined error to stop the items iteration.
  1586. */
  1587. typedef int (*sg_entrypoints_iter_cb)(void *cls,
  1588. struct sg_entrypoint *entrypoint);
  1589. /**
  1590. * Creates a new entry-points handle.
  1591. * \return Entry-points handle.
  1592. * \retval NULL If no memory space is available.
  1593. */
  1594. SG_EXTERN struct sg_entrypoints *sg_entrypoints_new(void) __SG_MALLOC;
  1595. /**
  1596. * Frees the entry-points handle previously allocated by #sg_entrypoints_new().
  1597. * \param[in] entrypoints Pointer of the entry-points to be freed.
  1598. */
  1599. SG_EXTERN void sg_entrypoints_free(struct sg_entrypoints *entrypoints);
  1600. /**
  1601. * Adds a new entry-point item to the entry-points \pr{entrypoints}.
  1602. * \param[in] entrypoints Entry-points handle.
  1603. * \param[in] path Entry-point path.
  1604. * \param[in] user_data User data pointer.
  1605. * \retval 0 Success.
  1606. * \retval EINVAL Invalid argument.
  1607. * \retval ENOMEM Out of memory.
  1608. * \retval EALREADY Entry-point already added.
  1609. */
  1610. SG_EXTERN int sg_entrypoints_add(struct sg_entrypoints *entrypoints,
  1611. const char *path, void *user_data);
  1612. /**
  1613. * Removes an entry-point item from the entry-points \pr{entrypoints}.
  1614. * \param[in] entrypoints Entry-points handle.
  1615. * \param[in] path Entry-point path to be removed.
  1616. * \retval 0 Success.
  1617. * \retval EINVAL Invalid argument.
  1618. * \retval ENOMEM Out of memory.
  1619. * \retval ENOENT Entry-point already removed.
  1620. */
  1621. SG_EXTERN int sg_entrypoints_rm(struct sg_entrypoints *entrypoints,
  1622. const char *path);
  1623. /**
  1624. * Iterates over entry-point items.
  1625. * \param[in] entrypoints Entry-points handle.
  1626. * \param[in] cb Callback to iterate the entry-point items.
  1627. * \param[in,out] cls User-specified value.
  1628. * \retval 0 Success.
  1629. * \retval EINVAL Invalid argument.
  1630. * \return Callback result when it is different from `0`.
  1631. */
  1632. SG_EXTERN int sg_entrypoints_iter(struct sg_entrypoints *entrypoints,
  1633. sg_entrypoints_iter_cb cb, void *cls);
  1634. /**
  1635. * Clears all existing entry-point items in the entry-points \pr{entrypoints}.
  1636. * \param[in] entrypoints Entry-points handle.
  1637. * \retval 0 Success.
  1638. * \retval EINVAL Invalid argument.
  1639. */
  1640. SG_EXTERN int sg_entrypoints_clear(struct sg_entrypoints *entrypoints);
  1641. /**
  1642. * Finds an entry-point item by path.
  1643. * \param[in] entrypoints Entry-points handle.
  1644. * \param[in,out] entrypoint Pointer of the variable to store the found
  1645. * entry-point.
  1646. * \param[in] path Entry-point path to be found.
  1647. * \retval 0 Success.
  1648. * \retval EINVAL Invalid argument.
  1649. * \retval ENOMEM Out of memory.
  1650. * \retval ENOENT Pair not found.
  1651. */
  1652. SG_EXTERN int sg_entrypoints_find(struct sg_entrypoints *entrypoints,
  1653. struct sg_entrypoint **entrypoint,
  1654. const char *path);
  1655. /**
  1656. * Handle for the route item. It holds a user data to be dispatched when a path
  1657. * matches the user defined pattern (route pattern).
  1658. * \struct sg_route
  1659. */
  1660. struct sg_route;
  1661. /**
  1662. * Callback signature used by #sg_route_segments_iter() to iterate the path
  1663. * segments.
  1664. * \param[out] cls User-defined closure.
  1665. * \param[out] index Current iterated item index.
  1666. * \param[out] segment Current iterated segment.
  1667. * \retval 0 Success.
  1668. * \retval E<ERROR> User-defined error to stop the segments iteration.
  1669. */
  1670. typedef int (*sg_segments_iter_cb)(void *cls, unsigned int index,
  1671. const char *segment);
  1672. /**
  1673. * Callback signature used by #sg_route_vars_iter() to iterate the path
  1674. * variables.
  1675. * \param[out] cls User-defined closure.
  1676. * \param[out] name Current iterated variable name.
  1677. * \param[out] val Current iterated variable value.
  1678. * \retval 0 Success.
  1679. * \retval E<ERROR> User-defined error to stop the variables iteration.
  1680. */
  1681. typedef int (*sg_vars_iter_cb)(void *cls, const char *name, const char *val);
  1682. /**
  1683. * Callback signature used to handle the path routing.
  1684. * \param[out] cls User-defined closure.
  1685. * \param[out] route Route handle.
  1686. */
  1687. typedef void (*sg_route_cb)(void *cls, struct sg_route *route);
  1688. /**
  1689. * Callback signature used by #sg_routes_iter() to iterate route items.
  1690. * \param[out] cls User-defined closure.
  1691. * \param[out] route Current iterated route.
  1692. * \retval 0 Success.
  1693. * \retval E<ERROR> User-defined error to stop the route items iteration.
  1694. */
  1695. typedef int (*sg_routes_iter_cb)(void *cls, struct sg_route *route);
  1696. /**
  1697. * Returns the PCRE2 handle containing the compiled regex code.
  1698. * \param[in] route Route handle.
  1699. * \return PCRE2 handle containing the compiled regex code.
  1700. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1701. */
  1702. SG_EXTERN void *sg_route_handle(struct sg_route *route);
  1703. /**
  1704. * Returns the PCRE2 match data created from the route pattern.
  1705. * \param[in] route Route handle.
  1706. * \return PCRE2 match data.
  1707. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1708. */
  1709. SG_EXTERN void *sg_route_match(struct sg_route *route);
  1710. /**
  1711. * Returns the raw route pattern. For example, given a pattern `/foo`, the raw
  1712. * pattern is `^/foo$`.
  1713. * \param[in] route Route handle.
  1714. * \return Raw pattern as a null-terminated string.
  1715. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1716. */
  1717. SG_EXTERN const char *sg_route_rawpattern(struct sg_route *route);
  1718. /**
  1719. * Returns the route pattern.
  1720. * \param[in] route Route handle.
  1721. * \return Pattern as a null-terminated string.
  1722. * \retval NULL
  1723. * - If \pr{route} is null and set the `errno` to `EINVAL`.
  1724. * - If no memory space is available and set the `errno` to `ENOMEM`.
  1725. * \warning The caller must free the returned value.
  1726. */
  1727. SG_EXTERN char *sg_route_pattern(struct sg_route *route) __SG_MALLOC;
  1728. /**
  1729. * Returns the route path.
  1730. * \param[in] route Route handle.
  1731. * \return Path component as a null-terminated string.
  1732. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1733. */
  1734. SG_EXTERN const char *sg_route_path(struct sg_route *route);
  1735. /**
  1736. * Iterates over path segments.
  1737. * \param[in] route Route handle.
  1738. * \param[in] cb Callback to iterate the path segments.
  1739. * \param[in,out] cls User-specified value.
  1740. * \retval 0 Success.
  1741. * \retval EINVAL Invalid argument.
  1742. * \return Callback result when it is different from `0`.
  1743. */
  1744. SG_EXTERN int sg_route_segments_iter(struct sg_route *route,
  1745. sg_segments_iter_cb cb, void *cls);
  1746. /**
  1747. * Iterates over path variables.
  1748. * \param[in] route Route handle.
  1749. * \param[in] cb Callback to iterate the path variables.
  1750. * \param[in,out] cls User-specified value.
  1751. * \retval 0 Success.
  1752. * \retval EINVAL Invalid argument.
  1753. * \retval ENOMEM Out of memory.
  1754. * \return Callback result when it is different from `0`.
  1755. */
  1756. SG_EXTERN int sg_route_vars_iter(struct sg_route *route, sg_vars_iter_cb cb,
  1757. void *cls);
  1758. /**
  1759. * Gets user data from the route handle.
  1760. * \param[in] route Route handle.
  1761. * \return User data pointer.
  1762. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1763. */
  1764. SG_EXTERN void *sg_route_user_data(struct sg_route *route);
  1765. /**
  1766. * Adds a route item to the route list \pr{routes}.
  1767. * \param[in,out] routes Route list pointer to add a new route item.
  1768. * \param[in,out] route Pointer of the variable to store the added route
  1769. * reference.
  1770. * \param[in] pattern Pattern as a null-terminated string. It must be a valid
  1771. * regular expression in PCRE2 syntax.
  1772. * \param[in,out] errmsg Pointer of a string to store the error message.
  1773. * \param[in] errlen Length of the error message.
  1774. * \param[in] cb Callback to handle the path routing.
  1775. * \param[in] cls User-defined closure.
  1776. * \retval 0 Success.
  1777. * \retval EINVAL Invalid argument.
  1778. * \retval EALREADY Route already added.
  1779. * \retval ENOMEM Out of memory.
  1780. * \note The pattern is enclosed between `^` and `$` automatically if it does
  1781. * not start with `(`.
  1782. * \note The escape sequence \\K is not supported. It causes `EINVAL` if used.
  1783. * \note The pattern is compiled using just-in-time optimization (JIT) when it
  1784. * is supported.
  1785. */
  1786. SG_EXTERN int sg_routes_add2(struct sg_route **routes, struct sg_route **route,
  1787. const char *pattern, char *errmsg, size_t errlen,
  1788. sg_route_cb cb, void *cls);
  1789. /**
  1790. * Adds a route item to the route list \pr{routes}. It uses the `stderr` to
  1791. * print the validation errors.
  1792. * \param[in,out] routes Route list pointer to add a new route item.
  1793. * \param[in] pattern Pattern as a null-terminated string. It must be a valid
  1794. * regular expression in PCRE2 syntax.
  1795. * \param[in] cb Callback to handle the path routing.
  1796. * \param[in] cls User-defined closure.
  1797. * \retval 0 Success.
  1798. * \retval EINVAL Invalid argument.
  1799. * \retval EALREADY Route already added.
  1800. * \retval ENOMEM Out of memory.
  1801. * \note The pattern is enclosed between `^` and `$` automatically if it does
  1802. * not start with `(`.
  1803. * \note The escape sequence \\K is not supported. It causes `EINVAL` if used.
  1804. * \note The pattern is compiled using just-in-time optimization (JIT) when it
  1805. * is supported.
  1806. */
  1807. SG_EXTERN bool sg_routes_add(struct sg_route **routes, const char *pattern,
  1808. sg_route_cb cb, void *cls);
  1809. /**
  1810. * Removes a route item from the route list \pr{routes}.
  1811. * \param[in,out] routes Route list pointer to add a new route item.
  1812. * \param[in] pattern Pattern as a null-terminated string of the route to be
  1813. * removed.
  1814. * \retval 0 Success.
  1815. * \retval EINVAL Invalid argument.
  1816. * \retval ENOENT Route already removed.
  1817. */
  1818. SG_EXTERN int sg_routes_rm(struct sg_route **routes, const char *pattern);
  1819. /**
  1820. * Iterates over all the routes in the route list \pr{routes}.
  1821. * \param[in] routes Route list handle.
  1822. * \param[in] cb Callback to iterate over route items.
  1823. * \param[in] cls User-defined closure.
  1824. * \retval 0 Success.
  1825. * \retval EINVAL Invalid argument.
  1826. * \retval E<ERROR> User-defined error to abort the list iteration.
  1827. */
  1828. SG_EXTERN int sg_routes_iter(struct sg_route *routes, sg_routes_iter_cb cb,
  1829. void *cls);
  1830. /**
  1831. * Returns the next route into the route list.
  1832. * \param[in,out] route Pointer to the next route item.
  1833. * \retval 0 Success.
  1834. * \retval EINVAL Invalid argument.
  1835. */
  1836. SG_EXTERN int sg_routes_next(struct sg_route **route);
  1837. /**
  1838. * Counts the total routes in the route list \pr{routes}.
  1839. * \param[in] routes Route list handle.
  1840. * \return Total of route items.
  1841. * \retval 0 If the list is empty or null.
  1842. */
  1843. SG_EXTERN unsigned int sg_routes_count(struct sg_route *routes);
  1844. /**
  1845. * Cleans the entire route list.
  1846. * \param[in,out] routes Pointer to the route list.
  1847. */
  1848. SG_EXTERN int sg_routes_cleanup(struct sg_route **routes);
  1849. /**
  1850. * Handle for the path router. It holds the reference of a route list to be
  1851. * dispatched.
  1852. * \struct sg_router
  1853. */
  1854. struct sg_router;
  1855. /**
  1856. * Callback signature used by #sg_router_dispatch2 in the route dispatching
  1857. * loop.
  1858. * \param[out] cls User-defined closure.
  1859. * \param[out] path Route path as a null-terminated string.
  1860. * \param[out] route Route handle.
  1861. * \retval 0 Success.
  1862. * \retval E<ERROR> User-defined error to stop the route dispatching loop.
  1863. */
  1864. typedef int (*sg_router_dispatch_cb)(void *cls, const char *path,
  1865. struct sg_route *route);
  1866. /**
  1867. * Callback signature used by #sg_router_dispatch2 when the path matches the
  1868. * pattern before the route dispatching.
  1869. * \param[out] cls User-defined closure.
  1870. * \param[out] route Route handle.
  1871. * \retval 0 Success.
  1872. * \retval E<ERROR> User-defined error to stop the route dispatching.
  1873. */
  1874. typedef int (*sg_router_match_cb)(void *cls, struct sg_route *route);
  1875. /**
  1876. * Creates a new path router handle. It requires a filled route list
  1877. * \pr{routes}.
  1878. * \param[in] routes Route list handle.
  1879. * \return New router handle.
  1880. * \retval NULL If the \pr{routes} is null and set the `errno` to `EINVAL` or
  1881. * no memory space.
  1882. */
  1883. SG_EXTERN struct sg_router *sg_router_new(struct sg_route *routes) __SG_MALLOC;
  1884. /**
  1885. * Frees the router handle previously allocated by #sg_router_new().
  1886. * \param[in] router Router handle.
  1887. */
  1888. SG_EXTERN void sg_router_free(struct sg_router *router);
  1889. /**
  1890. * Dispatches a route that its pattern matches the path passed in \pr{path}.
  1891. * \param[in] router Router handle.
  1892. * \param[in] path Path to dispatch a route.
  1893. * \param[in] user_data User data pointer to be held by the route.
  1894. * \param[in] dispatch_cb Callback triggered for each route item in the route
  1895. * dispatching loop.
  1896. * \param[in] cls User-defined closure passed to the \pr{dispatch_cb} and
  1897. * \pr{match_cb} callbacks.
  1898. * \param[in] match_cb Callback triggered when the path matches the route
  1899. * pattern.
  1900. * \retval 0 Success.
  1901. * \retval EINVAL Invalid argument.
  1902. * \retval ENOENT Route not found or path not matched.
  1903. * \retval E<ERROR> User-defined error in \pr{dispatch_cb} or \pr{match_cb}.
  1904. * \note The route callback #sg_route_cb is triggered when the path matches the
  1905. * route pattern.
  1906. * \note The match logic uses just-in-time optimization (JIT) when it is
  1907. * supported.
  1908. */
  1909. SG_EXTERN int sg_router_dispatch2(struct sg_router *router, const char *path,
  1910. void *user_data,
  1911. sg_router_dispatch_cb dispatch_cb, void *cls,
  1912. sg_router_match_cb match_cb);
  1913. /**
  1914. * Dispatches a route that its pattern matches the path passed in \pr{path}.
  1915. * \param[in] router Router handle.
  1916. * \param[in] path Path to dispatch a route.
  1917. * \param[in] user_data User data pointer to be held by the route.
  1918. * \retval 0 Success.
  1919. * \retval EINVAL Invalid argument.
  1920. * \retval ENOENT Route not found or path not matched.
  1921. * \retval E<ERROR> User-defined error in \pr{dispatch_cb} or \pr{match_cb}.
  1922. * \note The route callback #sg_route_cb is triggered when the path matches the
  1923. * route pattern.
  1924. * \note The match logic uses just-in-time optimization (JIT) when it is
  1925. * supported.
  1926. */
  1927. SG_EXTERN int sg_router_dispatch(struct sg_router *router, const char *path,
  1928. void *user_data);
  1929. /** \} */
  1930. #endif /* SG_PATH_ROUTING */
  1931. #ifdef SG_MATH_EXPR_EVAL
  1932. /**
  1933. * \ingroup sg_api
  1934. * \defgroup sg_expr Math expression evaluator
  1935. * Mathematical expression evaluator.
  1936. * \{
  1937. */
  1938. /**
  1939. * Handle for the mathematical expression evaluator.
  1940. * \struct sg_expr
  1941. */
  1942. struct sg_expr;
  1943. /**
  1944. * Possible error types returned by the mathematical expression evaluator.
  1945. * \enum sg_expr_err_type
  1946. */
  1947. enum sg_expr_err_type {
  1948. /** Error not related to evaluation, e.g. `EINVAL`. */
  1949. SG_EXPR_ERR_UNKNOWN,
  1950. /** Unexpected number, e.g. `"(1+2)3"`. */
  1951. SG_EXPR_ERR_UNEXPECTED_NUMBER,
  1952. /** Unexpected word, e.g. `"(1+2)x"`. */
  1953. SG_EXPR_ERR_UNEXPECTED_WORD,
  1954. /** Unexpected parenthesis, e.g. `"1(2+3)"`. */
  1955. SG_EXPR_ERR_UNEXPECTED_PARENS,
  1956. /** Missing expected operand, e.g. `"0^+1"`. */
  1957. SG_EXPR_ERR_MISSING_OPERAND,
  1958. /** Unknown operator, e.g. `"(1+2)."`. */
  1959. SG_EXPR_ERR_UNKNOWN_OPERATOR,
  1960. /** Invalid function name, e.g. `"unknownfunc()"`. */
  1961. SG_EXPR_ERR_INVALID_FUNC_NAME,
  1962. /** Bad parenthesis, e.g. `"(1+2"`. */
  1963. SG_EXPR_ERR_BAD_PARENS,
  1964. /** Too few arguments passed to a macro, e.g. `"$()"`. */
  1965. SG_EXPR_ERR_TOO_FEW_FUNC_ARGS,
  1966. /** First macro argument is not variable, e.g. `"$(1)"`. */
  1967. SG_EXPR_ERR_FIRST_ARG_IS_NOT_VAR,
  1968. /** Bad variable name, e.g. `"2.3.4"`. */
  1969. SG_EXPR_ERR_BAD_VARIABLE_NAME,
  1970. /** Bad assignment, e.g. `"2=3"`. */
  1971. SG_EXPR_ERR_BAD_ASSIGNMENT
  1972. };
  1973. /**
  1974. * Handle to access a user-defined function registered in the mathematical
  1975. * expression extension.
  1976. * \struct sg_expr_argument
  1977. */
  1978. struct sg_expr_argument;
  1979. /**
  1980. * Callback signature to specify a function at build time to be executed at
  1981. * run time in a mathematical expression.
  1982. * \param[out] cls User-defined closure.
  1983. * \param[out] args Floating-point arguments passed to the function.
  1984. * \param[out] identifier Null-terminated string to identify the function.
  1985. * \return Floating-point value calculated at build time to be used at run time
  1986. * in a mathematical expression.
  1987. */
  1988. typedef double (*sg_expr_func)(void *cls, struct sg_expr_argument *args,
  1989. const char *identifier);
  1990. /**
  1991. * Handle for the mathematical expression evaluator extension.
  1992. * \struct sg_expr_extension
  1993. */
  1994. struct sg_expr_extension {
  1995. /** User-defined function to be executed at run time in a mathematical
  1996. * expression. */
  1997. sg_expr_func func;
  1998. /** Null-terminated to identify the function. */
  1999. const char *identifier;
  2000. /** User-defined closure. */
  2001. void *cls;
  2002. };
  2003. /**
  2004. * Creates a new mathematical expression evaluator handle.
  2005. * \return New mathematical expression evaluator handle.
  2006. * \retval NULL If no memory space is available and set the `errno` to
  2007. * `ENOMEM`.
  2008. */
  2009. SG_EXTERN struct sg_expr *sg_expr_new(void) __SG_MALLOC;
  2010. /**
  2011. * Frees the mathematical expression evaluator handle previously allocated by
  2012. * #sg_expr_new().
  2013. * \param[in] expr Expression evaluator handle.
  2014. */
  2015. SG_EXTERN void sg_expr_free(struct sg_expr *expr);
  2016. /**
  2017. * Compiles a mathematical expression allowing to declare variables, macros and
  2018. * extensions.
  2019. * \param[in] expr Mathematical expression instance.
  2020. * \param[in] str Null-terminated string with the mathematical expression to be
  2021. * compiled.
  2022. * \param[in] len Length of the mathematical expression to be compiled.
  2023. * \param[in] extensions Array of extensions to extend the evaluator.
  2024. * \note The extension array must be terminated by a zeroed item.
  2025. * \retval 0 Success.
  2026. * \retval EINVAL Invalid argument.
  2027. * \retval ENOENT Missing a needed extenssion.
  2028. * \retval EALREADY Mathematical expression already compiled.
  2029. * \retval ENOMEM Out of memory.
  2030. */
  2031. SG_EXTERN int sg_expr_compile(struct sg_expr *expr, const char *str, size_t len,
  2032. struct sg_expr_extension *extensions);
  2033. /**
  2034. * Clears a mathematical expression instance.
  2035. * \param[in] expr Mathematical expression instance.
  2036. * \retval 0 Success.
  2037. * \retval EINVAL Invalid argument.
  2038. */
  2039. SG_EXTERN int sg_expr_clear(struct sg_expr *expr);
  2040. /**
  2041. * Evaluates a compiled mathematical expression.
  2042. * \param[in] expr Compiled mathematical expression.
  2043. * \return Floating-point value of the evaluated mathematical expression.
  2044. * \retval NAN If the \pr{expr} is null and set the `errno` to `EINVAL`.
  2045. */
  2046. SG_EXTERN double sg_expr_eval(struct sg_expr *expr);
  2047. /**
  2048. * Gets the value of a declared variable.
  2049. * \param[in] expr Mathematical expression instance.
  2050. * \param[in] name Name of the declared variable.
  2051. * \param[in] len Length of the variable name.
  2052. * \retval NAN
  2053. * - If \pr{expr} or \pr{name} is null, or \pr{len} is less than one, and set
  2054. * the `errno` to `EINVAL`.
  2055. * - If no memory space is available and set the `errno` to `ENOMEM`.
  2056. */
  2057. SG_EXTERN double sg_expr_var(struct sg_expr *expr, const char *name,
  2058. size_t len);
  2059. /**
  2060. * Sets a variable to the mathematical expression.
  2061. * \param[in] expr Mathematical expression instance.
  2062. * \param[in] name Name for the variable.
  2063. * \param[in] len Length of the variable name.
  2064. * \param[in] val Value for the variable.
  2065. * \retval 0 Success.
  2066. * \retval EINVAL Invalid argument.
  2067. * \retval ENOMEM Out of memory.
  2068. */
  2069. SG_EXTERN int sg_expr_set_var(struct sg_expr *expr, const char *name,
  2070. size_t len, double val);
  2071. /**
  2072. * Gets a function argument by its index.
  2073. * \param[in] args Arguments list.
  2074. * \param[in] index Argument index.
  2075. * \retval NAN If the \pr{args} is null or \pr{index} is less than zero and
  2076. * set the `errno` to `EINVAL`.
  2077. */
  2078. SG_EXTERN double sg_expr_arg(struct sg_expr_argument *args, int index);
  2079. /**
  2080. * Returns the nearby position of an error in the mathematical expression.
  2081. * \param[in] expr Compiled mathematical expression.
  2082. * \retval 0 Success.
  2083. * \retval EINVAL Invalid argument.
  2084. */
  2085. SG_EXTERN int sg_expr_near(struct sg_expr *expr);
  2086. /**
  2087. * Returns the type of an error in the mathematical expression.
  2088. * \param[in] expr Compiled mathematical expression.
  2089. * \return Enumerator representing the error type.
  2090. * \retval SG_EXPR_ERR_UNKNOWN If the \pr{expr} is null or an unknown error
  2091. * occurred and set the `errno` to `EINVAL`.
  2092. */
  2093. SG_EXTERN enum sg_expr_err_type sg_expr_err(struct sg_expr *expr);
  2094. /**
  2095. * Returns the description of an error in the mathematical expression.
  2096. * \param[in] expr Compiled mathematical expression.
  2097. * \return Description of the error as a null-terminated string.
  2098. * \retval NULL If the \pr{expr} is null and set the `errno` to `EINVAL`.
  2099. */
  2100. SG_EXTERN const char *sg_expr_strerror(struct sg_expr *expr);
  2101. /**
  2102. * Returns the evaluated value of a mathematical expression.
  2103. * \param[in] str Null-terminated string with the mathematical expression to be
  2104. * evaluated.
  2105. * \param[in] len Length of the mathematical expression to be evaluated.
  2106. * \retval NAN If \pr{str} is null, or \pr{len} is less than one, and set the
  2107. * `errno` to `EINVAL`.
  2108. */
  2109. SG_EXTERN double sg_expr_calc(const char *str, size_t len);
  2110. /** \} */
  2111. #endif /* SG_MATH_EXPR_EVAL */
  2112. #ifdef __cplusplus
  2113. }
  2114. #endif
  2115. #endif /* SAGUI_H */