├── .gitignore ├── .luacov ├── .travis.yml ├── LICENSE ├── README.md ├── example ├── dns_socket.lua ├── echo_client.lua ├── echo_server.lua ├── read_file.lua ├── read_stream.lua └── stdin_echo.lua ├── ludent.sh ├── rockspecs └── nodish-scm-1.rockspec ├── spec ├── events_spec.lua ├── process_spec.lua └── socket_spec.lua └── src └── nodish ├── _util.lua ├── buffer.lua ├── dns.lua ├── events.lua ├── fs.lua ├── js.lua ├── net.lua ├── net ├── server.lua └── socket.lua ├── nexttick.lua ├── process.lua └── stream.lua /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.*~ 3 | *#*# 4 | *#* 5 | luacov.report.out 6 | -------------------------------------------------------------------------------- /.luacov: -------------------------------------------------------------------------------- 1 | --- Global configuration file. Copy, customize and store in your 2 | -- project folder as '.luacov' for project specific configuration 3 | -- @class module 4 | -- @name luacov.defaults 5 | return { 6 | 7 | -- default filename to load for config options if not provided 8 | -- only has effect in 'luacov.defaults.lua' 9 | ["configfile"] = ".luacov", 10 | 11 | -- filename to store stats collected 12 | ["statsfile"] = "luacov.stats.out", 13 | 14 | -- filename to store report 15 | ["reportfile"] = "luacov.report.out", 16 | 17 | -- Run reporter on completion? (won't work for ticks) 18 | runreport = true, 19 | 20 | -- Delete stats file after reporting? 21 | deletestats = true, 22 | 23 | -- Patterns for files to include when reporting 24 | -- all will be included if nothing is listed 25 | -- (exclude overrules include, do not include 26 | -- the .lua extension) 27 | ["include"] = { 28 | "nodish%.*" 29 | }, 30 | 31 | -- Patterns for files to exclude when reporting 32 | -- all will be included if nothing is listed 33 | -- (exclude overrules include, do not include 34 | -- the .lua extension) 35 | ["exclude"] = { 36 | }, 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: erlang 2 | 3 | env: 4 | 5 | install: 6 | - sudo add-apt-repository ppa:mwild1/ppa -y 7 | - sudo apt-get update -y 8 | - sudo apt-get install luajit -y --force-yes 9 | - sudo apt-get install libev-dev 10 | - sudo apt-get install luarocks 11 | - git clone git://github.com/lipp/busted.git 12 | - cd busted 13 | - git checkout add-finally 14 | - sudo luarocks make 15 | - cd ../ 16 | - git clone git://github.com/justincormack/ljsyscall.git 17 | - cd ljsyscall 18 | - sudo luarocks make rockspec/ljsyscall-scm-1.rockspec 19 | - cd ../ 20 | 21 | script: "sudo luarocks make rockspecs/nodish-scm-1.rockspec && busted spec" 22 | 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Gerhard Preuss 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | nodish 2 | ========== 3 | 4 | A lightweight Lua equivalent to [Node.js](http://nodejs.org). [![Build Status](https://travis-ci.org/lipp/nodish.png?branch=master)](https://travis-ci.org/lipp/nodish). 5 | 6 | Motivation / Target Audience 7 | ============================ 8 | 9 | This framework might be for you, if you want node.js like API, but: 10 | 11 | - You have very limited ressources (memory) 12 | - You need a lua-ev backend 13 | - You are interested in a "Lua-only" (>90%) implementation 14 | 15 | Unlike [luvit](http://github.com/luvit/luvit) or [LuaNode](http://github.com/ignacio/luanode) this project does NOT (yet) try to be a complete node.js port. Instead it tries to keep dependecies as minimal as possible to keep size small for embedded systems. To use nodish you need: 16 | 17 | Interpreter 18 | ----------- 19 | - [luajit](http://luajit.org) (or Lua + luaffi) 20 | 21 | Lua modules 22 | ----------- 23 | - [ljsyscall](http://github.com/justincormack/ljsyscall) to interface to the system (sockets,read,write,etc) 24 | - [lua-ev](http://github.com/brimworks/lua-ev) as I/O loop framework 25 | 26 | C libraries 27 | ----------- 28 | - Any ljsyscall compatible libc 29 | - [libev](http://software.schmorp.de/pkg/libev.html) 30 | 31 | To reduce size further, you may be interested in [squish](http://matthewwild.co.uk/projects/squish/home). 32 | 33 | NOTE: If you have no ressource problems, you should use a more robust and mature implementation like [luvit](http://github.com/luvit/luvit) or [LuaNode](http://github.com/ignacio/luanode) or event better, just use the fantastic [Node.js](http://nodejs.org)! 34 | 35 | Examples 36 | ======== 37 | 38 | Echo Server 39 | ----------- 40 | 41 | ```lua 42 | local net = require'nodish.net' 43 | local process = require'nodish.process' 44 | 45 | net.createServer(function(client) 46 | client:pipe(client) 47 | client:pipe(process.stdout) 48 | end):listen(12345) 49 | 50 | process.loop() 51 | ``` 52 | 53 | Echo Client 54 | ----------- 55 | 56 | ```lua 57 | local net = require'nodish.net' 58 | local process = require'nodish.process' 59 | 60 | local client = net.connect(12345) 61 | client:on('connect',function() 62 | process.stdin:pipe(client) 63 | client:pipe(process.stdout) 64 | end) 65 | 66 | process.loop() 67 | ``` 68 | 69 | Installation 70 | ============ 71 | 72 | Linux (Debian based) 73 | -------------------- 74 | 75 | ```shell 76 | sudo add-apt-repository ppa:mwild1/ppa -y 77 | sudo apt-get update -y 78 | sudo apt-get install luajit -y --force-yes 79 | sudo apt-get install libev-dev 80 | sudo apt-get install luarocks 81 | git clone git://github.com/justincormack/ljsyscall.git 82 | cd ljsyscall 83 | sudo luarocks make rockspec/ljsyscall-scm-1.rockspec 84 | cd ../ 85 | git clone http://github.com/lipp/nodish.git 86 | cd nodish 87 | sudo luarocks make rockspecs/nodish-scm-1.rockspec 88 | ``` 89 | 90 | OSX (with homebrew) 91 | ------------------- 92 | 93 | ```shell 94 | brew install luajit 95 | brew install libev 96 | brew install luarocks 97 | git clone git://github.com/justincormack/ljsyscall.git 98 | cd ljsyscall 99 | sudo luarocks make rockspec/ljsyscall-scm-1.rockspec 100 | cd ../ 101 | git clone http://github.com/lipp/nodish.git 102 | cd nodish 103 | sudo luarocks make rockspecs/nodish-scm-1.rockspec 104 | ``` 105 | 106 | Status 107 | ====== 108 | 109 | Module | Status | API | Remarks 110 | -------------|-----------------|------------------------------------------------|-------------- 111 | net | Almost complete | [net](http://nodejs.org/api/net.html) | 112 | events | Complete | [events](http://nodejs.org/api/events.html) | 113 | process | Partial | [process](http://nodejs.org/api/process.html) | 114 | buffer | Almost complete | [buffer](http://nodejs.org/api/buffer.html) | add buffer.release and buffer.isReleased for better buffer reuse 115 | 116 | 117 | -------------------------------------------------------------------------------- /example/dns_socket.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env luajit 2 | local this_dir = arg[0]:match('(.+/)[^/]+%.lua') or './' 3 | package.path = this_dir..'../src/'..package.path 4 | 5 | local net = require'nodish.net' 6 | local process = require'nodish.process' 7 | 8 | local client = net.connect(53,'192.168.1.1') 9 | client:on('connect',function() 10 | print('connected') 11 | end) 12 | 13 | process.loop() 14 | -------------------------------------------------------------------------------- /example/echo_client.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env luajit 2 | local this_dir = arg[0]:match('(.+/)[^/]+%.lua') or './' 3 | package.path = this_dir..'../src/'..package.path 4 | 5 | local net = require'nodish.net' 6 | local process = require'nodish.process' 7 | 8 | local client = net.connect(12345) 9 | 10 | client:on('connect',function() 11 | print('connected to server') 12 | process.stdin:resume() 13 | process.stdin:pipe(client) 14 | end) 15 | 16 | client:on('fin',function(e) 17 | print('server closed') 18 | process.stdin:unpipe(client) 19 | os.exit(1) 20 | end) 21 | 22 | process.loop() 23 | -------------------------------------------------------------------------------- /example/echo_server.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env luajit 2 | local this_dir = arg[0]:match('(.+/)[^/]+%.lua') or './' 3 | package.path = this_dir..'../src/'..package.path 4 | 5 | local net = require'nodish.net' 6 | local process = require'nodish.process' 7 | 8 | net.createServer(function(client) 9 | client:pipe(client) 10 | client:pipe(process.stdout,false) 11 | end):listen(12345) 12 | 13 | process.loop() 14 | -------------------------------------------------------------------------------- /example/read_file.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env luajit 2 | local this_dir = arg[0]:match('(.+/)[^/]+%.lua') or './' 3 | package.path = this_dir..'../src/'..package.path 4 | 5 | local process = require'nodish.process' 6 | local fs = require'nodish.fs' 7 | 8 | fs.readFile(this_dir..'../README.md',function(err,data) 9 | process.stdout:write(data) 10 | end) 11 | 12 | process.loop() 13 | 14 | -------------------------------------------------------------------------------- /example/read_stream.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env luajit 2 | local this_dir = arg[0]:match('(.+/)[^/]+%.lua') or './' 3 | package.path = this_dir..'../src/'..package.path 4 | 5 | local process = require'nodish.process' 6 | local fs = require'nodish.fs' 7 | require'nodish.js' 8 | 9 | local readStream = fs.createReadStream(this_dir..'../README.md') 10 | readStream:on('open',function(fd) 11 | console.log('open',fd) 12 | end) 13 | 14 | readStream:on('data',function(data) 15 | console.log('data',data) 16 | end) 17 | 18 | process.loop() 19 | 20 | -------------------------------------------------------------------------------- /example/stdin_echo.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | local this_dir = arg[0]:match('(.+/)[^/]+%.lua') or './' 3 | package.path = this_dir..'../src/'..package.path 4 | 5 | local process = require'nodish.process' 6 | local ev = require'ev' 7 | 8 | process.stdin:pipe(process.stdout) 9 | process.stdin:resume() 10 | 11 | ev.Loop.default:loop() 12 | -------------------------------------------------------------------------------- /ludent.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | ludent $(find . -name "*.lua") 3 | -------------------------------------------------------------------------------- /rockspecs/nodish-scm-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "nodish" 2 | version = "scm-1" 3 | 4 | source = { 5 | url = "git://github.com/lipp/nodish.git", 6 | } 7 | 8 | description = { 9 | summary = "A lightweight Lua equivalent to Node.js", 10 | homepage = "http://github.com/lipp/nodish", 11 | license = "MIT/X11", 12 | detailed = "" 13 | } 14 | 15 | dependencies = { 16 | "lua >= 5.1", 17 | "ljsyscall", 18 | "lua-ev", 19 | } 20 | 21 | build = { 22 | type = 'none', 23 | install = { 24 | lua = { 25 | ['nodish.events'] = 'src/nodish/events.lua', 26 | ['nodish.process'] = 'src/nodish/process.lua', 27 | ['nodish.nexttick'] = 'src/nodish/nexttick.lua', 28 | ['nodish.dns'] = 'src/nodish/dns.lua', 29 | ['nodish.buffer'] = 'src/nodish/buffer.lua', 30 | ['nodish.net'] = 'src/nodish/net.lua', 31 | ['nodish._util'] = 'src/nodish/_util.lua', 32 | ['nodish.stream'] = 'src/nodish/stream.lua', 33 | ['nodish.net.socket'] = 'src/nodish/net/socket.lua', 34 | ['nodish.net.server'] = 'src/nodish/net/server.lua', 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /spec/events_spec.lua: -------------------------------------------------------------------------------- 1 | describe('The events module',function() 2 | local events = require'nodish.events' 3 | it('provides EventEmitter method',function() 4 | assert.is_function(events.EventEmitter) 5 | end) 6 | 7 | it('esock.new returns an object/table',function() 8 | assert.is_table(events.EventEmitter()) 9 | end) 10 | 11 | describe('with an emitter instance',function() 12 | local i 13 | before_each(function() 14 | i = events.EventEmitter() 15 | end) 16 | 17 | local expectedMethods = { 18 | 'addListener', 19 | 'on', 20 | 'once', 21 | 'removeListener', 22 | 'emit', 23 | } 24 | 25 | for _,method in ipairs(expectedMethods) do 26 | it('i.'..method..' is function',function() 27 | assert.is_function(i[method]) 28 | end) 29 | end 30 | 31 | it('i.addListener and i.on are the same method',function() 32 | assert.is_equal(i.addListener,i.on) 33 | end) 34 | 35 | it('i.on callback gets called with correct arguments',function(done) 36 | i:on('foo',async(function(a,b) 37 | assert.is_equal(a,'test') 38 | assert.is_equal(b,123) 39 | done() 40 | end)) 41 | i:emit('foo','test',123) 42 | end) 43 | 44 | it('i.on callback gets called once for each emit',function(done) 45 | local count = 0 46 | i:on('foo',async(function() 47 | count = count + 1 48 | if count == 2 then 49 | done() 50 | end 51 | end)) 52 | i:emit('foo') 53 | i:emit('foo') 54 | end) 55 | 56 | it('once is really called once',function(done) 57 | local count = 0 58 | i:once('bar',async(function() 59 | count = count + 1 60 | end)) 61 | local b = 0 62 | i:on('bar',async(function() 63 | b = b + 1 64 | if b == 2 then 65 | assert.is_equal(count,1) 66 | done() 67 | end 68 | end)) 69 | i:emit('bar',1) 70 | i:emit('bar',2) 71 | end) 72 | 73 | it('once can be canceled',function(done) 74 | local entered 75 | local onceCb = async(function() 76 | entered = true 77 | end) 78 | i:once('bar',onceCb) 79 | i:on('bar',async(function() 80 | assert.is_nil(entered) 81 | done() 82 | end)) 83 | i:removeListener('bar',onceCb) 84 | i:emit('bar') 85 | end) 86 | 87 | it('removeAllListeners works for a specific event',function(done) 88 | local entered = 0 89 | i:on('foo',async(function() 90 | entered = entered + 1 91 | end)) 92 | i:on('foo',async(function() 93 | entered = entered + 1 94 | end)) 95 | i:on('bar',async(function() 96 | assert.is_equal(entered,0) 97 | done() 98 | end)) 99 | i:removeAllListeners('foo') 100 | i:emit('foo') 101 | i:emit('bar') 102 | end) 103 | 104 | it('removeAllListeners works for all events',function(done) 105 | local entered = 0 106 | i:on('foo',async(function() 107 | entered = entered + 1 108 | end)) 109 | i:on('foo',async(function() 110 | entered = entered + 1 111 | end)) 112 | i:on('bar',async(function() 113 | entered = entered + 1 114 | -- done() 115 | end)) 116 | i:removeAllListeners() 117 | i:emit('foo') 118 | i:emit('bar') 119 | assert.is_equal(entered,0) 120 | done() 121 | end) 122 | 123 | end) 124 | end) 125 | -------------------------------------------------------------------------------- /spec/process_spec.lua: -------------------------------------------------------------------------------- 1 | setloop('ev') 2 | 3 | describe('The process module',function() 4 | local process = require'nodish.process' 5 | 6 | it('provides nextTick method',function() 7 | assert.is_function(process.nextTick) 8 | end) 9 | 10 | it('the nextTick callback gets called',function(done) 11 | process.nextTick(async(function() 12 | done() 13 | end)) 14 | end) 15 | 16 | it('the nextTick callback gets called from another call context',function(done) 17 | local s = {} 18 | process.nextTick(async(function() 19 | assert.is_true(s.dirty) 20 | done() 21 | end)) 22 | s.dirty = true 23 | end) 24 | 25 | end) 26 | -------------------------------------------------------------------------------- /spec/socket_spec.lua: -------------------------------------------------------------------------------- 1 | setloop('ev') 2 | 3 | local ev = require'ev' 4 | 5 | local cleanup = function() 6 | os.execute('killall nc 2>/dev/null') 7 | os.execute('rm infifo 2>/dev/null') 8 | os.execute('rm outfifo 2>/dev/null') 9 | end 10 | 11 | cleanup() 12 | 13 | os.execute('mkfifo infifo') 14 | os.execute('mkfifo outfifo') 15 | os.execute('nc -6 -k -l 12345 < infifo > outfifo &') 16 | 17 | local infifo = io.open('infifo','w') 18 | local outfifo = io.open('outfifo','r') 19 | 20 | describe('The net.socket module',function() 21 | 22 | teardown(function() 23 | cleanup() 24 | end) 25 | 26 | local socket = require'nodish.net.socket' 27 | it('provides new method',function() 28 | assert.is_function(socket.new) 29 | end) 30 | 31 | it('socket.new returns an object/table',function() 32 | assert.is_table(socket.new()) 33 | end) 34 | 35 | it('error and close events are emitted once',function(done) 36 | local s = socket.new() 37 | local dead_port = 16237 38 | s:connect(dead_port) 39 | local nerrors = 0 40 | local ncloses = 0 41 | s:on('error',async(function() 42 | nerrors = nerrors + 1 43 | s:destroy() 44 | end)) 45 | 46 | s:on('close',async(function() 47 | ncloses = ncloses + 1 48 | end)) 49 | ev.Timer.new(async(function() 50 | assert.is_equal(nerrors,1) 51 | assert.is_equal(ncloses,1) 52 | done() 53 | end),0.01):start(ev.Loop.default) 54 | end) 55 | 56 | describe('with an net.socket instance',function() 57 | local i 58 | before_each(function() 59 | i = socket.new() 60 | end) 61 | 62 | after_each(function(done) 63 | i:destroy() 64 | -- this is required since netcat (nc) 65 | -- seems to return "Connection refused" if tests are 66 | -- executed to fast 67 | ev.Timer.new(async(function() 68 | done() 69 | end),0.01):start(ev.Loop.default) 70 | end) 71 | 72 | local expected_methods = { 73 | 'connect', 74 | 'write', 75 | 'fin', 76 | 'destroy', 77 | 'pause', 78 | 'resume', 79 | 'setTimeout', 80 | 'setNoDelay', 81 | 'setKeepAlive', 82 | 'on', 83 | 'once', 84 | 'addListener', 85 | 'removeListener', 86 | } 87 | 88 | for _,method in ipairs(expected_methods) do 89 | it('i.'..method..' is function',function() 90 | assert.is_function(i[method]) 91 | end) 92 | end 93 | 94 | it('can connect to www.google.com',function(done) 95 | i:on('connect',async(function(j) 96 | assert.is_same(i,j) 97 | done() 98 | end)) 99 | i:on('error',async(function(err) 100 | assert.is_nil(err) 101 | end)) 102 | i:connect(80,'www.google.com') 103 | end) 104 | 105 | it('can connect to www.google.com and address is correct',function(done) 106 | i:on('connect',async(function(j) 107 | local addr = i:address() 108 | assert.is_number(addr.port) 109 | assert.is_string(addr.address) 110 | assert.is_true(addr.family == 'IPv4' or addr.family == 'IPv6') 111 | done() 112 | end)) 113 | i:on('error',async(function(err) 114 | assert.is_nil(err) 115 | end)) 116 | i:connect(80,'www.google.com') 117 | end) 118 | 119 | it('can write and drain event is emitted',function(done) 120 | i:on('drain',async(function() 121 | local data = outfifo:read('*l') 122 | assert.is_equal(data,'halloposl') 123 | end)) 124 | i:on('connect',async(function() 125 | i:write('hallo') 126 | i:fin('posl\n') 127 | end)) 128 | i:on('finish',async(function() 129 | done() 130 | end)) 131 | i:on('error',async(function(err) 132 | assert.is_nil(err) 133 | end)) 134 | i:connect(12345) 135 | end) 136 | 137 | it('can write and drain event is emitted with 100k bytes',function(done) 138 | local lines = 20 139 | local many_bytes = string.rep('hallo',1000) 140 | i:on('drain',async(function() 141 | for x = 1,lines do 142 | local data = outfifo:read('*l') 143 | assert.is_equal(data,many_bytes) 144 | end 145 | assert.is_equal(i.bytesWritten,20*(#many_bytes+1)) 146 | done() 147 | end)) 148 | i:on('connect',async(function() 149 | for x = 1,lines do 150 | i:write(many_bytes..'\n') 151 | end 152 | i:fin() 153 | end)) 154 | i:on('error',async(function(err) 155 | assert.is_nil(err) 156 | end)) 157 | i:connect(12345) 158 | end) 159 | 160 | it('address() is correct',function(done) 161 | i:on('connect',async(function() 162 | local addr = i:address() 163 | assert.is_number(addr.port) 164 | assert.is_string(addr.address) 165 | assert.is_true(addr.family == 'IPv4' or addr.family == 'IPv6') 166 | assert.is_number(i.remotePort) 167 | assert.is_string(i.remoteAddress) 168 | done() 169 | end)) 170 | i:on('error',async(function(err) 171 | assert.is_nil(err) 172 | end)) 173 | i:connect(12345) 174 | end) 175 | 176 | it('data event is emitted with correct argument',function(done) 177 | local nc_data = 'hello world' 178 | i:on('data',async(function(data) 179 | assert.is_same(data,nc_data) 180 | assert.is_equal(i.bytesRead,#nc_data) 181 | done() 182 | end)) 183 | i:on('connect',async(function() 184 | infifo:write(nc_data) 185 | infifo:flush() 186 | end)) 187 | i:on('error',async(function(err) 188 | assert.is_nil(err) 189 | end)) 190 | i:connect(12345) 191 | i:setEncoding('utf8') 192 | end) 193 | 194 | it('support ipv6',function(done) 195 | i:on('connect',async(function() 196 | done() 197 | end)) 198 | i:on('error',async(function(err) 199 | assert.is_nil(err) 200 | end)) 201 | i:connect(12345,'::1') 202 | end) 203 | 204 | end) 205 | end) 206 | -------------------------------------------------------------------------------- /src/nodish/_util.lua: -------------------------------------------------------------------------------- 1 | local loop = require'ev'.Loop.default 2 | 3 | local daemonize = function(watcher,makeDaemon) 4 | -- keep pending info, since watcher:stop also 5 | -- would call watcher:clear_pending internally 6 | -- with no chance of recovery 7 | local revents = watcher:clear_pending(loop) 8 | watcher:stop(loop) 9 | watcher:start(loop,makeDaemon) 10 | if revents ~= 0 then 11 | watcher:callback()(loop,watcher,revents) 12 | end 13 | end 14 | 15 | local ref = function(watcher) 16 | daemonize(watcher,false) 17 | end 18 | 19 | local unref = function(watcher) 20 | daemonize(watcher,true) 21 | end 22 | 23 | 24 | return { 25 | ref = ref, 26 | unref = unref, 27 | } 28 | -------------------------------------------------------------------------------- /src/nodish/buffer.lua: -------------------------------------------------------------------------------- 1 | local ffi = require'ffi' 2 | local S = require'syscall' 3 | 4 | 5 | local types = { 6 | Double = { 7 | ctype = 'double', 8 | size = 8, 9 | }, 10 | Float = { 11 | ctype = 'float', 12 | size = 4 13 | }, 14 | UInt8 = { 15 | ctype = 'uint8_t', 16 | size = 1, 17 | }, 18 | UInt16 = { 19 | ctype = 'uint16_t', 20 | size = 2, 21 | }, 22 | UInt32 = { 23 | ctype = 'uint32_t', 24 | size = 4, 25 | }, 26 | Int8 = { 27 | ctype = 'int8_t', 28 | size = 1, 29 | }, 30 | Int16 = { 31 | ctype = 'int16_t', 32 | size = 2, 33 | }, 34 | Int32 = { 35 | ctype = 'int32_t', 36 | size = 4, 37 | }, 38 | } 39 | 40 | local tmpBuf = ffi.new('uint8_t[8]') 41 | 42 | local methods = {} 43 | 44 | for typeName,typeInfo in pairs(types) do 45 | local readName = 'read'..typeName 46 | local ctype = typeInfo.ctype..'*' 47 | local size = typeInfo.size 48 | methods[readName] = function(self,offset,noAssert) 49 | if not noAssert then 50 | if offset + size >= self.length then 51 | error('out of bounds') 52 | end 53 | end 54 | return ffi.cast(ctype,self.buf + offset)[0] 55 | end 56 | local swapRead = function(self,offset,noAssert) 57 | if not noAssert then 58 | if offset + size >= self.length then 59 | error('out of bounds') 60 | end 61 | end 62 | for i=0,size-1 do 63 | tmpBuf[i] = self.buf[size-i-1+offset] 64 | end 65 | return ffi.cast(ctype,tmpBuf)[0] 66 | end 67 | 68 | if ffi.abi('be') then 69 | methods[readName..'BE'] = methods[readName] 70 | methods[readName..'LE'] = swapRead 71 | else 72 | methods[readName..'BE'] = swapRead 73 | methods[readName..'LE'] = methods[readName] 74 | end 75 | end 76 | 77 | for typeName,typeInfo in pairs(types) do 78 | local writeName = 'write'..typeName 79 | local size = typeInfo.size 80 | local store = ffi.new(typeInfo.ctype..'[1]') 81 | methods[writeName] = function(self,val,offset,noAssert) 82 | if not noAssert then 83 | if offset + size >= self.length then 84 | error('out of bounds') 85 | end 86 | end 87 | store[0] = val 88 | ffi.copy(self.buf + offset,store,size) 89 | end 90 | local swapWrite = function(self,val,offset,noAssert) 91 | if not noAssert then 92 | if offset + size >= self.length then 93 | error('out of bounds') 94 | end 95 | end 96 | store[0] = val 97 | for i=0,size-1 do 98 | tmpBuf[i] = store[size-i-1] 99 | end 100 | ffi.copy(self.buf + offset,tmpBuf,size) 101 | end 102 | 103 | if ffi.abi('be') then 104 | methods[writeName..'BE'] = methods[writeName] 105 | methods[writeName..'LE'] = swapWrite 106 | else 107 | methods[writeName..'BE'] = swapWrite 108 | methods[writeName..'LE'] = methods[writeName] 109 | end 110 | end 111 | 112 | methods.write = function(self,string,offset,length,encoding) 113 | offset = offset or 0 114 | length = length or (self.length - offset) 115 | ffi.copy(self.buf + offset,string,math.min(length,#string)) 116 | end 117 | 118 | methods.toString = function(self,encoding,offset,stop) 119 | offset = offset or 0 120 | stop = stop or self.length 121 | local len = stop - offset 122 | return ffi.string(self.buf + offset,len) 123 | end 124 | 125 | methods.fill = function(self,value,offset,stop) 126 | print(self.length) 127 | offset = offset or 0 128 | stop = stop or self.length 129 | local len = stop - offset 130 | ffi.fill(self.buf+offset,len,string.byte(value)) 131 | end 132 | 133 | methods.release = function(self,release) 134 | self.released = release ~= nil and release or true 135 | end 136 | 137 | methods.isReleased = function(self) 138 | return self.released 139 | end 140 | 141 | methods._setLength = function(self,length) 142 | assert(length <= self.length) 143 | self.length = length 144 | end 145 | 146 | local mt = { 147 | __index = function(self,key) 148 | if rawget(self,'released') then 149 | error('buffer is released and cannot be accesed',2) 150 | end 151 | if type(key) == 'number' then 152 | return self.buf[key] 153 | else 154 | return methods[key] 155 | end 156 | end, 157 | __tostring = function(self) 158 | local hex = {} 159 | hex[1] = ' maxListeners and maxListeners ~= 0 then 24 | error('maxListeners limit reached for event '..event) 25 | end 26 | tinsert(listeners[event],listener) 27 | self:emit('newListener',event,listener) 28 | return self 29 | end 30 | 31 | self.on = self.addListener 32 | 33 | self.removeListener = function(_,event,oldlistener) 34 | if listeners[event] then 35 | for i,listener in ipairs(listeners[event]) do 36 | if listener == oldlistener then 37 | tremove(listeners[event],i) 38 | self:emit('removeListener',event,listener) 39 | return self 40 | end 41 | end 42 | end 43 | return self 44 | end 45 | 46 | local removeAllListenersForEvent = function(event) 47 | local listenersbak = listeners[event] or {} 48 | listeners[event] = nil 49 | for _,listener in ipairs(listenersbak) do 50 | self:emit('removeListener',event,listener) 51 | end 52 | end 53 | 54 | self.removeAllListeners = function(_,event) 55 | if event then 56 | removeAllListenersForEvent(event) 57 | else 58 | for event in pairs(listeners) do 59 | removeAllListenersForEvent(event) 60 | end 61 | end 62 | return self 63 | end 64 | 65 | self.once = function(_,event,listener) 66 | local remove 67 | remove = function() 68 | self:removeListener(event,remove) 69 | self:removeListener(event,listener) 70 | end 71 | self:addListener(event,listener) 72 | self:addListener(event,remove) 73 | return self 74 | end 75 | 76 | local emitListeners = {} 77 | 78 | self.emit = function(_,event,...) 79 | local listeners = listeners[event] 80 | if listeners then 81 | for i,listener in ipairs(listeners) do 82 | emitListeners[i] = listener 83 | end 84 | for i=1,#listeners do 85 | local ok,err = pcall(emitListeners[i],...) 86 | if not ok then 87 | self:emit('error',err) 88 | print('error in listener',err) 89 | end 90 | end 91 | end 92 | return self 93 | end 94 | 95 | return self 96 | end 97 | 98 | return { 99 | EventEmitter = EventEmitter, 100 | } 101 | -------------------------------------------------------------------------------- /src/nodish/fs.lua: -------------------------------------------------------------------------------- 1 | local S = require'syscall' 2 | local events = require'nodish.events' 3 | local stream = require'nodish.stream' 4 | local nextTick = require'nodish.nexttick'.nextTick 5 | local util = require'nodish._util' 6 | local ev = require'ev' 7 | local buffer = require'nodish.buffer' 8 | local octal = require "syscall.helpers".octal 9 | local loop = ev.Loop.default 10 | 11 | local createReadStream = function(path,options) 12 | options = options or {} 13 | local fd = options.fd 14 | local encoding = options.encoding 15 | local flags = options.flags or 'r' 16 | local autoClose 17 | if options.autoClose ~= nil then 18 | autoClose = options.autoClose 19 | else 20 | autoClose = true 21 | end 22 | local mode 23 | if options.mode then 24 | mode = octal(options.mode) 25 | else 26 | mode = octal('0666') 27 | end 28 | local self = events.EventEmitter() 29 | self.watchers = {} 30 | stream.readable(self) 31 | 32 | if not fd then 33 | local err 34 | fd,err = S.open(path,"rdonly",438)--mode) 35 | if not fd then 36 | error(err) 37 | end 38 | end 39 | local readable = true 40 | fd:nonblock(true) 41 | 42 | self.destroy = function(_,hadError) 43 | for _,watcher in pairs(self.watchers) do 44 | watcher:stop(loop) 45 | end 46 | if fd and autoClose then 47 | fd:close() 48 | fd = nil 49 | self:emit('close',hadError) 50 | end 51 | end 52 | 53 | self:once('error',function(err) 54 | local hadError = err and true 55 | self:destroy(hadError) 56 | end) 57 | 58 | self:once('fin',function() 59 | self:destroy(hadError) 60 | end) 61 | 62 | local buf 63 | local chunkSize = 4096*2 64 | 65 | self._read = function() 66 | if not buf or not buf:isReleased() then 67 | buf = buffer.Buffer(chunkSize) 68 | end 69 | local ret,err = fd:read(buf.buf,chunkSize) 70 | if ret then 71 | if ret > 0 then 72 | buf:_setLength(ret) 73 | assert(buf.length == ret) 74 | data = buf 75 | return data,err 76 | elseif ret == 0 then 77 | return nil,nil,true 78 | end 79 | end 80 | return nil,err 81 | end 82 | 83 | nextTick(function() 84 | self:emit('open',fd:getfd()) 85 | self:addReadWatcher(fd:getfd()) 86 | self:resume() 87 | end) 88 | 89 | return self 90 | end 91 | 92 | local readFile = function(path,callback) 93 | local rs = createReadStream(path) 94 | rs:on('error',function(err) 95 | callback(err) 96 | end) 97 | local content = '' 98 | rs:on('data',function(data) 99 | content = content..data:toString() 100 | end) 101 | rs:on('fin',function() 102 | callback(nil,content) 103 | end) 104 | end 105 | 106 | return { 107 | createReadStream = createReadStream, 108 | readFile = readFile, 109 | } 110 | -------------------------------------------------------------------------------- /src/nodish/js.lua: -------------------------------------------------------------------------------- 1 | local process = require'nodish.process' 2 | local ev = require'ev' 3 | local loop = ev.Loop.default 4 | local timers = {} 5 | local timerCount = 0 6 | 7 | setTimeout = function(f,msecs) 8 | timerCount = timerCount + 1 9 | local timer = ev.Timer.new(function() 10 | f() 11 | timers[timerCount] = nil 12 | end,msecs*1000) 13 | timer:start(loop) 14 | timers[timerCount] = timer 15 | return timerCount 16 | end 17 | 18 | clearTimeout = function(id) 19 | if timers[id] then 20 | timers[id]:stop(loop) 21 | end 22 | end 23 | 24 | setInterval = function(f,msecs) 25 | timerCount = timerCount + 1 26 | local timer = ev.Timer.new(function() 27 | f() 28 | end,msecs*1000,msecs*1000) 29 | timer:start(loop) 30 | timers[timerCount] = timer 31 | return timerCount 32 | end 33 | 34 | clearInterval = function(id) 35 | if timers[id] then 36 | timers[id]:stop(loop) 37 | end 38 | end 39 | 40 | local table_print 41 | -- from http://lua-users.org/wiki/TableSerialization 42 | table_print = function (tt, indent, done) 43 | done = done or {} 44 | indent = indent or 0 45 | if type(tt) == "table" then 46 | if not getmetatable(tt) or not getmetatable(tt).__tostring then 47 | local sb = {} 48 | for key, value in pairs (tt) do 49 | table.insert(sb, string.rep (" ", indent)) -- indent it 50 | if type (value) == "table" and not done [value] then 51 | done [value] = true 52 | table.insert(sb, "{\n"); 53 | table.insert(sb, table_print (value, indent + 2, done)) 54 | table.insert(sb, string.rep (" ", indent)) -- indent it 55 | table.insert(sb, "}\n"); 56 | elseif "number" == type(key) then 57 | table.insert(sb, string.format("\"%s\"\n", tostring(value))) 58 | else 59 | table.insert(sb, string.format( 60 | "%s = \"%s\"\n", tostring (key), tostring(value))) 61 | end 62 | end 63 | return table.concat(sb) 64 | else 65 | return tostring(tt) 66 | end 67 | else 68 | return tt .. "\n" 69 | end 70 | end 71 | 72 | local to_string = function( tbl ) 73 | if "nil" == type( tbl ) then 74 | return tostring(nil) 75 | elseif "table" == type( tbl ) then 76 | return table_print(tbl) 77 | elseif "string" == type( tbl ) then 78 | return tbl 79 | else 80 | return tostring(tbl) 81 | end 82 | end 83 | 84 | console = {} 85 | 86 | console.log = function(...) 87 | local args = {...} 88 | for i,arg in ipairs(args) do 89 | process.stdout:write(to_string(arg)..'\t') 90 | end 91 | process.stdout:write('\n') 92 | end 93 | -------------------------------------------------------------------------------- /src/nodish/net.lua: -------------------------------------------------------------------------------- 1 | local socket = require'nodish.net.socket' 2 | local server = require'nodish.net.server' 3 | 4 | return { 5 | socket = socket, 6 | Socket = socket.new, 7 | connect = socket.connect, 8 | createConnection = socket.createConnection, 9 | createServer = server.createServer, 10 | isIP = socket.isIP, 11 | isIPv4 = socket.isIPv4, 12 | isIPv6 = socket.isIPv6, 13 | } 14 | -------------------------------------------------------------------------------- /src/nodish/net/server.lua: -------------------------------------------------------------------------------- 1 | local nextTick = require'nodish.process'.nextTick 2 | local S = require'syscall' 3 | local h = require "syscall.helpers" 4 | local events = require'nodish.events' 5 | local ev = require'ev' 6 | local nsocket = require'nodish.net.socket' 7 | local util = require'nodish._util' 8 | local dns = require'nodish.dns' 9 | local ffi = require'ffi' 10 | 11 | local loop = ev.Loop.default 12 | 13 | local INADDR_ANY = 0x0 14 | 15 | local inaddr = function(port,addr) 16 | local inaddr = S.t.sockaddr_in() 17 | inaddr.family = S.c.AF.INET 18 | inaddr.port = port 19 | if addr then 20 | inaddr.addr = addr 21 | else 22 | inaddr.sin_addr.s_addr = INADDR_ANY--h.htonl(INADDR_ANY) 23 | end 24 | return inaddr 25 | end 26 | 27 | --- creates and binds a listening socket for 28 | -- ipv4 and (if available) ipv6. 29 | local sbind = function(host,port,backlog) 30 | local server = S.socket('inet','stream') 31 | server:nonblock(true) 32 | server:setsockopt('socket','reuseaddr',true) 33 | -- TODO respect host 34 | local hostAddr 35 | if host then 36 | hostAddr = dns.getaddrinfo(host)[1].addr --maybe nil 37 | end 38 | server:bind(inaddr(port,hostAddr)) 39 | server:listen(backlog or 511) 40 | return server 41 | end 42 | 43 | local new = function(options) 44 | local allowHalfOpen = options and options.allowHalfOpen 45 | local self = events.EventEmitter() 46 | local conCount = 0 47 | local lsock 48 | local listenIo 49 | local closing 50 | 51 | self:once('error',function(err) 52 | if lsock then 53 | lsock:close() 54 | end 55 | self:emit('close',err) 56 | end) 57 | 58 | self.listen = function(_,port,host,backlog,callback) 59 | assert(_ == self) 60 | lsock = sbind(host,port,backlog) 61 | nextTick(function() 62 | self:emit('listening',self) 63 | end) 64 | if callback then 65 | self:once('listening',callback) 66 | end 67 | listenIo = ev.IO.new( 68 | function() 69 | local sock,err = lsock:accept() 70 | if sock then 71 | local s = nsocket.new({ 72 | fd = sock, 73 | allowHalfOpen = allowHalfOpen 74 | }) 75 | conCount = conCount + 1 76 | assert(conCount > 0) 77 | s:once('close',function() 78 | assert(conCount > 0) 79 | conCount = conCount - 1 80 | if closing and conCount == 0 then 81 | self:emit('close') 82 | end 83 | end) 84 | self:emit('connection',s) 85 | else 86 | assert(err) 87 | self:emit('error',err) 88 | end 89 | end, 90 | lsock:getfd(), 91 | ev.READ) 92 | listenIo:start(loop) 93 | 94 | end 95 | 96 | self.unref = function() 97 | util.unref(listenIo) 98 | end 99 | 100 | self.ref = function() 101 | util.ref(listenIo) 102 | end 103 | 104 | self.address = function() 105 | if lsock then 106 | local addr = lsock:getsockname() 107 | local resObj = { 108 | address = tostring(addr.addr), 109 | port = addr.port, 110 | family = family[addr.family], 111 | } 112 | return resObj 113 | end 114 | end 115 | 116 | self.close = function(_,cb) 117 | listenIo:stop(loop) 118 | lsock:close() 119 | closing = true 120 | if cb then 121 | self:once('close',cb) 122 | end 123 | if conCount == 0 then 124 | self:emit('close') 125 | end 126 | end 127 | return self 128 | end 129 | 130 | local createServer = function(...) 131 | local args = {...} 132 | local options 133 | local connectionListener 134 | if type(args[1]) == 'table' then 135 | options = args[1] 136 | elseif type(args[1]) == 'function' then 137 | connectionListener = args[1] 138 | end 139 | if #args > 1 then 140 | connectionListener = args[2] 141 | end 142 | 143 | local server = new(options) 144 | server:on('connection',connectionListener) 145 | return server 146 | end 147 | 148 | return { 149 | createServer = createServer 150 | } 151 | -------------------------------------------------------------------------------- /src/nodish/net/socket.lua: -------------------------------------------------------------------------------- 1 | local S = require'syscall' 2 | local events = require'nodish.events' 3 | local stream = require'nodish.stream' 4 | local nextTick = require'nodish.nexttick'.nextTick 5 | local util = require'nodish._util' 6 | local ev = require'ev' 7 | local ffi = require'ffi' 8 | local dns = require'nodish.dns' 9 | local buffer = require'nodish.buffer' 10 | 11 | local loop = ev.Loop.default 12 | 13 | -- TODO: employ ljsyscall 14 | local isIP = function(ip) 15 | return dns.getaddrinfo(ip) 16 | end 17 | 18 | -- TODO: employ ljsyscall 19 | local isIPv6 = function(ip) 20 | local addrinfo,err = luasocket.dns.getaddrinfo(ip) 21 | if addrinfo then 22 | assert(#addrinfo > 0) 23 | if addrinfo[1].family == 'IPv6' then 24 | return true 25 | end 26 | end 27 | return false 28 | end 29 | 30 | -- TODO: employ ljsyscall 31 | local isIPv4 = function(ip) 32 | return isIP(ip) and not isIPv6(ip) 33 | end 34 | 35 | local new = function(options) 36 | options = options or {} 37 | local readable = options.readable or true 38 | local writable = options.writable or true 39 | local allowHalfOpen = options.allowHalfOpen or false 40 | local sock = options.fd or nil 41 | local self = events.EventEmitter() 42 | local watchers = {} 43 | self.watchers = watchers 44 | 45 | if readable then 46 | stream.readable(self) 47 | end 48 | 49 | if writable then 50 | stream.writable(self) 51 | end 52 | 53 | local connecting = false 54 | local connected = false 55 | local closing = false 56 | 57 | self:once('error',function(err) 58 | local hadError = err and true 59 | self:destroy(hadError) 60 | end) 61 | 62 | if readable then 63 | self:once('fin',function() 64 | if not allowHalfOpen then 65 | -- socket.fin has not been called yet 66 | if writable then 67 | self:once('finish',function() 68 | self:destroy() 69 | end) 70 | 71 | self:fin() 72 | else 73 | self:destroy() 74 | end 75 | end 76 | end) 77 | end 78 | 79 | -- TODO: use metatable __index access for lazy loading 80 | local addAddressesToSelf = function() 81 | local remoteAddr = sock:getpeername() 82 | 83 | self.remoteAddress = tostring(remoteAddr.addr) 84 | self.remotePort = remoteAddr.port 85 | 86 | local localAddr = sock:getsockname() 87 | self.localAddress = tostring(localAddr.addr) 88 | self.localPort = localAddr.port 89 | end 90 | 91 | local onConnect = function() 92 | connecting = false 93 | connected = true 94 | 95 | addAddressesToSelf() 96 | if readable then 97 | local chunkSize = 4096*2 98 | local buf 99 | -- provide read mehod for stream 100 | self._read = function() 101 | if not sock then 102 | return nil,nil,true 103 | end 104 | if not buf or not buf:isReleased() then 105 | buf = buffer.Buffer(chunkSize) 106 | end 107 | local ret,err = sock:read(buf.buf,chunkSize) 108 | if ret then 109 | if ret > 0 then 110 | buf:_setLength(ret) 111 | assert(buf.length == ret) 112 | data = buf 113 | return data,err 114 | elseif ret == 0 then 115 | return nil,nil,true 116 | end 117 | end 118 | return nil,err 119 | end 120 | self:addReadWatcher(sock:getfd()) 121 | self:resume() 122 | end 123 | 124 | if writable then 125 | -- provide write method for stream 126 | self._write = function(_,data) 127 | return sock:write(data) 128 | end 129 | self:addWriteWatcher(sock:getfd()) 130 | end 131 | self:emit('connect',self) 132 | end 133 | 134 | if sock then 135 | sock:nonblock(true) 136 | onConnect() 137 | end 138 | 139 | self.connect = function(_,port,ip) 140 | ip = ip or '127.0.0.1' 141 | if not isIP(ip) then 142 | onError(err) 143 | end 144 | if sock and closing then 145 | self:once('close',function(self) 146 | self:_connect(port,ip) 147 | end) 148 | elseif not connecting then 149 | self:_connect(port,ip) 150 | end 151 | end 152 | 153 | self._connect = function(_,port,ip) 154 | local addrinfo = dns.getaddrinfo(ip)[1] 155 | local addr 156 | if addrinfo.family == 'IPv6' then 157 | sock = S.socket('inet6','stream') 158 | addr = S.types.t.sockaddr_in6(port,addrinfo.addr) 159 | else 160 | sock = S.socket('inet','stream') 161 | addr = S.types.t.sockaddr_in(port,addrinfo.addr) 162 | end 163 | sock:nonblock(true) 164 | connecting = true 165 | closing = false 166 | local _,err = sock:connect(addr) 167 | if not err or err.errno == S.c.E.ISCONN then 168 | onConnect() 169 | elseif err.errno == S.c.E.INPROGRESS then 170 | watchers.connect = ev.IO.new(function(loop,io) 171 | io:stop(loop) 172 | local _,err = sock:connect(addr) 173 | if not err or err.errno == S.c.E.ISCONN then 174 | watchers.connect = nil 175 | onConnect() 176 | else 177 | self:emit('error',tostring(err)) 178 | end 179 | end,sock:getfd(),ev.WRITE) 180 | watchers.connect:start(loop) 181 | else 182 | nextTick(function() 183 | self:emit('error',tostring(err)) 184 | end) 185 | end 186 | end 187 | 188 | local writableWrite = self.write 189 | 190 | self.write = function(_,data) 191 | if not writable then 192 | error('socket is not writable') 193 | end 194 | if connecting then 195 | self:once('connect',function() 196 | writableWrite(_,data) 197 | end) 198 | else 199 | assert(connected) 200 | writableWrite(_,data) 201 | end 202 | return self 203 | end 204 | 205 | local writableFin = self.fin 206 | 207 | self.fin = function(_,data) 208 | if not writable then 209 | return 210 | end 211 | writable = false 212 | self:once('finish',function() 213 | if sock then 214 | sock:shutdown(S.c.SHUT.WR) 215 | end 216 | end) 217 | writableFin(_,data) 218 | return self 219 | end 220 | 221 | self.destroy = function(_,hadError) 222 | writable = false 223 | readable = false 224 | for _,watcher in pairs(watchers) do 225 | watcher:stop(loop) 226 | end 227 | if sock then 228 | sock:close() 229 | sock = nil 230 | self:emit('close',hadError) 231 | end 232 | end 233 | 234 | local family = { 235 | [S.c.AF.INET] = 'IPv4', 236 | [S.c.AF.INET6] = 'IPv6', 237 | } 238 | 239 | self.address = function() 240 | if sock then 241 | local addr = sock:getsockname() 242 | local resObj = { 243 | address = tostring(addr.addr), 244 | port = addr.port, 245 | family = family[addr.family], 246 | } 247 | return resObj 248 | end 249 | end 250 | 251 | self.setTimeout = function(_,msecs,callback) 252 | if msecs > 0 and type(msecs) == 'number' then 253 | if watchers.timer then 254 | watchers.timer:stop(loop) 255 | end 256 | local secs = msecs / 1000 257 | watchers.timer = ev.Timer.new(function() 258 | self:emit('timeout') 259 | end,secs,secs) 260 | watchers.timer:start(loop) 261 | if callback then 262 | self:once('timeout',callback) 263 | end 264 | else 265 | watchers.timer:stop(loop) 266 | if callback then 267 | self:removeListener('timeout',callback) 268 | end 269 | end 270 | end 271 | 272 | self.setKeepAlive = function(_,enable) 273 | if sock then 274 | sock:setsockopt(S.c.SO.KEEPALIVE,enable) 275 | else 276 | end 277 | end 278 | 279 | self.setNoDelay = function(_,enable) 280 | if sock then 281 | sock:setoption('tcp-nodelay',enable) 282 | end 283 | end 284 | 285 | self.unref = function() 286 | for _,watcher in pairs(self.watchers) do 287 | util.unref(watcher) 288 | end 289 | end 290 | 291 | self.ref = function() 292 | for _,watcher in pairs(self.watchers) do 293 | util.ref(watcher) 294 | end 295 | end 296 | 297 | return self 298 | end 299 | 300 | local connect = function(...) 301 | local args = {...} 302 | local port 303 | local host 304 | local connectionListener 305 | if type(args[1]) == 'table' then 306 | local options = args[1] 307 | assert(options.port) 308 | port = options.port 309 | host = options.host 310 | connectionListener = args[2] 311 | else 312 | port = args[1] 313 | host = type(args[2]) == 'string' and args[2] 314 | connectionListener = (type(args[2]) == 'function' and args[2]) or (type(args[3]) == 'function' and args[3]) 315 | end 316 | local sock = new() 317 | if connectionListener then 318 | sock:once('connect',connectionListener) 319 | end 320 | sock:connect(port,host) 321 | return sock 322 | end 323 | 324 | return { 325 | new = new, 326 | Socket = new, 327 | connect = connect, 328 | createConnection = connect, 329 | isIP = isIP, 330 | isIPv4 = isIPv4, 331 | isIPv6 = isIPv6, 332 | } 333 | -------------------------------------------------------------------------------- /src/nodish/nexttick.lua: -------------------------------------------------------------------------------- 1 | local ev = require'ev' 2 | local tinsert = table.insert 3 | 4 | local pcallArray = function(arr) 5 | for _,f in ipairs(arr) do 6 | local ok,err = pcall(f) 7 | if not ok then 8 | print('process.nextTick callback failed',err) 9 | end 10 | end 11 | end 12 | 13 | local createNexttick = function(loop) 14 | if ev.Idle then 15 | local onIdle = {} 16 | local idleIo = ev.Idle.new( 17 | function(loop,idleIo) 18 | idleIo:stop(loop) 19 | pcallArray(onIdle) 20 | onIdle = {} 21 | end) 22 | return function(f) 23 | tinsert(onIdle,f) 24 | idleIo:start(loop) 25 | end 26 | else 27 | local eps = 2^-40 28 | local once 29 | local onTimeout = {} 30 | local timerIo = ev.Timer.new( 31 | function(loop,timerIo) 32 | once = true 33 | timerIo:stop(loop) 34 | pcallArray(onTimeout) 35 | onTimeout = {} 36 | end,eps,eps) 37 | return function(f) 38 | tinsert(onTimeout,f) 39 | if once then 40 | timerIo:again(loop) 41 | else 42 | timerIo:start(loop) 43 | end 44 | end 45 | end 46 | end 47 | 48 | return { 49 | nextTick = createNexttick(ev.Loop.default) 50 | } 51 | -------------------------------------------------------------------------------- /src/nodish/process.lua: -------------------------------------------------------------------------------- 1 | local ev = require'ev' 2 | local S = require'syscall' 3 | local events = require'nodish.events' 4 | local stream = require'nodish.stream' 5 | local buffer = require'nodish.buffer' 6 | local tinsert = table.insert 7 | 8 | local stdin = function() 9 | local self = events.EventEmitter() 10 | self.watchers = {} 11 | stream.readable(self) 12 | self:setEncoding('utf8') 13 | S.stdin:nonblock(true) 14 | local chunkSize = 4096*2 15 | local buf 16 | self._read = function() 17 | if not buf or not buf:isReleased() then 18 | buf = buffer.Buffer(chunkSize) 19 | end 20 | local ret,err = S.stdin:read(buf.buf,chunkSize) 21 | if ret then 22 | if ret > 0 then 23 | buf:_setLength(ret) 24 | assert(buf.length == ret) 25 | data = buf 26 | return data,err 27 | elseif ret == 0 then 28 | return nil,nil,true 29 | end 30 | end 31 | return nil,err 32 | end 33 | self:addReadWatcher(S.stdin:getfd()) 34 | return self 35 | end 36 | 37 | local stdout = function() 38 | local self = events.EventEmitter() 39 | self.watchers = {} 40 | stream.writable(self) 41 | S.stdout:nonblock(true) 42 | self._write = function(_,data) 43 | return S.stdout:write(data) 44 | end 45 | self:addWriteWatcher(S.stdout:getfd()) 46 | return self 47 | end 48 | 49 | local stderr = function() 50 | local self = events.EventEmitter() 51 | self.watchers = {} 52 | stream.writable(self) 53 | S.stderr:nonblock(true) 54 | self._write = function(_,data) 55 | return S.stderr:write(data) 56 | end 57 | self:addWriteWatcher(S.stderr:getfd()) 58 | return self 59 | end 60 | 61 | local unloop = function() 62 | print('quitting') 63 | ev.Loop.default:unloop() 64 | end 65 | 66 | local loop = function() 67 | local sigkill = 9 68 | local sigint = 2 69 | local sigquit = 3 70 | local sighup = 1 71 | for _,sig in ipairs({sigkill,sigint,sigquit,sighup}) do 72 | ev.Signal.new( 73 | unloop, 74 | sig):start(ev.Loop.default,true) 75 | end 76 | 77 | local sigpipe = 13 78 | ev.Signal.new( 79 | function() 80 | print('SIGPIPE ignored') 81 | end, 82 | sigpipe):start(ev.Loop.default,true) 83 | 84 | ev.Loop.default:loop() 85 | end 86 | 87 | return { 88 | nextTick = require'nodish.nexttick'.nextTick, 89 | stdin = stdin(), 90 | stdout = stdout(), 91 | stderr = stderr(), 92 | loop = loop, 93 | unloop = unloop, 94 | } 95 | -------------------------------------------------------------------------------- /src/nodish/stream.lua: -------------------------------------------------------------------------------- 1 | local ev = require'ev' 2 | local S = require'syscall' 3 | local loop = ev.Loop.default 4 | 5 | local EAGAIN = S.c.E.AGAIN 6 | 7 | local nextTick = require'nodish.nexttick'.nextTick 8 | local buffer = require'nodish.buffer' 9 | 10 | local readable = function(emitter) 11 | local self = emitter 12 | self.bytesRead = 0 13 | assert(self.watchers) 14 | local encoding 15 | 16 | self.setEncoding = function(_,enc) 17 | if not enc then 18 | encoding = nil 19 | elseif enc:lower() == 'utf8' or enc:lower() == 'utf-8' then 20 | encoding = 'utf8' 21 | else 22 | error('encoding not supported '..encoding) 23 | end 24 | end 25 | 26 | self.addReadWatcher = function(_,fd) 27 | assert(self._read) 28 | if self.watchers.read then 29 | return 30 | end 31 | local watchers = self.watchers 32 | watchers.read = ev.IO.new(function(loop,io) 33 | self:emit('readable') 34 | repeat 35 | local buf,err,fin = self:_read() 36 | if buf then 37 | assert(buf.length > 0) 38 | self.bytesRead = self.bytesRead + buf.length 39 | if watchers.timer then 40 | watchers.timer:again(loop) 41 | end 42 | local data = buf 43 | if encoding then 44 | assert(encoding == 'utf8') 45 | data = buf:toString() 46 | end 47 | self:emit('data',data) 48 | elseif fin then 49 | self:emit('fin') 50 | io:stop(loop) 51 | return 52 | elseif err and err.errno ~= EAGAIN then 53 | io:stop(loop) 54 | self:emit('error',err) 55 | err = nil 56 | end 57 | until err 58 | end,fd,ev.READ) 59 | end 60 | 61 | self.pause = function() 62 | self.watchers.read:stop(loop) 63 | end 64 | 65 | local mightHaveData 66 | 67 | self.resume = function() 68 | if not mightHaveData then 69 | nextTick(function() 70 | if self.watchers.read and not self.watchers.read:is_pending() then 71 | self.watchers.read:callback()(loop,self.watchers.read) 72 | end 73 | end) 74 | mightHaveData = false 75 | end 76 | self.watchers.read:start(loop) 77 | end 78 | 79 | local piped = {} 80 | 81 | local removePipeCallbacks = function(callbacks) 82 | self:removeListener('data',callbacks.forwardData) 83 | if callbacks.fowardFin then 84 | self:removeListener('',callbacks.forwardFin) 85 | end 86 | end 87 | 88 | self.pipe = function(_,writable,options) 89 | if piped[writable] then 90 | error('pipe to writable already open') 91 | end 92 | local callbacks = {} 93 | piped[writable] = callbacks 94 | callbacks.forwardData = function(data) 95 | writable:write(data) 96 | end 97 | self:on('data',callbacks.forwardData) 98 | if options and options.fin then 99 | callbacks.forwardFin = function() 100 | writable:fin() 101 | end 102 | self:on('fin',callbacks.forwardFin) 103 | end 104 | callbacks.cleanup = function() 105 | removePipeCallbacks(callbacks) 106 | writable:removeListener('fin',callbacks.cleanup) 107 | end 108 | writable:once('fin',callbacks.cleanup) 109 | writable:emit('pipe') 110 | end 111 | 112 | self.unpipe = function(_,writable) 113 | if not piped[writable] then 114 | error('pipe to writable not open') 115 | end 116 | piped[writable].cleanup() 117 | piped[writable] = nil 118 | writable:emit('unpipe') 119 | end 120 | 121 | end 122 | 123 | local writable = function(emitter) 124 | local self = emitter 125 | self.bytesWritten = 0 126 | local pending 127 | local ended 128 | 129 | self.addWriteWatcher = function(_,fd) 130 | assert(self._write) 131 | if self.watchers.write then 132 | return 133 | end 134 | local pos = 1 135 | local left 136 | local watchers = self.watchers 137 | watchers.write = ev.IO.new(function(loop,io) 138 | local written,err = self:_write(pending:sub(pos)) 139 | if written > 0 then 140 | self.bytesWritten = self.bytesWritten + written 141 | pos = pos + written 142 | if pos > #pending then 143 | pos = 1 144 | pending = nil 145 | io:stop(loop) 146 | self:emit('drain') 147 | if ended then 148 | self:emit('finish') 149 | end 150 | end 151 | elseif err and err.errno ~= EAGAIN then 152 | io:stop(loop) 153 | self:emit('error',err) 154 | return 155 | end 156 | if watchers.timer then 157 | watchers.timer:again(loop) 158 | end 159 | end,fd,ev.WRITE) 160 | end 161 | 162 | 163 | --may be overwritten by 'subclass/implementors' 164 | -- save for usage in fin 165 | local write = function(_,data) 166 | if buffer.isBuffer(data) then 167 | data = data:toString() 168 | end 169 | if pending then 170 | pending = pending..data 171 | elseif ended then 172 | error('writable.fin has been called') 173 | else 174 | pending = data 175 | self.watchers.write:start(loop) 176 | end 177 | end 178 | 179 | self.write = write 180 | 181 | self.fin = function(_,data) 182 | if data then 183 | write(self,data) 184 | elseif not pending then 185 | nextTick(function() 186 | self:emit('finish') 187 | end) 188 | end 189 | ended = true 190 | end 191 | 192 | end 193 | 194 | return { 195 | readable = readable, 196 | writable = writable 197 | } 198 | --------------------------------------------------------------------------------