cgi.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements helper procs for CGI applications. Example:
  10. ##
  11. ## ```Nim
  12. ## import std/[strtabs, cgi]
  13. ##
  14. ## # Fill the values when debugging:
  15. ## when debug:
  16. ## setTestData("name", "Klaus", "password", "123456")
  17. ## # read the data into `myData`
  18. ## var myData = readData()
  19. ## # check that the data's variable names are "name" or "password"
  20. ## validateData(myData, "name", "password")
  21. ## # start generating content:
  22. ## writeContentType()
  23. ## # generate content:
  24. ## write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n")
  25. ## write(stdout, "<html><head><title>Test</title></head><body>\n")
  26. ## writeLine(stdout, "your name: " & myData["name"])
  27. ## writeLine(stdout, "your password: " & myData["password"])
  28. ## writeLine(stdout, "</body></html>")
  29. ## ```
  30. import std/[strutils, os, strtabs, cookies, uri]
  31. export uri.encodeUrl, uri.decodeUrl
  32. when defined(nimPreviewSlimSystem):
  33. import std/syncio
  34. proc addXmlChar(dest: var string, c: char) {.inline.} =
  35. case c
  36. of '&': add(dest, "&amp;")
  37. of '<': add(dest, "&lt;")
  38. of '>': add(dest, "&gt;")
  39. of '\"': add(dest, "&quot;")
  40. else: add(dest, c)
  41. proc xmlEncode*(s: string): string =
  42. ## Encodes a value to be XML safe:
  43. ## * `"` is replaced by `&quot;`
  44. ## * `<` is replaced by `&lt;`
  45. ## * `>` is replaced by `&gt;`
  46. ## * `&` is replaced by `&amp;`
  47. ## * every other character is carried over.
  48. result = newStringOfCap(s.len + s.len shr 2)
  49. for i in 0..len(s)-1: addXmlChar(result, s[i])
  50. type
  51. CgiError* = object of IOError ## Exception that is raised if a CGI error occurs.
  52. RequestMethod* = enum ## The used request method.
  53. methodNone, ## no REQUEST_METHOD environment variable
  54. methodPost, ## query uses the POST method
  55. methodGet ## query uses the GET method
  56. proc cgiError*(msg: string) {.noreturn.} =
  57. ## Raises a `CgiError` exception with message `msg`.
  58. raise newException(CgiError, msg)
  59. proc getEncodedData(allowedMethods: set[RequestMethod]): string =
  60. case getEnv("REQUEST_METHOD")
  61. of "POST":
  62. if methodPost notin allowedMethods:
  63. cgiError("'REQUEST_METHOD' 'POST' is not supported")
  64. var L = parseInt(getEnv("CONTENT_LENGTH"))
  65. if L == 0:
  66. return ""
  67. result = newString(L)
  68. if readBuffer(stdin, addr(result[0]), L) != L:
  69. cgiError("cannot read from stdin")
  70. of "GET":
  71. if methodGet notin allowedMethods:
  72. cgiError("'REQUEST_METHOD' 'GET' is not supported")
  73. result = getEnv("QUERY_STRING")
  74. else:
  75. if methodNone notin allowedMethods:
  76. cgiError("'REQUEST_METHOD' must be 'POST' or 'GET'")
  77. iterator decodeData*(data: string): tuple[key, value: string] =
  78. ## Reads and decodes CGI data and yields the (name, value) pairs the
  79. ## data consists of.
  80. for (key, value) in uri.decodeQuery(data):
  81. yield (key, value)
  82. iterator decodeData*(allowedMethods: set[RequestMethod] =
  83. {methodNone, methodPost, methodGet}): tuple[key, value: string] =
  84. ## Reads and decodes CGI data and yields the (name, value) pairs the
  85. ## data consists of. If the client does not use a method listed in the
  86. ## `allowedMethods` set, a `CgiError` exception is raised.
  87. let data = getEncodedData(allowedMethods)
  88. for (key, value) in uri.decodeQuery(data):
  89. yield (key, value)
  90. proc readData*(allowedMethods: set[RequestMethod] =
  91. {methodNone, methodPost, methodGet}): StringTableRef =
  92. ## Reads CGI data. If the client does not use a method listed in the
  93. ## `allowedMethods` set, a `CgiError` exception is raised.
  94. result = newStringTable()
  95. for name, value in decodeData(allowedMethods):
  96. result[name] = value
  97. proc readData*(data: string): StringTableRef =
  98. ## Reads CGI data from a string.
  99. result = newStringTable()
  100. for name, value in decodeData(data):
  101. result[name] = value
  102. proc validateData*(data: StringTableRef, validKeys: varargs[string]) =
  103. ## Validates data; raises `CgiError` if this fails. This checks that each variable
  104. ## name of the CGI `data` occurs in the `validKeys` array.
  105. for key, val in pairs(data):
  106. if find(validKeys, key) < 0:
  107. cgiError("unknown variable name: " & key)
  108. proc getContentLength*(): string =
  109. ## Returns contents of the `CONTENT_LENGTH` environment variable.
  110. return getEnv("CONTENT_LENGTH")
  111. proc getContentType*(): string =
  112. ## Returns contents of the `CONTENT_TYPE` environment variable.
  113. return getEnv("CONTENT_Type")
  114. proc getDocumentRoot*(): string =
  115. ## Returns contents of the `DOCUMENT_ROOT` environment variable.
  116. return getEnv("DOCUMENT_ROOT")
  117. proc getGatewayInterface*(): string =
  118. ## Returns contents of the `GATEWAY_INTERFACE` environment variable.
  119. return getEnv("GATEWAY_INTERFACE")
  120. proc getHttpAccept*(): string =
  121. ## Returns contents of the `HTTP_ACCEPT` environment variable.
  122. return getEnv("HTTP_ACCEPT")
  123. proc getHttpAcceptCharset*(): string =
  124. ## Returns contents of the `HTTP_ACCEPT_CHARSET` environment variable.
  125. return getEnv("HTTP_ACCEPT_CHARSET")
  126. proc getHttpAcceptEncoding*(): string =
  127. ## Returns contents of the `HTTP_ACCEPT_ENCODING` environment variable.
  128. return getEnv("HTTP_ACCEPT_ENCODING")
  129. proc getHttpAcceptLanguage*(): string =
  130. ## Returns contents of the `HTTP_ACCEPT_LANGUAGE` environment variable.
  131. return getEnv("HTTP_ACCEPT_LANGUAGE")
  132. proc getHttpConnection*(): string =
  133. ## Returns contents of the `HTTP_CONNECTION` environment variable.
  134. return getEnv("HTTP_CONNECTION")
  135. proc getHttpCookie*(): string =
  136. ## Returns contents of the `HTTP_COOKIE` environment variable.
  137. return getEnv("HTTP_COOKIE")
  138. proc getHttpHost*(): string =
  139. ## Returns contents of the `HTTP_HOST` environment variable.
  140. return getEnv("HTTP_HOST")
  141. proc getHttpReferer*(): string =
  142. ## Returns contents of the `HTTP_REFERER` environment variable.
  143. return getEnv("HTTP_REFERER")
  144. proc getHttpUserAgent*(): string =
  145. ## Returns contents of the `HTTP_USER_AGENT` environment variable.
  146. return getEnv("HTTP_USER_AGENT")
  147. proc getPathInfo*(): string =
  148. ## Returns contents of the `PATH_INFO` environment variable.
  149. return getEnv("PATH_INFO")
  150. proc getPathTranslated*(): string =
  151. ## Returns contents of the `PATH_TRANSLATED` environment variable.
  152. return getEnv("PATH_TRANSLATED")
  153. proc getQueryString*(): string =
  154. ## Returns contents of the `QUERY_STRING` environment variable.
  155. return getEnv("QUERY_STRING")
  156. proc getRemoteAddr*(): string =
  157. ## Returns contents of the `REMOTE_ADDR` environment variable.
  158. return getEnv("REMOTE_ADDR")
  159. proc getRemoteHost*(): string =
  160. ## Returns contents of the `REMOTE_HOST` environment variable.
  161. return getEnv("REMOTE_HOST")
  162. proc getRemoteIdent*(): string =
  163. ## Returns contents of the `REMOTE_IDENT` environment variable.
  164. return getEnv("REMOTE_IDENT")
  165. proc getRemotePort*(): string =
  166. ## Returns contents of the `REMOTE_PORT` environment variable.
  167. return getEnv("REMOTE_PORT")
  168. proc getRemoteUser*(): string =
  169. ## Returns contents of the `REMOTE_USER` environment variable.
  170. return getEnv("REMOTE_USER")
  171. proc getRequestMethod*(): string =
  172. ## Returns contents of the `REQUEST_METHOD` environment variable.
  173. return getEnv("REQUEST_METHOD")
  174. proc getRequestURI*(): string =
  175. ## Returns contents of the `REQUEST_URI` environment variable.
  176. return getEnv("REQUEST_URI")
  177. proc getScriptFilename*(): string =
  178. ## Returns contents of the `SCRIPT_FILENAME` environment variable.
  179. return getEnv("SCRIPT_FILENAME")
  180. proc getScriptName*(): string =
  181. ## Returns contents of the `SCRIPT_NAME` environment variable.
  182. return getEnv("SCRIPT_NAME")
  183. proc getServerAddr*(): string =
  184. ## Returns contents of the `SERVER_ADDR` environment variable.
  185. return getEnv("SERVER_ADDR")
  186. proc getServerAdmin*(): string =
  187. ## Returns contents of the `SERVER_ADMIN` environment variable.
  188. return getEnv("SERVER_ADMIN")
  189. proc getServerName*(): string =
  190. ## Returns contents of the `SERVER_NAME` environment variable.
  191. return getEnv("SERVER_NAME")
  192. proc getServerPort*(): string =
  193. ## Returns contents of the `SERVER_PORT` environment variable.
  194. return getEnv("SERVER_PORT")
  195. proc getServerProtocol*(): string =
  196. ## Returns contents of the `SERVER_PROTOCOL` environment variable.
  197. return getEnv("SERVER_PROTOCOL")
  198. proc getServerSignature*(): string =
  199. ## Returns contents of the `SERVER_SIGNATURE` environment variable.
  200. return getEnv("SERVER_SIGNATURE")
  201. proc getServerSoftware*(): string =
  202. ## Returns contents of the `SERVER_SOFTWARE` environment variable.
  203. return getEnv("SERVER_SOFTWARE")
  204. proc setTestData*(keysvalues: varargs[string]) =
  205. ## Fills the appropriate environment variables to test your CGI application.
  206. ## This can only simulate the 'GET' request method. `keysvalues` should
  207. ## provide embedded (name, value)-pairs. Example:
  208. ## ```Nim
  209. ## setTestData("name", "Hanz", "password", "12345")
  210. ## ```
  211. putEnv("REQUEST_METHOD", "GET")
  212. var i = 0
  213. var query = ""
  214. while i < keysvalues.len:
  215. add(query, encodeUrl(keysvalues[i]))
  216. add(query, '=')
  217. add(query, encodeUrl(keysvalues[i+1]))
  218. add(query, '&')
  219. inc(i, 2)
  220. putEnv("QUERY_STRING", query)
  221. proc writeContentType*() =
  222. ## Calls this before starting to send your HTML data to `stdout`. This
  223. ## implements this part of the CGI protocol:
  224. ## ```Nim
  225. ## write(stdout, "Content-type: text/html\n\n")
  226. ## ```
  227. write(stdout, "Content-type: text/html\n\n")
  228. proc resetForStacktrace() =
  229. stdout.write """<!--: spam
  230. Content-Type: text/html
  231. <body bgcolor=#f0f0f8><font color=#f0f0f8 size=-5> -->
  232. <body bgcolor=#f0f0f8><font color=#f0f0f8 size=-5> --> -->
  233. </font> </font> </font> </script> </object> </blockquote> </pre>
  234. </table> </table> </table> </table> </table> </font> </font> </font>
  235. """
  236. proc writeErrorMessage*(data: string) =
  237. ## Tries to reset browser state and writes `data` to stdout in
  238. ## <plaintext> tag.
  239. resetForStacktrace()
  240. # We use <plaintext> here, instead of escaping, so stacktrace can
  241. # be understood by human looking at source.
  242. stdout.write("<plaintext>\n")
  243. stdout.write(data)
  244. proc setStackTraceStdout*() =
  245. ## Makes Nim output stacktraces to stdout, instead of server log.
  246. errorMessageWriter = writeErrorMessage
  247. proc setCookie*(name, value: string) =
  248. ## Sets a cookie.
  249. write(stdout, "Set-Cookie: ", name, "=", value, "\n")
  250. var
  251. gcookies {.threadvar.}: StringTableRef
  252. proc getCookie*(name: string): string =
  253. ## Gets a cookie. If no cookie of `name` exists, "" is returned.
  254. if gcookies == nil: gcookies = parseCookies(getHttpCookie())
  255. result = gcookies.getOrDefault(name)
  256. proc existsCookie*(name: string): bool =
  257. ## Checks if a cookie of `name` exists.
  258. if gcookies == nil: gcookies = parseCookies(getHttpCookie())
  259. result = hasKey(gcookies, name)