summary refs log tree commit diff stats
path: root/compiler/vmops.nim
blob: 83e65279aff36a312b786040ab9267d8906f3738 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#
#
#           The Nim Compiler
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# Unforunately this cannot be a module yet:
#import vmdeps, vm
from math import sqrt, ln, log10, log2, exp, round, arccos, arcsin,
  arctan, arctan2, cos, cosh, hypot, sinh, sin, tan, tanh, pow, trunc,
  floor, ceil, fmod

from os import getEnv, existsEnv, dirExists, fileExists, putEnv, walkDir

template mathop(op) {.dirty.} =
  registerCallback(c, "stdlib.math." & astToStr(op), `op Wrapper`)

template osop(op) {.dirty.} =
  registerCallback(c, "stdlib.os." & astToStr(op), `op Wrapper`)

template ospathsop(op) {.dirty.} =
  registerCallback(c, "stdlib.ospaths." & astToStr(op), `op Wrapper`)

template systemop(op) {.dirty.} =
  registerCallback(c, "stdlib.system." & astToStr(op), `op Wrapper`)

template macrosop(op) {.dirty.} =
  registerCallback(c, "stdlib.macros." & astToStr(op), `op Wrapper`)

template wrap1f_math(op) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    setResult(a, op(getFloat(a, 0)))
  mathop op

template wrap2f_math(op) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    setResult(a, op(getFloat(a, 0), getFloat(a, 1)))
  mathop op

template wrap0(op, modop) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    setResult(a, op())
  modop op

template wrap1s(op, modop) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    setResult(a, op(getString(a, 0)))
  modop op

template wrap2s(op, modop) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    setResult(a, op(getString(a, 0), getString(a, 1)))
  modop op

template wrap1svoid(op, modop) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    op(getString(a, 0))
  modop op

template wrap2svoid(op, modop) {.dirty.} =
  proc `op Wrapper`(a: VmArgs) {.nimcall.} =
    op(getString(a, 0), getString(a, 1))
  modop op

proc getCurrentExceptionMsgWrapper(a: VmArgs) {.nimcall.} =
  setResult(a, if a.currentException.isNil: ""
               else: a.currentException.sons[3].skipColon.strVal)

proc staticWalkDirImpl(path: string, relative: bool): PNode =
  result = newNode(nkBracket)
  for k, f in walkDir(path, relative):
    result.add newTree(nkTupleConstr, newIntNode(nkIntLit, k.ord),
                              newStrNode(nkStrLit, f))

proc registerAdditionalOps*(c: PCtx) =
  proc gorgeExWrapper(a: VmArgs) =
    let (s, e) = opGorge(getString(a, 0), getString(a, 1), getString(a, 2),
                         a.currentLineInfo, c.config)
    setResult a, newTree(nkTupleConstr, newStrNode(nkStrLit, s), newIntNode(nkIntLit, e))

  proc getProjectPathWrapper(a: VmArgs) =
    setResult a, c.config.projectPath.string

  wrap1f_math(sqrt)
  wrap1f_math(ln)
  wrap1f_math(log10)
  wrap1f_math(log2)
  wrap1f_math(exp)
  wrap1f_math(round)
  wrap1f_math(arccos)
  wrap1f_math(arcsin)
  wrap1f_math(arctan)
  wrap2f_math(arctan2)
  wrap1f_math(cos)
  wrap1f_math(cosh)
  wrap2f_math(hypot)
  wrap1f_math(sinh)
  wrap1f_math(sin)
  wrap1f_math(tan)
  wrap1f_math(tanh)
  wrap2f_math(pow)
  wrap1f_math(trunc)
  wrap1f_math(floor)
  wrap1f_math(ceil)
  wrap2f_math(fmod)

  when defined(nimcore):
    wrap2s(getEnv, ospathsop)
    wrap1s(existsEnv, ospathsop)
    wrap2svoid(putEnv, ospathsop)
    wrap1s(dirExists, osop)
    wrap1s(fileExists, osop)
    wrap2svoid(writeFile, systemop)
    wrap1s(readFile, systemop)
    systemop getCurrentExceptionMsg
    registerCallback c, "stdlib.*.staticWalkDir", proc (a: VmArgs) {.nimcall.} =
      setResult(a, staticWalkDirImpl(getString(a, 0), getBool(a, 1)))
    systemop gorgeEx
  macrosop getProjectPath
