sagui.h 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2025 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 5
  67. #define SG_VERSION_PATCH 2
  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] hostname Host name for listening to connections.
  1300. * \param[in] port Port for listening to connections.
  1301. * \param[in] backlog Maximum length of the queue of pending connections.
  1302. * Default: `511`.
  1303. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1304. * server creates one thread per connection.
  1305. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1306. * null, set the `errno` to `EINVAL`.
  1307. * \note If port is `0`, the operating system will assign an unused port
  1308. * randomly.
  1309. */
  1310. SG_EXTERN bool sg_httpsrv_tls_listen4(struct sg_httpsrv *srv, const char *key,
  1311. const char *pwd, const char *cert,
  1312. const char *trust, const char *dhparams,
  1313. const char *priorities,
  1314. const char *hostname, uint16_t port,
  1315. uint32_t backlog, bool threaded);
  1316. /**
  1317. * Starts the HTTPS server.
  1318. * \param[in] srv Server handle.
  1319. * \param[in] key Memory pointer for the private key (key.pem) to be used by
  1320. * the HTTPS server.
  1321. * \param[in] pwd Password for the private key.
  1322. * \param[in] cert Memory pointer for the certificate (cert.pem) to be used by
  1323. * the HTTPS server.
  1324. * \param[in] trust Memory pointer for the certificate (ca.pem) to be used by
  1325. * the HTTPS server for client authentication.
  1326. * \param[in] dhparams Memory pointer for the Diffie Hellman parameters (dh.pem)
  1327. * to be used by the HTTPS server for key exchange.
  1328. * \param[in] priorities Memory pointer specifying the cipher algorithm.
  1329. * Default: `"NORMAL"`.
  1330. * \param[in] port Port for listening to connections.
  1331. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1332. * server creates one thread per connection.
  1333. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1334. * null, set the `errno` to `EINVAL`.
  1335. * \note If port is `0`, the operating system will assign an unused port
  1336. * randomly.
  1337. */
  1338. SG_EXTERN bool sg_httpsrv_tls_listen3(struct sg_httpsrv *srv, const char *key,
  1339. const char *pwd, const char *cert,
  1340. const char *trust, const char *dhparams,
  1341. const char *priorities, uint16_t port,
  1342. bool threaded);
  1343. /**
  1344. * Starts the HTTPS server.
  1345. * \param[in] srv Server handle.
  1346. * \param[in] key Memory pointer for the private key (key.pem) to be used by
  1347. * the HTTPS server.
  1348. * \param[in] pwd Password for the private key.
  1349. * \param[in] cert Memory pointer for the certificate (cert.pem) to be used by
  1350. * the HTTPS server.
  1351. * \param[in] trust Memory pointer for the certificate (ca.pem) to be used by
  1352. * the HTTPS server for client authentication.
  1353. * \param[in] dhparams Memory pointer for the Diffie Hellman parameters (dh.pem)
  1354. * to be used by the HTTPS server for key exchange.
  1355. * \param[in] port Port for listening to connections.
  1356. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1357. * server creates one thread per connection.
  1358. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1359. * null, set the `errno` to `EINVAL`.
  1360. * \note If port is `0`, the operating system will assign an unused port
  1361. * randomly.
  1362. */
  1363. SG_EXTERN bool sg_httpsrv_tls_listen2(struct sg_httpsrv *srv, const char *key,
  1364. const char *pwd, const char *cert,
  1365. const char *trust, const char *dhparams,
  1366. uint16_t port, bool threaded);
  1367. /**
  1368. * Starts the HTTPS server.
  1369. * \param[in] srv Server handle.
  1370. * \param[in] key Memory pointer for the private key (key.pem) to be used by
  1371. * the HTTPS server.
  1372. * \param[in] cert Memory pointer for the certificate (cert.pem) to be used by
  1373. * the HTTPS server.
  1374. * \param[in] port Port for listening to connections.
  1375. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1376. * server creates one thread per connection.
  1377. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1378. * null, set the `errno` to `EINVAL`.
  1379. * \note If port is `0`, the operating system will assign an unused port
  1380. * randomly.
  1381. */
  1382. SG_EXTERN bool sg_httpsrv_tls_listen(struct sg_httpsrv *srv, const char *key,
  1383. const char *cert, uint16_t port,
  1384. bool threaded);
  1385. #endif /* SG_HTTPS_SUPPORT */
  1386. /**
  1387. * Starts the HTTP server.
  1388. * \param[in] srv Server handle.
  1389. * \param[in] hostname Host name for listening to connections.
  1390. * \param[in] port Port for listening to connections.
  1391. * \param[in] backlog Maximum length of the queue of pending connections.
  1392. * Default: `511`.
  1393. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1394. * server creates one thread per connection.
  1395. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1396. * null, set the `errno` to `EINVAL`.
  1397. * \note If port is `0`, the operating system will randomly assign an unused
  1398. * port.
  1399. */
  1400. SG_EXTERN bool sg_httpsrv_listen2(struct sg_httpsrv *srv, const char *hostname,
  1401. uint16_t port, uint32_t backlog,
  1402. bool threaded);
  1403. /**
  1404. * Starts the HTTP server.
  1405. * \param[in] srv Server handle.
  1406. * \param[in] port Port for listening to connections.
  1407. * \param[in] threaded Enables/disables the threaded mode. If `true`, the
  1408. * server creates one thread per connection.
  1409. * \retval true If the server is started, `false` otherwise. If \pr{srv} is
  1410. * null, set the `errno` to `EINVAL`.
  1411. * \note If port is `0`, the operating system will randomly assign an unused
  1412. * port.
  1413. */
  1414. SG_EXTERN bool sg_httpsrv_listen(struct sg_httpsrv *srv, uint16_t port,
  1415. bool threaded);
  1416. /**
  1417. * Stops the server not to accept new connections.
  1418. * \param[in] srv Server handle.
  1419. * \retval 0 If the server is stopped.
  1420. * \retval EINVAL Invalid argument.
  1421. * \retval EALREADY Already shut down.
  1422. */
  1423. SG_EXTERN int sg_httpsrv_shutdown(struct sg_httpsrv *srv);
  1424. /**
  1425. * Returns the server listening port.
  1426. * \param[in] srv Server handle.
  1427. * \return Server listening port, `0` otherwise. If \pr{srv} is null, set the
  1428. * `errno` to `EINVAL`.
  1429. */
  1430. SG_EXTERN uint16_t sg_httpsrv_port(struct sg_httpsrv *srv);
  1431. /**
  1432. * Checks if the server was started in threaded mode.
  1433. * \param[in] srv Server handle.
  1434. * \retval true If the server is in threaded mode, `false` otherwise. If
  1435. * \pr{srv} is null, set the `errno` to `EINVAL`.
  1436. */
  1437. SG_EXTERN bool sg_httpsrv_is_threaded(struct sg_httpsrv *srv);
  1438. /**
  1439. * Sets the server callback for client connection events.
  1440. * \param[in] srv Server handle.
  1441. * \param[in] cb Callback to handle client events.
  1442. * \param[in] cls User-defined closure.
  1443. * \retval 0 Success.
  1444. * \retval EINVAL Invalid argument.
  1445. */
  1446. SG_EXTERN int sg_httpsrv_set_cli_cb(struct sg_httpsrv *srv,
  1447. sg_httpsrv_cli_cb cb, void *cls);
  1448. /**
  1449. * Sets the server uploading callbacks.
  1450. * \param[in] srv Server handle.
  1451. * \param[in] cb Callback to handle uploaded files and/or fields.
  1452. * \param[in] cls User-defined closure.
  1453. * \param[in] write_cb Callback to write the stream of the uploaded files.
  1454. * \param[in] free_cb Callback to free stream of the uploaded files.
  1455. * \param[in] save_cb Callback to save the uploaded files.
  1456. * \param[in] save_as_cb Callback to save the uploaded files defining their
  1457. * path.
  1458. * \retval 0 Success.
  1459. * \retval EINVAL Invalid argument.
  1460. */
  1461. SG_EXTERN int sg_httpsrv_set_upld_cbs(struct sg_httpsrv *srv, sg_httpupld_cb cb,
  1462. void *cls, sg_write_cb write_cb,
  1463. sg_free_cb free_cb, sg_save_cb save_cb,
  1464. sg_save_as_cb save_as_cb);
  1465. /**
  1466. * Sets the directory to save the uploaded files.
  1467. * \param[in] srv Server handle.
  1468. * \param[in] dir Directory as a null-terminated string.
  1469. * \retval 0 Success.
  1470. * \retval EINVAL Invalid argument.
  1471. */
  1472. SG_EXTERN int sg_httpsrv_set_upld_dir(struct sg_httpsrv *srv, const char *dir);
  1473. /**
  1474. * Gets the directory of the uploaded files.
  1475. * \param[in] srv Server handle.
  1476. * \return Directory as a null-terminated string.
  1477. * \retval NULL If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1478. */
  1479. SG_EXTERN const char *sg_httpsrv_upld_dir(struct sg_httpsrv *srv);
  1480. /**
  1481. * Sets a size to the post buffering.
  1482. * \param[in] srv Server handle.
  1483. * \param[in] size Post buffering size.
  1484. * \retval 0 Success.
  1485. * \retval EINVAL Invalid argument.
  1486. */
  1487. SG_EXTERN int sg_httpsrv_set_post_buf_size(struct sg_httpsrv *srv, size_t size);
  1488. /**
  1489. * Gets the size of the post buffering.
  1490. * \param[in] srv Server handle.
  1491. * \return Post buffering size.
  1492. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1493. */
  1494. SG_EXTERN size_t sg_httpsrv_post_buf_size(struct sg_httpsrv *srv);
  1495. /**
  1496. * Sets a limit to the total payload.
  1497. * \param[in] srv Server handle.
  1498. * \param[in] limit Payload total limit. Use zero for no limit.
  1499. * \retval 0 Success.
  1500. * \retval EINVAL Invalid argument.
  1501. */
  1502. SG_EXTERN int sg_httpsrv_set_payld_limit(struct sg_httpsrv *srv, size_t limit);
  1503. /**
  1504. * Gets the limit of the total payload.
  1505. * \param[in] srv Server handle.
  1506. * \return Payload total limit.
  1507. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1508. */
  1509. SG_EXTERN size_t sg_httpsrv_payld_limit(struct sg_httpsrv *srv);
  1510. /**
  1511. * Sets a limit to the total uploads.
  1512. * \param[in] srv Server handle.
  1513. * \param[in] limit Uploads total limit. Use zero for no limit.
  1514. * \retval 0 Success.
  1515. * \retval EINVAL Invalid argument.
  1516. */
  1517. SG_EXTERN int sg_httpsrv_set_uplds_limit(struct sg_httpsrv *srv,
  1518. uint64_t limit);
  1519. /**
  1520. * Gets the limit of the total uploads.
  1521. * \param[in] srv Server handle.
  1522. * \return Uploads total limit.
  1523. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1524. */
  1525. SG_EXTERN uint64_t sg_httpsrv_uplds_limit(struct sg_httpsrv *srv);
  1526. /**
  1527. * Sets the size for the thread pool.
  1528. * \param[in] srv Server handle.
  1529. * \param[in] size Thread pool size. Size greater than 1 enables the thread
  1530. * pooling.
  1531. * \retval 0 Success.
  1532. * \retval EINVAL Invalid argument.
  1533. */
  1534. SG_EXTERN int sg_httpsrv_set_thr_pool_size(struct sg_httpsrv *srv,
  1535. unsigned int size);
  1536. /**
  1537. * Gets the size of the thread pool.
  1538. * \param[in] srv Server handle.
  1539. * \return Thread pool size.
  1540. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1541. */
  1542. SG_EXTERN unsigned int sg_httpsrv_thr_pool_size(struct sg_httpsrv *srv);
  1543. /**
  1544. * Sets the inactivity time to a client to get time out.
  1545. * \param[in] srv Server handle.
  1546. * \param[in] timeout Timeout (in seconds). Use zero for infinity timeout. Default: 15 seconds.
  1547. * \retval 0 Success.
  1548. * \retval EINVAL Invalid argument.
  1549. */
  1550. SG_EXTERN int sg_httpsrv_set_con_timeout(struct sg_httpsrv *srv,
  1551. unsigned int timeout);
  1552. /**
  1553. * Gets the inactivity time to a client to get time out.
  1554. * \param[in] srv Server handle.
  1555. * \return Timeout (in seconds).
  1556. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1557. */
  1558. SG_EXTERN unsigned int sg_httpsrv_con_timeout(struct sg_httpsrv *srv);
  1559. /**
  1560. * Sets the limit of concurrent connections.
  1561. * \param[in] srv Server handle.
  1562. * \param[in] limit Concurrent connections limit. Use zero for no limit.
  1563. * \retval 0 Success.
  1564. * \retval EINVAL Invalid argument.
  1565. */
  1566. SG_EXTERN int sg_httpsrv_set_con_limit(struct sg_httpsrv *srv,
  1567. unsigned int limit);
  1568. /**
  1569. * Gets the limit of concurrent connections.
  1570. * \param[in] srv Server handle.
  1571. * \return Concurrent connections limit.
  1572. * \retval 0 If the \pr{srv} is null and set the `errno` to `EINVAL`.
  1573. */
  1574. SG_EXTERN unsigned int sg_httpsrv_con_limit(struct sg_httpsrv *srv);
  1575. /**
  1576. * Returns the MHD instance.
  1577. * \param[in] srv Server handle.
  1578. * \return MHD instance.
  1579. * \return NULL If the server is shut down.
  1580. * \retval NULL If \pr{srv} is null and set the `errno` to `EINVAL`.
  1581. */
  1582. SG_EXTERN void *sg_httpsrv_handle(struct sg_httpsrv *srv);
  1583. /** \} */
  1584. #ifdef SG_PATH_ROUTING
  1585. /**
  1586. * \ingroup sg_api
  1587. * \defgroup sg_routing Path routing
  1588. * High-performance path routing.
  1589. * \{
  1590. */
  1591. /**
  1592. * Handle for the entry-point handling. It defines an entry-point to a path or
  1593. * resource. For example, given a path `/api1/customer`, the part considered as
  1594. * entry-point is `/api1`.
  1595. * \struct sg_entrypoint
  1596. */
  1597. struct sg_entrypoint;
  1598. /**
  1599. * Returns the name of the entry-point handle \pr{entrypoint}.
  1600. * \param[in] entrypoint Entry-point handle.
  1601. * \return Entry-point name as a null-terminated string.
  1602. * \retval NULL If the \pr{entrypoint} is null and set the `errno` to `EINVAL`.
  1603. */
  1604. SG_EXTERN const char *sg_entrypoint_name(struct sg_entrypoint *entrypoint);
  1605. /**
  1606. * Sets user data to the entry-point handle.
  1607. * \param[in] entrypoint Entry-point handle.
  1608. * \param[in] data User data pointer.
  1609. * \retval 0 Success.
  1610. * \retval EINVAL Invalid argument.
  1611. */
  1612. SG_EXTERN int sg_entrypoint_set_user_data(struct sg_entrypoint *entrypoint,
  1613. void *data);
  1614. /**
  1615. * Gets user data from the entry-point handle.
  1616. * \param[in] entrypoint Entry-point handle.
  1617. * \return User data pointer.
  1618. * \retval NULL If \pr{entrypoint} is null and set the `errno` to `EINVAL`.
  1619. */
  1620. SG_EXTERN void *sg_entrypoint_user_data(struct sg_entrypoint *entrypoint);
  1621. /**
  1622. * Handle for the entry-point list. It is used to create a list of entry-point
  1623. * #sg_entrypoint.
  1624. * \struct sg_entrypoints
  1625. */
  1626. struct sg_entrypoints;
  1627. /**
  1628. * Callback signature used by #sg_entrypoints_iter() to iterate entry-point
  1629. * items.
  1630. * \param[out] cls User-defined closure.
  1631. * \param[out] entrypoint Current iterated entry-point.
  1632. * \retval 0 Success.
  1633. * \retval E<ERROR> User-defined error to stop the items iteration.
  1634. */
  1635. typedef int (*sg_entrypoints_iter_cb)(void *cls,
  1636. struct sg_entrypoint *entrypoint);
  1637. /**
  1638. * Creates a new entry-points handle.
  1639. * \return Entry-points handle.
  1640. * \retval NULL If no memory space is available.
  1641. */
  1642. SG_EXTERN struct sg_entrypoints *sg_entrypoints_new(void) __SG_MALLOC;
  1643. /**
  1644. * Frees the entry-points handle previously allocated by #sg_entrypoints_new().
  1645. * \param[in] entrypoints Pointer of the entry-points to be freed.
  1646. */
  1647. SG_EXTERN void sg_entrypoints_free(struct sg_entrypoints *entrypoints);
  1648. /**
  1649. * Adds a new entry-point item to the entry-points \pr{entrypoints}.
  1650. * \param[in] entrypoints Entry-points handle.
  1651. * \param[in] path Entry-point path.
  1652. * \param[in] user_data User data pointer.
  1653. * \retval 0 Success.
  1654. * \retval EINVAL Invalid argument.
  1655. * \retval ENOMEM Out of memory.
  1656. * \retval EALREADY Entry-point already added.
  1657. */
  1658. SG_EXTERN int sg_entrypoints_add(struct sg_entrypoints *entrypoints,
  1659. const char *path, void *user_data);
  1660. /**
  1661. * Removes an entry-point item from the entry-points \pr{entrypoints}.
  1662. * \param[in] entrypoints Entry-points handle.
  1663. * \param[in] path Entry-point path to be removed.
  1664. * \retval 0 Success.
  1665. * \retval EINVAL Invalid argument.
  1666. * \retval ENOMEM Out of memory.
  1667. * \retval ENOENT Entry-point already removed.
  1668. */
  1669. SG_EXTERN int sg_entrypoints_rm(struct sg_entrypoints *entrypoints,
  1670. const char *path);
  1671. /**
  1672. * Iterates over entry-point items.
  1673. * \param[in] entrypoints Entry-points handle.
  1674. * \param[in] cb Callback to iterate the entry-point items.
  1675. * \param[in,out] cls User-specified value.
  1676. * \retval 0 Success.
  1677. * \retval EINVAL Invalid argument.
  1678. * \return Callback result when it is different from `0`.
  1679. */
  1680. SG_EXTERN int sg_entrypoints_iter(struct sg_entrypoints *entrypoints,
  1681. sg_entrypoints_iter_cb cb, void *cls);
  1682. /**
  1683. * Clears all existing entry-point items in the entry-points \pr{entrypoints}.
  1684. * \param[in] entrypoints Entry-points handle.
  1685. * \retval 0 Success.
  1686. * \retval EINVAL Invalid argument.
  1687. */
  1688. SG_EXTERN int sg_entrypoints_clear(struct sg_entrypoints *entrypoints);
  1689. /**
  1690. * Finds an entry-point item by path.
  1691. * \param[in] entrypoints Entry-points handle.
  1692. * \param[in,out] entrypoint Pointer of the variable to store the found
  1693. * entry-point.
  1694. * \param[in] path Entry-point path to be found.
  1695. * \retval 0 Success.
  1696. * \retval EINVAL Invalid argument.
  1697. * \retval ENOMEM Out of memory.
  1698. * \retval ENOENT Pair not found.
  1699. */
  1700. SG_EXTERN int sg_entrypoints_find(struct sg_entrypoints *entrypoints,
  1701. struct sg_entrypoint **entrypoint,
  1702. const char *path);
  1703. /**
  1704. * Handle for the route item. It holds a user data to be dispatched when a path
  1705. * matches the user defined pattern (route pattern).
  1706. * \struct sg_route
  1707. */
  1708. struct sg_route;
  1709. /**
  1710. * Callback signature used by #sg_route_segments_iter() to iterate the path
  1711. * segments.
  1712. * \param[out] cls User-defined closure.
  1713. * \param[out] index Current iterated item index.
  1714. * \param[out] segment Current iterated segment.
  1715. * \retval 0 Success.
  1716. * \retval E<ERROR> User-defined error to stop the segments iteration.
  1717. */
  1718. typedef int (*sg_segments_iter_cb)(void *cls, unsigned int index,
  1719. const char *segment);
  1720. /**
  1721. * Callback signature used by #sg_route_vars_iter() to iterate the path
  1722. * variables.
  1723. * \param[out] cls User-defined closure.
  1724. * \param[out] name Current iterated variable name.
  1725. * \param[out] val Current iterated variable value.
  1726. * \retval 0 Success.
  1727. * \retval E<ERROR> User-defined error to stop the variables iteration.
  1728. */
  1729. typedef int (*sg_vars_iter_cb)(void *cls, const char *name, const char *val);
  1730. /**
  1731. * Callback signature used to handle the path routing.
  1732. * \param[out] cls User-defined closure.
  1733. * \param[out] route Route handle.
  1734. */
  1735. typedef void (*sg_route_cb)(void *cls, struct sg_route *route);
  1736. /**
  1737. * Callback signature used by #sg_routes_iter() to iterate route items.
  1738. * \param[out] cls User-defined closure.
  1739. * \param[out] route Current iterated route.
  1740. * \retval 0 Success.
  1741. * \retval E<ERROR> User-defined error to stop the route items iteration.
  1742. */
  1743. typedef int (*sg_routes_iter_cb)(void *cls, struct sg_route *route);
  1744. /**
  1745. * Returns the PCRE2 handle containing the compiled regex code.
  1746. * \param[in] route Route handle.
  1747. * \return PCRE2 handle containing the compiled regex code.
  1748. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1749. */
  1750. SG_EXTERN void *sg_route_handle(struct sg_route *route);
  1751. /**
  1752. * Returns the PCRE2 match data created from the route pattern.
  1753. * \param[in] route Route handle.
  1754. * \return PCRE2 match data.
  1755. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1756. */
  1757. SG_EXTERN void *sg_route_match(struct sg_route *route);
  1758. /**
  1759. * Returns the raw route pattern. For example, given a pattern `/foo`, the raw
  1760. * pattern is `^/foo$`.
  1761. * \param[in] route Route handle.
  1762. * \return Raw pattern as a null-terminated string.
  1763. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1764. */
  1765. SG_EXTERN const char *sg_route_rawpattern(struct sg_route *route);
  1766. /**
  1767. * Returns the route pattern.
  1768. * \param[in] route Route handle.
  1769. * \return Pattern as a null-terminated string.
  1770. * \retval NULL
  1771. * - If \pr{route} is null and set the `errno` to `EINVAL`.
  1772. * - If no memory space is available and set the `errno` to `ENOMEM`.
  1773. * \warning The caller must free the returned value.
  1774. */
  1775. SG_EXTERN char *sg_route_pattern(struct sg_route *route) __SG_MALLOC;
  1776. /**
  1777. * Returns the route path.
  1778. * \param[in] route Route handle.
  1779. * \return Path component as a null-terminated string.
  1780. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1781. */
  1782. SG_EXTERN const char *sg_route_path(struct sg_route *route);
  1783. /**
  1784. * Iterates over path segments.
  1785. * \param[in] route Route handle.
  1786. * \param[in] cb Callback to iterate the path segments.
  1787. * \param[in,out] cls User-specified value.
  1788. * \retval 0 Success.
  1789. * \retval EINVAL Invalid argument.
  1790. * \return Callback result when it is different from `0`.
  1791. */
  1792. SG_EXTERN int sg_route_segments_iter(struct sg_route *route,
  1793. sg_segments_iter_cb cb, void *cls);
  1794. /**
  1795. * Iterates over path variables.
  1796. * \param[in] route Route handle.
  1797. * \param[in] cb Callback to iterate the path variables.
  1798. * \param[in,out] cls User-specified value.
  1799. * \retval 0 Success.
  1800. * \retval EINVAL Invalid argument.
  1801. * \retval ENOMEM Out of memory.
  1802. * \return Callback result when it is different from `0`.
  1803. */
  1804. SG_EXTERN int sg_route_vars_iter(struct sg_route *route, sg_vars_iter_cb cb,
  1805. void *cls);
  1806. /**
  1807. * Gets user data from the route handle.
  1808. * \param[in] route Route handle.
  1809. * \return User data pointer.
  1810. * \retval NULL If \pr{route} is null and set the `errno` to `EINVAL`.
  1811. */
  1812. SG_EXTERN void *sg_route_user_data(struct sg_route *route);
  1813. /**
  1814. * Adds a route item to the route list \pr{routes}.
  1815. * \param[in,out] routes Route list pointer to add a new route item.
  1816. * \param[in,out] route Pointer of the variable to store the added route
  1817. * reference.
  1818. * \param[in] pattern Pattern as a null-terminated string. It must be a valid
  1819. * regular expression in PCRE2 syntax.
  1820. * \param[in,out] errmsg Pointer of a string to store the error message.
  1821. * \param[in] errlen Length of the error message.
  1822. * \param[in] cb Callback to handle the path routing.
  1823. * \param[in] cls User-defined closure.
  1824. * \retval 0 Success.
  1825. * \retval EINVAL Invalid argument.
  1826. * \retval EALREADY Route already added.
  1827. * \retval ENOMEM Out of memory.
  1828. * \note The pattern is enclosed between `^` and `$` automatically if it does
  1829. * not start with `(`.
  1830. * \note The escape sequence \\K is not supported. It causes `EINVAL` if used.
  1831. * \note The pattern is compiled using just-in-time optimization (JIT) when it
  1832. * is supported.
  1833. */
  1834. SG_EXTERN int sg_routes_add2(struct sg_route **routes, struct sg_route **route,
  1835. const char *pattern, char *errmsg, size_t errlen,
  1836. sg_route_cb cb, void *cls);
  1837. /**
  1838. * Adds a route item to the route list \pr{routes}. It uses the `stderr` to
  1839. * print the validation errors.
  1840. * \param[in,out] routes Route list pointer to add a new route item.
  1841. * \param[in] pattern Pattern as a null-terminated string. It must be a valid
  1842. * regular expression in PCRE2 syntax.
  1843. * \param[in] cb Callback to handle the path routing.
  1844. * \param[in] cls User-defined closure.
  1845. * \retval 0 Success.
  1846. * \retval EINVAL Invalid argument.
  1847. * \retval EALREADY Route already added.
  1848. * \retval ENOMEM Out of memory.
  1849. * \note The pattern is enclosed between `^` and `$` automatically if it does
  1850. * not start with `(`.
  1851. * \note The escape sequence \\K is not supported. It causes `EINVAL` if used.
  1852. * \note The pattern is compiled using just-in-time optimization (JIT) when it
  1853. * is supported.
  1854. */
  1855. SG_EXTERN bool sg_routes_add(struct sg_route **routes, const char *pattern,
  1856. sg_route_cb cb, void *cls);
  1857. /**
  1858. * Removes a route item from the route list \pr{routes}.
  1859. * \param[in,out] routes Route list pointer to add a new route item.
  1860. * \param[in] pattern Pattern as a null-terminated string of the route to be
  1861. * removed.
  1862. * \retval 0 Success.
  1863. * \retval EINVAL Invalid argument.
  1864. * \retval ENOENT Route already removed.
  1865. */
  1866. SG_EXTERN int sg_routes_rm(struct sg_route **routes, const char *pattern);
  1867. /**
  1868. * Iterates over all the routes in the route list \pr{routes}.
  1869. * \param[in] routes Route list handle.
  1870. * \param[in] cb Callback to iterate over route items.
  1871. * \param[in] cls User-defined closure.
  1872. * \retval 0 Success.
  1873. * \retval EINVAL Invalid argument.
  1874. * \retval E<ERROR> User-defined error to abort the list iteration.
  1875. */
  1876. SG_EXTERN int sg_routes_iter(struct sg_route *routes, sg_routes_iter_cb cb,
  1877. void *cls);
  1878. /**
  1879. * Returns the next route into the route list.
  1880. * \param[in,out] route Pointer to the next route item.
  1881. * \retval 0 Success.
  1882. * \retval EINVAL Invalid argument.
  1883. */
  1884. SG_EXTERN int sg_routes_next(struct sg_route **route);
  1885. /**
  1886. * Counts the total routes in the route list \pr{routes}.
  1887. * \param[in] routes Route list handle.
  1888. * \return Total of route items.
  1889. * \retval 0 If the list is empty or null.
  1890. */
  1891. SG_EXTERN unsigned int sg_routes_count(struct sg_route *routes);
  1892. /**
  1893. * Cleans the entire route list.
  1894. * \param[in,out] routes Pointer to the route list.
  1895. */
  1896. SG_EXTERN int sg_routes_cleanup(struct sg_route **routes);
  1897. /**
  1898. * Handle for the path router. It holds the reference of a route list to be
  1899. * dispatched.
  1900. * \struct sg_router
  1901. */
  1902. struct sg_router;
  1903. /**
  1904. * Callback signature used by #sg_router_dispatch2 in the route dispatching
  1905. * loop.
  1906. * \param[out] cls User-defined closure.
  1907. * \param[out] path Route path as a null-terminated string.
  1908. * \param[out] route Route handle.
  1909. * \retval 0 Success.
  1910. * \retval E<ERROR> User-defined error to stop the route dispatching loop.
  1911. */
  1912. typedef int (*sg_router_dispatch_cb)(void *cls, const char *path,
  1913. struct sg_route *route);
  1914. /**
  1915. * Callback signature used by #sg_router_dispatch2 when the path matches the
  1916. * pattern before the route dispatching.
  1917. * \param[out] cls User-defined closure.
  1918. * \param[out] route Route handle.
  1919. * \retval 0 Success.
  1920. * \retval E<ERROR> User-defined error to stop the route dispatching.
  1921. */
  1922. typedef int (*sg_router_match_cb)(void *cls, struct sg_route *route);
  1923. /**
  1924. * Creates a new path router handle. It requires a filled route list
  1925. * \pr{routes}.
  1926. * \param[in] routes Route list handle.
  1927. * \return New router handle.
  1928. * \retval NULL If the \pr{routes} is null and set the `errno` to `EINVAL` or
  1929. * no memory space.
  1930. */
  1931. SG_EXTERN struct sg_router *sg_router_new(struct sg_route *routes) __SG_MALLOC;
  1932. /**
  1933. * Frees the router handle previously allocated by #sg_router_new().
  1934. * \param[in] router Router handle.
  1935. */
  1936. SG_EXTERN void sg_router_free(struct sg_router *router);
  1937. /**
  1938. * Dispatches a route that its pattern matches the path passed in \pr{path}.
  1939. * \param[in] router Router handle.
  1940. * \param[in] path Path to dispatch a route.
  1941. * \param[in] user_data User data pointer to be held by the route.
  1942. * \param[in] dispatch_cb Callback triggered for each route item in the route
  1943. * dispatching loop.
  1944. * \param[in] cls User-defined closure passed to the \pr{dispatch_cb} and
  1945. * \pr{match_cb} callbacks.
  1946. * \param[in] match_cb Callback triggered when the path matches the route
  1947. * pattern.
  1948. * \retval 0 Success.
  1949. * \retval EINVAL Invalid argument.
  1950. * \retval ENOENT Route not found or path not matched.
  1951. * \retval E<ERROR> User-defined error in \pr{dispatch_cb} or \pr{match_cb}.
  1952. * \note The route callback #sg_route_cb is triggered when the path matches the
  1953. * route pattern.
  1954. * \note The match logic uses just-in-time optimization (JIT) when it is
  1955. * supported.
  1956. */
  1957. SG_EXTERN int sg_router_dispatch2(struct sg_router *router, const char *path,
  1958. void *user_data,
  1959. sg_router_dispatch_cb dispatch_cb, void *cls,
  1960. sg_router_match_cb match_cb);
  1961. /**
  1962. * Dispatches a route that its pattern matches the path passed in \pr{path}.
  1963. * \param[in] router Router handle.
  1964. * \param[in] path Path to dispatch a route.
  1965. * \param[in] user_data User data pointer to be held by the route.
  1966. * \retval 0 Success.
  1967. * \retval EINVAL Invalid argument.
  1968. * \retval ENOENT Route not found or path not matched.
  1969. * \retval E<ERROR> User-defined error in \pr{dispatch_cb} or \pr{match_cb}.
  1970. * \note The route callback #sg_route_cb is triggered when the path matches the
  1971. * route pattern.
  1972. * \note The match logic uses just-in-time optimization (JIT) when it is
  1973. * supported.
  1974. */
  1975. SG_EXTERN int sg_router_dispatch(struct sg_router *router, const char *path,
  1976. void *user_data);
  1977. /** \} */
  1978. #endif /* SG_PATH_ROUTING */
  1979. #ifdef SG_MATH_EXPR_EVAL
  1980. /**
  1981. * \ingroup sg_api
  1982. * \defgroup sg_expr Math expression evaluator
  1983. * Mathematical expression evaluator.
  1984. * \{
  1985. */
  1986. /**
  1987. * Handle for the mathematical expression evaluator.
  1988. * \struct sg_expr
  1989. */
  1990. struct sg_expr;
  1991. /**
  1992. * Possible error types returned by the mathematical expression evaluator.
  1993. * \enum sg_expr_err_type
  1994. */
  1995. enum sg_expr_err_type {
  1996. /** Error not related to evaluation, e.g. `EINVAL`. */
  1997. SG_EXPR_ERR_UNKNOWN,
  1998. /** Unexpected number, e.g. `"(1+2)3"`. */
  1999. SG_EXPR_ERR_UNEXPECTED_NUMBER,
  2000. /** Unexpected word, e.g. `"(1+2)x"`. */
  2001. SG_EXPR_ERR_UNEXPECTED_WORD,
  2002. /** Unexpected parenthesis, e.g. `"1(2+3)"`. */
  2003. SG_EXPR_ERR_UNEXPECTED_PARENS,
  2004. /** Missing expected operand, e.g. `"0^+1"`. */
  2005. SG_EXPR_ERR_MISSING_OPERAND,
  2006. /** Unknown operator, e.g. `"(1+2)."`. */
  2007. SG_EXPR_ERR_UNKNOWN_OPERATOR,
  2008. /** Invalid function name, e.g. `"unknownfunc()"`. */
  2009. SG_EXPR_ERR_INVALID_FUNC_NAME,
  2010. /** Bad parenthesis, e.g. `"(1+2"`. */
  2011. SG_EXPR_ERR_BAD_PARENS,
  2012. /** Too few arguments passed to a macro, e.g. `"$()"`. */
  2013. SG_EXPR_ERR_TOO_FEW_FUNC_ARGS,
  2014. /** First macro argument is not variable, e.g. `"$(1)"`. */
  2015. SG_EXPR_ERR_FIRST_ARG_IS_NOT_VAR,
  2016. /** Bad variable name, e.g. `"2.3.4"`. */
  2017. SG_EXPR_ERR_BAD_VARIABLE_NAME,
  2018. /** Bad assignment, e.g. `"2=3"`. */
  2019. SG_EXPR_ERR_BAD_ASSIGNMENT
  2020. };
  2021. /**
  2022. * Handle to access a user-defined function registered in the mathematical
  2023. * expression extension.
  2024. * \struct sg_expr_argument
  2025. */
  2026. struct sg_expr_argument;
  2027. /**
  2028. * Callback signature to specify a function at build time to be executed at
  2029. * run time in a mathematical expression.
  2030. * \param[out] cls User-defined closure.
  2031. * \param[out] args Floating-point arguments passed to the function.
  2032. * \param[out] identifier Null-terminated string to identify the function.
  2033. * \return Floating-point value calculated at build time to be used at run time
  2034. * in a mathematical expression.
  2035. */
  2036. typedef double (*sg_expr_func)(void *cls, struct sg_expr_argument *args,
  2037. const char *identifier);
  2038. /**
  2039. * Handle for the mathematical expression evaluator extension.
  2040. * \struct sg_expr_extension
  2041. */
  2042. struct sg_expr_extension {
  2043. /** User-defined function to be executed at run time in a mathematical
  2044. * expression. */
  2045. sg_expr_func func;
  2046. /** Null-terminated to identify the function. */
  2047. const char *identifier;
  2048. /** User-defined closure. */
  2049. void *cls;
  2050. };
  2051. /**
  2052. * Creates a new mathematical expression evaluator handle.
  2053. * \return New mathematical expression evaluator handle.
  2054. * \retval NULL If no memory space is available and set the `errno` to
  2055. * `ENOMEM`.
  2056. */
  2057. SG_EXTERN struct sg_expr *sg_expr_new(void) __SG_MALLOC;
  2058. /**
  2059. * Frees the mathematical expression evaluator handle previously allocated by
  2060. * #sg_expr_new().
  2061. * \param[in] expr Expression evaluator handle.
  2062. */
  2063. SG_EXTERN void sg_expr_free(struct sg_expr *expr);
  2064. /**
  2065. * Compiles a mathematical expression allowing to declare variables, macros and
  2066. * extensions.
  2067. * \param[in] expr Mathematical expression instance.
  2068. * \param[in] str Null-terminated string with the mathematical expression to be
  2069. * compiled.
  2070. * \param[in] len Length of the mathematical expression to be compiled.
  2071. * \param[in] extensions Array of extensions to extend the evaluator.
  2072. * \note The extension array must be terminated by a zeroed item.
  2073. * \retval 0 Success.
  2074. * \retval EINVAL Invalid argument.
  2075. * \retval ENOENT Missing a needed extenssion.
  2076. * \retval EALREADY Mathematical expression already compiled.
  2077. * \retval ENOMEM Out of memory.
  2078. */
  2079. SG_EXTERN int sg_expr_compile(struct sg_expr *expr, const char *str, size_t len,
  2080. struct sg_expr_extension *extensions);
  2081. /**
  2082. * Clears a mathematical expression instance.
  2083. * \param[in] expr Mathematical expression instance.
  2084. * \retval 0 Success.
  2085. * \retval EINVAL Invalid argument.
  2086. */
  2087. SG_EXTERN int sg_expr_clear(struct sg_expr *expr);
  2088. /**
  2089. * Evaluates a compiled mathematical expression.
  2090. * \param[in] expr Compiled mathematical expression.
  2091. * \return Floating-point value of the evaluated mathematical expression.
  2092. * \retval NAN If the \pr{expr} is null and set the `errno` to `EINVAL`.
  2093. */
  2094. SG_EXTERN double sg_expr_eval(struct sg_expr *expr);
  2095. /**
  2096. * Gets the value of a declared variable.
  2097. * \param[in] expr Mathematical expression instance.
  2098. * \param[in] name Name of the declared variable.
  2099. * \param[in] len Length of the variable name.
  2100. * \retval NAN
  2101. * - If \pr{expr} or \pr{name} is null, or \pr{len} is less than one, and set
  2102. * the `errno` to `EINVAL`.
  2103. * - If no memory space is available and set the `errno` to `ENOMEM`.
  2104. */
  2105. SG_EXTERN double sg_expr_var(struct sg_expr *expr, const char *name,
  2106. size_t len);
  2107. /**
  2108. * Sets a variable to the mathematical expression.
  2109. * \param[in] expr Mathematical expression instance.
  2110. * \param[in] name Name for the variable.
  2111. * \param[in] len Length of the variable name.
  2112. * \param[in] val Value for the variable.
  2113. * \retval 0 Success.
  2114. * \retval EINVAL Invalid argument.
  2115. * \retval ENOMEM Out of memory.
  2116. */
  2117. SG_EXTERN int sg_expr_set_var(struct sg_expr *expr, const char *name,
  2118. size_t len, double val);
  2119. /**
  2120. * Gets a function argument by its index.
  2121. * \param[in] args Arguments list.
  2122. * \param[in] index Argument index.
  2123. * \retval NAN If the \pr{args} is null or \pr{index} is less than zero and
  2124. * set the `errno` to `EINVAL`.
  2125. */
  2126. SG_EXTERN double sg_expr_arg(struct sg_expr_argument *args, int index);
  2127. /**
  2128. * Returns the nearby position of an error in the mathematical expression.
  2129. * \param[in] expr Compiled mathematical expression.
  2130. * \retval 0 Success.
  2131. * \retval EINVAL Invalid argument.
  2132. */
  2133. SG_EXTERN int sg_expr_near(struct sg_expr *expr);
  2134. /**
  2135. * Returns the type of an error in the mathematical expression.
  2136. * \param[in] expr Compiled mathematical expression.
  2137. * \return Enumerator representing the error type.
  2138. * \retval SG_EXPR_ERR_UNKNOWN If the \pr{expr} is null or an unknown error
  2139. * occurred and set the `errno` to `EINVAL`.
  2140. */
  2141. SG_EXTERN enum sg_expr_err_type sg_expr_err(struct sg_expr *expr);
  2142. /**
  2143. * Returns the description of an error in the mathematical expression.
  2144. * \param[in] expr Compiled mathematical expression.
  2145. * \return Description of the error as a null-terminated string.
  2146. * \retval NULL If the \pr{expr} is null and set the `errno` to `EINVAL`.
  2147. */
  2148. SG_EXTERN const char *sg_expr_strerror(struct sg_expr *expr);
  2149. /**
  2150. * Returns the evaluated value of a mathematical expression.
  2151. * \param[in] str Null-terminated string with the mathematical expression to be
  2152. * evaluated.
  2153. * \param[in] len Length of the mathematical expression to be evaluated.
  2154. * \retval NAN If \pr{str} is null, or \pr{len} is less than one, and set the
  2155. * `errno` to `EINVAL`.
  2156. */
  2157. SG_EXTERN double sg_expr_calc(const char *str, size_t len);
  2158. /** \} */
  2159. #endif /* SG_MATH_EXPR_EVAL */
  2160. #ifdef __cplusplus
  2161. }
  2162. #endif
  2163. #endif /* SAGUI_H */