/
main.coffee
535 lines (455 loc) · 16.9 KB
/
main.coffee
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#include include.js
#include require.js
require.path.unshift('./lib/');
{ fork, sleep, exit, wait } = require 'builtin/process'
console = require 'builtin/console'
Config = require 'Config'
#String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
#String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
String::beginsWtih = (str) -> !!@match new RegExp "^#{str}"
String::endsWith = (str) -> (@substr 0, str.length) is str
########################################################################################################################
class Logfile
{ fork, sleep } = require 'builtin/process'
construct: ->
@logfile = require 'builtin/logfile'
start: ->
if !fork()
while true
sleep 5
@logfile.flush()
return
write: (s) ->
@logfile.write(s)
########################################################################################################################
class Semaphore
{ open, close, exists, flock, LOCK_EX, LOCK_UN, O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC } = require 'builtin/fs'
constructor: (@lockFile) ->
unless exists(@lockFile)
@fd = open @lockFile, O_WRONLY|O_CREAT|O_TRUNC, 0644
else
@fd = open @lockFile, O_RDONLY
lock: ->
flock @fd, LOCK_EX
unlock: ->
flock @fd, LOCK_UN
close: ->
close @fd
########################################################################################################################
class ServerSocket
{ listen, accept } = require 'builtin/net'
constructor: (port) ->
@socket = listen port
accept: ->
accept @socket
########################################################################################################################
class HttpRequest
http = require 'builtin/http'
net = require 'builtin/net'
stream = null;
init: (sock) ->
@start = new Date().getTime()
stream = http.openStream sock unless stream
raw = http.readHeaders stream
return false unless raw
lines = raw.split '\n'
first = lines.shift().split /\s+/
# create @headers from key: value pairs (request header lines)
headers = {}
for line in lines
colon = line.indexOf ':'
key = line.substr 0,colon
value = line.substr(colon+1).replace /&\s+/, ''
headers[key.toLowerCase()] = value
@headers = headers;
# process Host: header
host = 'localhost'
port = Config.port
if headers.host
[host,oport] = headers.host.split ':'
port = oport or 80
@host = host;
@port = port
# process query_string
uriParts = first[1].split '?'
data = {}
if uriParts[1]
for part in uriParts[1].split '&'
[key,value] = part.split '&'
data[key] = decodeUriComponent value.replace(/\+/g, ' ')
@method = first[0]
@uri = uriParts[0]
@proto = first[2] || 'http/0.9'
@remote_addr = net.remote_addr()
# process cookies
if headers.cookie
for cookie in headers.cookie.split /;\s*/
[key,value] = cookie.split '='
data[key] = decodeUriComponent value.replace(/+/g, ' ')
# process POST data
post = ''
mimeParts = []
contentLength = headers['content-length']
if (contentLength)
contentType = headers['content-type']
if contentType?.toLowerCase().indexOf('multipart/form-data') != -1
boundary = contentType.replace /^.*?boundary=/i, ''
post = http.readMime stream, contentLength, boundary
mimeParts = post.split '--'+boundary
mimeParts.shift()
mimeParts.pop()
for part in mimeParts
lines = part.split '\r\n'
disposition = lines[1].split /;\s*/
name = disposition[1].replace /name="(.*)"/, '$1'
if disposition.length == 3
data[name] =
filename: disposition[2].replace /filename="(.*)"/, '$1'
contentType: lines[2].replace /Content-Type:\s*/i, ''
size: parseInt(lines[3].replace(/Content-Length:\s*/i, ''), 10)
contentEncoding: lines[4].replace /Content-Encoding:\s*/i, ''
content: lines[6]
else
data[name] = lines[3]
else
post = http.readPost stream, contentLength
if headers['content-type'].match(/^application\/x-www-form-urlencoded/i)
for part in post.split '&'
[key,value] = part.split '='
data[key] = decodeURIComponent value.replace(/\+/gm, ' ')
@data = data
true
getHeader: (key) ->
headers[key.toLowerCase()]
close: ->
http.closeStream stream if stream
stream = null
########################################################################################################################
class HttpResponse
buffer = require 'builtin/buffer'
net = require 'builtin/net'
fs = require 'builtin/fs'
responseCodeText =
100: 'Continue'
101: 'Switching Protocols'
200: 'OK'
201: 'Created'
202: 'Accepted'
203: 'Non-Authoritative Information'
204: 'No Content'
205: 'Reset Content'
206: 'Partial Content'
300: 'Multiple Choices'
301: 'Moved Permanently'
302: 'Found'
303: 'See Other'
304: 'Not Modified'
305: 'Use Proxy'
307: 'Temporary Redirect'
400: 'Bad Request'
401: 'Unauthorized'
402: 'Payment Required' # note RFC says reserved for future use
403: 'Forbidden'
404: 'Not Found'
405: 'Method Not Allowed'
406: 'Not Acceptable'
407: 'Proxy Authentication Required'
408: 'Request Timeout'
409: 'Conflict'
410: 'Gone'
411: 'Length Required'
412: 'Precondition Failed'
413: 'Request Entity Too Large'
414: 'Request-URI Too Long'
415: 'Unsupported Media Type'
416: 'Request Range Not Satisfiable'
417: 'Expectation Failed'
500: 'Internal Server Error'
501: 'Not Implemented'
502: 'Bad Gateway'
503: 'Service Unavailable'
504: 'Gateway Timeout'
505: 'HTTP Version Not Supported'
constructor: ->
@buf = buffer.create()
init: (@clientSocket, keepAlive, requestsHandled) ->
buffer.reset @buf
@status = 200
@contentLength = 0
@contentType = 'text/html'
@cookies = {}
@headers =
Server: 'SILK JS CoffeeScript Server'
@data = {}
@headersSent = false
ka = req.headers?.connection
if ka && keepAlive
@headers.Connection = 'Keep-Alive'
@headers['keep-alive'] = 'timeout: 5; max=' + (Config.requestsPerChild - requestsHandled)
else
keepAlive = false
@headers.Connection = 'close'
return keepAlive
stop: ->
throw 'RES.STOP'
reset: ->
buffer.reset(@buf)
setCookie: (key, value, expires, path, domain) ->
cookie =
value: value
if expires
cookie.expires = if Util.isDate(expires) then expires.toGMTString() else expires
cookie.path = path if path?
cookie.domain = domain if domain?
@cookies[key] = cookie
setHeader: (key, value) ->
@headers[key] = value
sendHeaders: ->
return if headersSent
out = '';
out += req.proto + ' ' + @status + ' ' + responseCodeText[@status] + '\r\n';
out += 'Date: ' + new Date().toGMTString() + '\r\n';
for key,value of @headers
out += key + ': ' + value + '\r\n'
for key,cookie of @cookies
out += 'Set-Cookie: ' + key + '=' +encodeURIComponent(cookie.value);
out += '; Expires='+cookie.expires unless cookie.expires
out += '; Path='+encodeURIComponent(cookie.path) unless cookie.path
out += '; Domain='+encodeURIComponent(cookie.domain) unless cookie.domain
out += '\r\n';
out += 'Content-Type: ' + @contentType + '\r\n';
out += 'Content-Length: ' + @contentLength + '\r\n\r\n';
try
net.cork @clientSocket, true
net.write @clientSocket, out, out.length
catch e
throw new SilkException e
headersSent = true
write: (s) ->
try
buffer.write @buf, s, s.length
catch e
throw new SilkException e
writeln: (s) ->
try
buffer.write @buf, s+'\n', s.length+1
catch e
throw new SilkException e
write64: (s) ->
try
buffer.write64 @buf, s, s.length
catch e
throw new SilkException e
sendFile: (fn) ->
@reset(); # so extra stuff sent with res.write() isn't sent'
modified = fs.fileModified fn
size = fs.fileSize fn
@headers['last-modified'] = new Date(modified*1000).toGMTString()
ifModifiedSince = req.headers['if-modified-since']
if ifModifiedSince
ifModifiedSince = Date.parse(ifModifiedSince) / 1000
if modified <= ifModifiedSince
@status = 304
@stop()
@contentLength = size
try
@sendHeaders();
net.sendFile(@clientSocket, fn, 0, size) # (FileSystem.readfile64(fn));
catch e
throw new SilkException e
@stop();
flush: ->
len = buffer.size @buf
if len
@contentLength = len
@sendHeaders()
net.writeBuffer @clientSocket, @buf
else
@sendHeaders()
net.cork @clientSocket, false
redirect: (uri) ->
@status = 302
base = 'http://' + req.host
base += ':' + req.port unless req.port == 80
@setHeader 'Location', base + uri
@stop()
close: ->
buffer.destroy @buf
########################################################################################################################
class HttpChild
v8 = require 'builtin/v8'
Config = require 'Config'
net = require 'builtin/net'
{ fork, exit, sleep, wait, getpid, error } = require 'builtin/process'
{ stat, readFile, close, realpath, isDir, isFile, exists } = require 'builtin/fs'
notFound = () ->
res.reset()
res.result = 404
global.notFound_action?()
res.write '<h1>Not Found</h1>'
res.stop()
@requestHandler: null
jst_cache = {}
getCachedJst = (fn) ->
jst = jst_cache[fn]
mtime = stat(fn).mtime
if !jst || mtime < jst.mtime
source = readFile fn
jst =
mtime: mtime
parsed: Jst.parse source
jst_cache[fn] = jst;
return jst.parsed
includeJst = (fn) ->
jst = getCachedJst Config.documentRoot + fn
return Jst.includeParsed jst,
include: includeJst
runJst = (fn) ->
jst = getCachedJst fn
out = Jst.executeParsed jst
include: includeJst
res.contentLength = out.length
res.write out
res.stop()
coffee_cache = {}
getCachedCoffeeScript = (fn) ->
coffee = coffee_cache[fn]
mtime = stat(fn).mtime
if !coffee || mtime > coffee.mtime
v8.freeScript coffee.script if coffee
source = readFile fn
compiled = CoffeeScript.compile source
script = v8.compileScript compiled
coffee =
mtime: mtime
script: script
coffee_cache[fn] = coffee
return coffee.script
runCoffee = (fn) ->
coffee = getCachedCoffee fn
out = v8.runScript coffee
res.stop()
runMarkdown = (fn) ->
content = readFile fn
converter = new Showdown.converter()
html = converter.makeHtml content
res.write html
res.stop()
sendFile = (fn) ->
res.sendFile fn
contentTypes =
coffee: { contentType: 'text/html', handler: runCoffee }
jst: { contentType: 'text/html', handler: runJst }
md: { contentType: 'text/html', handler: runMarkdown }
ogg: { contentType: 'audio/ogg', handler: sendFile }
mp3: { contentType: 'audio/mpeg3', handler: sendFile }
png: { contentType: 'image/png', handler: sendFile }
ico: { contentType: 'image/ico', handler: sendFile }
gif: { contentType: 'image/gif', handler: sendFile }
jpg: { contentType: 'image/jpeg', handler: sendFile }
jpeg: { contentType: 'image/jpeg', handler: sendFile }
html: { contentType: 'text/html', handler: sendFile }
js: { contentType: 'text/javascript', handler: sendFile }
css: { contentType: 'text/css', handler: sendFile }
xml: { contentType: 'text/xml', handler: sendFile }
handleRequest = () ->
parts = req.uri.substr(1).split '/'
parts[0] = 'main' unless parts[0].length
action = parts[0] + '_action'
global[action]() if global[action]
fnPath = Config.documentRoot + req.uri
fn = realpath fnPath
notFound() unless fn
if isDir fn
if !req.uri.endsWith '/'
log 'redirect ' + req.uri + ' ' + fn + ' ' + fn.substr(fn.length-1, 1)
res.redirect req.uri + '/'
found = ''
for index in Config.directoryIndex
f = fn
f += '/'
f += index
if exists f
found = f
break
if found
fn = found
else if isFile fn + '/index.jst'
fn += '/index.jst'
else if isFile fn + '/index.coffee'
fn += '/index.coffee'
else if isFile fn + '/index.md'
fn += '/index.md'
notFound() unless isFile fn
res.status = 200
req.path = fn
parts = fn.split '.'
if parts.length > 1
extension = parts.pop().toLowerCase()
handler = contentTypes[extension]
if handler
res.contentType = handler.contentType
handler.handler fn
info = stat fn
notFound() unless info
res.contentType = 'text/plain'
res.sendHeaders()
net.sendFile @clientSocket, fn, 0, info.size
constructor: (@serverSocket) ->
global.req = new HttpRequest
global.res = new HttpResponse
HttpChild::pids = {}
spawn: (@serverSocket) ->
pid = fork()
if pid == -1
throw error()
else if pid != 0
HttpChild::pids[pid] = this;
return pid
@pid = getpid()
@run();
run: ->
serverSocket = @serverSocket
requestHandler = @requestHandler
semaphore = new Semaphore Config.lockFile
REQUESTS_PER_CHILD = Config.requestsPerChild || 100
requestsHandled = 0;
while requestsHandled < REQUESTS_PER_CHILD
semaphore.lock();
clientSocket = serverSocket.accept()
semaphore.unlock()
keepAlive = true
while keepAlive
keepAlive = false if ++requestsHandled > REQUESTS_PER_CHILD
try
break unless req.init clientSocket
keepAlive = res.init clientSocket, keepAlive, requestsHandled
requestHandler?()
handleRequest()
catch e
Error.exceptionHandler e unless e == 'RES.STOP'
res.flush()
# console.log req.remote_addr + ' ' + req.method + ' ' + req.uri + ' completed in ' + (new Date().getTime() - req.start) + '\n'
# logfile.write req.remote_addr + ' ' + req.method + ' ' + req.uri + ' completed in ' + (new Date().getTime() - req.start) + '\n'
req.close()
net.close clientSocket
v8.gc()
semaphore.close()
res.close()
return
wait: ->
while true
o = wait()
if HttpChild::pids?[o.pid]?
delete HttpChild::pids[o.pid]
this.spawn()
return
########################################################################################################################
main = (files...) ->
for file of files
if file.endsWith '.js' or file.endsWith '.coffee'
include file
serverSocket = new ServerSocket(Config.port)
child = new HttpChild serverSocket
child.spawn serverSocket for i in [ 1 .. Config.numChildren ]
child.wait()