'>154 155 156 157 158 159 160 161 162 163 164 165 166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275

                   
 
                   
               
                    
               
                
                

                   

                      
                              


                                        






                            
                      
                         
 

                    















































                                                                       
                                                  



































                                                                                                                                        






                                         
                  
 










































                                                                               
                                                 



















                                                                  
                    
                                 
            

                                                
                                                    
                                 











                                                     
 
                                                              
                



                                    
                  

                       





                                    
                                                                            








                                   
                           

                                     
                     
                                                   
                 

                             
                                               


                                         








                                                     
                                                        







                                          
                   
 
                                                                      
                   


                                      
                             
     

   

                                       
import std/strutils
import std/times

import io/urlfilter
import js/error
import js/javascript
import js/regex
import types/url
import types/opt
import utils/twtstr

type
  Cookie* = ref object
    created: int64 # unix time
    name {.jsget.}: string
    value {.jsget.}: string
    expires {.jsget.}: int64 # unix time
    secure {.jsget.}: bool
    httponly {.jsget.}: bool
    samesite {.jsget.}: bool
    domain {.jsget.}: string
    path {.jsget.}: string

  CookieJar* = ref object
    filter*: URLFilter
    cookies*: seq[Cookie]

jsDestructor(Cookie)

proc parseCookieDate(val: string): Option[DateTime] =
  # cookie-date
  const Delimiters = {'\t', ' '..'/', ';'..'@', '['..'`', '{'..'~'}
  const NonDigit = AllChars - AsciiDigit
  var foundTime = false
  var foundDayOfMonth = false
  var foundMonth = false
  var foundYear = false
  # date-token-list
  var time: array[3, int]
  var dayOfMonth: int
  var month: int
  var year: int
  for dateToken in val.split(Delimiters):
    if dateToken == "": continue # *delimiter
    if not foundTime:
      block timeBlock: # test for time
        let hmsTime = dateToken.until(NonDigit - {':'})
        var i = 0
        for timeField in hmsTime.split(':'):
          if i > 2: break timeBlock # too many time fields
          # 1*2DIGIT
          if timeField.len != 1 and timeField.len != 2: break timeBlock
          var timeFields: array[3, int]
          for c in timeField:
            if c notin AsciiDigit: break timeBlock
            timeFields[i] *= 10
            timeFields[i] += c.decValue
          time = timeFields
          inc i
        if i != 3: break timeBlock
        foundTime = true
        continue
    if not foundDayOfMonth:
      block dayOfMonthBlock: # test for day-of-month
        let digits = dateToken.until(NonDigit)
        if digits.len != 1 and digits.len != 2: break dayOfMonthBlock
        var n = 0
        for c in digits:
          if c notin AsciiDigit: break dayOfMonthBlock
          n *= 10
          n += c.decValue
        dayOfMonth = n
        foundDayOfMonth = true
        continue
    if not foundMonth:
      block monthBlock: # test for month
        if dateToken.len < 3: break monthBlock
        case dateToken.substr(0, 2).toLowerAscii()
        of "jan": month = 1
        of "feb": month = 2
        of "mar": month = 3
        of "apr": month = 4
        of "may": month = 5
        of "jun": month = 6
        of "jul": month = 7
        of "aug": month = 8
        of "sep": month = 9
        of "oct": month = 10
        of "nov": month = 11
        of "dec": month = 12
        else: break monthBlock
        foundMonth = true
        continue
    if not foundYear:
      block yearBlock: # test for year
        let digits = dateToken.until(NonDigit)
        if digits.len != 2 and digits.len != 4: break yearBlock
        var n = 0
        for c in digits:
          if c notin AsciiDigit: break yearBlock
          n *= 10
          n += c.decValue
        year = n
        foundYear = true
        continue
  if not (foundDayOfMonth and foundMonth and foundYear and foundTime): return none(DateTime)
  if dayOfMonth notin 0..31: return none(DateTime)
  if year < 1601: return none(DateTime)
  if time[0] > 23: return none(DateTime)
  if time[1] > 59: return none(DateTime)
  if time[2] > 59: return none(DateTime)
  var dateTime = dateTime(year, Month(month), MonthdayRange(dayOfMonth), HourRange(time[0]), MinuteRange(time[1]), SecondRange(time[2]))
  return some(dateTime)

# For debugging
proc `$`*(cookiejar: CookieJar): string =
  result &= $cookiejar.filter
  result &= "\n"
  for cookie in cookiejar.cookies:
    result &= "Cookie "
    result &= $cookie[]
    result &= "\n"

# https://www.rfc-editor.org/rfc/rfc6265#section-5.1.4
func defaultCookiePath(url: URL): string =
  let path = ($url.path).beforeLast('/')
  if path == "" or path[0] != '/':
    return "/"
  return path

