cgi.nim 12 KB

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