cgi.nim 11 KB

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