func cookiePathMatches(cookiePath, requestPath: string): bool =
  if requestPath.startsWith(cookiePath):
    if requestPath.len == cookiePath.len:
      return true
    if cookiePath[^1] == '/':
      return true
    if requestPath.len > cookiePath.len and requestPath[cookiePath.len] == '/':
      return true
  return false

# I have no clue if this is actually compliant, because the spec is worded
# so badly.
# Either way, this implementation is needed for compatibility.
# (Here is this part of the spec in its full glory:
#   A string domain-matches a given domain string if at least one of the
#   following conditions hold:
#   o  The domain string and the string are identical.  (Note that both
#      the domain string and the string will have been canonicalized to
#      lower case at this point.)
#   o  All of the following conditions hold:
#      *  The domain string is a suffix of the string.
#      *  The last character of the string that is not included in the
#         domain string is a %x2E (".") character. (???)
#      *  The string is a host name (i.e., not an IP address).)
func cookieDomainMatches(cookieDomain: string, url: URL): bool =
  let host = url.host
  if host == cookieDomain:
    return true
  if url.isIP():
    return false
  let cookieDomain = if cookieDomain.len > 0 and cookieDomain[0] == '.':
    cookieDomain.substr(1)
  else:
    cookieDomain
  return host.endsWith(cookieDomain)

proc add*(cookieJar: CookieJar, cookie: Cookie) =
  var i = -1
  for j in 0 ..< cookieJar.cookies.len:
    let old = cookieJar.cookies[j]
    if old.name == cookie.name and old.domain == cookie.domain and
        old.path == cookie.path:
      i = j
      break
  if i != -1:
    let old = cookieJar.cookies[i]
    cookie.created = old.created
    cookieJar.cookies.del(i)
  cookieJar.cookies.add(cookie)

proc add*(cookiejar: CookieJar, cookies: seq[Cookie]) =
  for cookie in cookies:
    cookiejar.add(cookie)

# https://www.rfc-editor.org/rfc/rfc6265#section-5.4
proc serialize*(cookiejar: CookieJar, url: URL): string =
  if not cookiejar.filter.match(url):
    return "" # fail
  let t = now().toTime().toUnix()
  #TODO sort
  for i in countdown(cookiejar.cookies.high, 0):
    let cookie = cookiejar.cookies[i]
    if cookie.expires != -1 and cookie.expires <= t:
      cookiejar.cookies.delete(i)
      continue
    if cookie.secure and url.scheme != "https":
      continue
    if not cookiePathMatches(cookie.path, $url.path):
      continue
    if not cookieDomainMatches(cookie.domain, url):
      continue
    if result != "":
      result &= "; "
    result &= cookie.name
    result &= "="
    result &= cookie.value

proc newCookie*(str: string, url: URL = nil): JSResult[Cookie]
    {.jsctor.} =
  let cookie = Cookie(
    expires: -1,
    created: now().toTime().toUnix()
  )
  var first = true
  var haspath = false
  var hasdomain = false
  for part in str.split(';'):
    if first:
      cookie.name = part.until('=')
      cookie.value = part.after('=')
      first = false
      continue
    let part = part.strip(leading = true, trailing = false, AsciiWhitespace)
    var n = 0
    for i in 0..part.high:
      if part[i] == '=':
        n = i
        break
    if n == 0:
      continue
    let key = part.substr(0, n - 1)
    let val = part.substr(n + 1)
    case key.toLowerAscii()
    of "expires":
      let date = parseCookieDate(val)
      if date.isSome:
        cookie.expires = date.get.toTime().toUnix()
    of "max-age":
      let x = parseInt64(val)
      if x.isSome:
        cookie.expires = cookie.created + x.get
    of "secure": cookie.secure = true
    of "httponly": cookie.httponly = true
    of "samesite": cookie.samesite = true
    of "path":
      if val != "" and val[0] == '/':
        haspath = true
        cookie.path = val
    of "domain":
      if url == nil or cookieDomainMatches(val, url):
        cookie.domain = val
        hasdomain = true
      else:
        return err(newTypeError("Domains do not match"))
  if not hasdomain:
    if url != nil:
      cookie.domain = url.host
  if not haspath:
    if url == nil:
      cookie.path = "/"
    else:
      cookie.path = defaultCookiePath(url)
  return ok(cookie)

proc newCookieJar*(location: URL, allowhosts: seq[Regex]): CookieJar =
  return CookieJar(
    filter: newURLFilter(
      scheme = some(location.scheme),
      allowhost = some(location.host),
      allowhosts = allowhosts
    )
  )

proc addCookieModule*(ctx: JSContext) =
  ctx.registerType(Cookie)