net.server_event: Fix to not call onconnect a second time after the SSL handshake...
[prosody.git] / net / server_event.lua
1 --[[
2
3
4                         server.lua based on lua/libevent by blastbeat
5
6                         notes:
7                         -- when using luaevent, never register 2 or more EV_READ at one socket, same for EV_WRITE
8                         -- you cant even register a new EV_READ/EV_WRITE callback inside another one
9                         -- never call eventcallback:close( ) from inside eventcallback
10                         -- to do some of the above, use timeout events or something what will called from outside
11                         -- dont let garbagecollect eventcallbacks, as long they are running
12                         -- when using luasec, there are 4 cases of timeout errors: wantread or wantwrite during reading or writing
13
14 --]]
15
16 local SCRIPT_NAME           = "server_event.lua"
17 local SCRIPT_VERSION        = "0.05"
18 local SCRIPT_AUTHOR         = "blastbeat"
19 local LAST_MODIFIED         = "2009/11/20"
20
21 local cfg = {
22         MAX_CONNECTIONS       = 100000,  -- max per server connections (use "ulimit -n" on *nix)
23         MAX_HANDSHAKE_ATTEMPTS= 1000,  -- attempts to finish ssl handshake
24         HANDSHAKE_TIMEOUT     = 60,  -- timeout in seconds per handshake attempt
25         MAX_READ_LENGTH       = 1024 * 1024 * 1024 * 1024,  -- max bytes allowed to read from sockets
26         MAX_SEND_LENGTH       = 1024 * 1024 * 1024 * 1024,  -- max bytes size of write buffer (for writing on sockets)
27         ACCEPT_DELAY          = 10,  -- seconds to wait until the next attempt of a full server to accept
28         READ_TIMEOUT          = 60 * 60 * 6,  -- timeout in seconds for read data from socket
29         WRITE_TIMEOUT         = 180,  -- timeout in seconds for write data on socket
30         CONNECT_TIMEOUT       = 20,  -- timeout in seconds for connection attempts
31         CLEAR_DELAY           = 5,  -- seconds to wait for clearing interface list (and calling ondisconnect listeners)
32         DEBUG                 = true,  -- show debug messages
33 }
34
35 local function use(x) return rawget(_G, x); end
36 local print = use "print"
37 local pcall = use "pcall"
38 local ipairs = use "ipairs"
39 local string = use "string"
40 local select = use "select"
41 local require = use "require"
42 local tostring = use "tostring"
43 local coroutine = use "coroutine"
44 local setmetatable = use "setmetatable"
45
46 local ssl = use "ssl"
47 local socket = use "socket" or require "socket"
48
49 local log = require ("util.logger").init("socket")
50
51 local function debug(...)
52         return log("debug", ("%s "):rep(select('#', ...)), ...)
53 end
54 local vdebug = debug;
55
56 local bitor = ( function( ) -- thx Rici Lake
57         local hasbit = function( x, p )
58                 return x % ( p + p ) >= p
59         end
60         return function( x, y )
61                 local p = 1
62                 local z = 0
63                 local limit = x > y and x or y
64                 while p <= limit do
65                         if hasbit( x, p ) or hasbit( y, p ) then
66                                 z = z + p
67                         end
68                         p = p + p
69                 end
70                 return z
71         end
72 end )( )
73
74 local event = require "luaevent.core"
75 local base = event.new( )
76 local EV_READ = event.EV_READ
77 local EV_WRITE = event.EV_WRITE
78 local EV_TIMEOUT = event.EV_TIMEOUT
79 local EV_SIGNAL = event.EV_SIGNAL
80
81 local EV_READWRITE = bitor( EV_READ, EV_WRITE )
82
83 local interfacelist = ( function( )  -- holds the interfaces for sockets
84         local array = { }
85         local len = 0
86         return function( method, arg )
87                 if "add" == method then
88                         len = len + 1
89                         array[ len ] = arg
90                         arg:_position( len )
91                         return len
92                 elseif "delete" == method then
93                         if len <= 0 then
94                                 return nil, "array is already empty"
95                         end
96                         local position = arg:_position()  -- get position in array
97                         if position ~= len then
98                                 local interface = array[ len ]  -- get last interface
99                                 array[ position ] = interface  -- copy it into free position
100                                 array[ len ] = nil  -- free last position
101                                 interface:_position( position )  -- set new position in array
102                         else  -- free last position
103                                 array[ len ] = nil
104                         end
105                         len = len - 1
106                         return len
107                 else
108                         return array
109                 end
110         end
111 end )( )
112
113 -- Client interface methods
114 local interface_mt
115 do
116         interface_mt = {}; interface_mt.__index = interface_mt;
117         
118         local addevent = base.addevent
119         local coroutine_wrap, coroutine_yield = coroutine.wrap,coroutine.yield
120         local string_len = string.len
121         
122         -- Private methods
123         function interface_mt:_position(new_position)
124                         self.position = new_position or self.position
125                         return self.position;
126         end
127         function interface_mt:_close() -- regs event to start self:_destroy()
128                         local callback = function( )
129                                 self:_destroy();
130                                 self.eventclose = nil
131                                 return -1
132                         end
133                         self.eventclose = addevent( base, nil, EV_TIMEOUT, callback, 0 )
134                         return true
135         end
136         
137         function interface_mt:_start_connection(plainssl) -- should be called from addclient
138                         local callback = function( event )
139                                 if EV_TIMEOUT == event then  -- timeout during connection
140                                         self.fatalerror = "connection timeout"
141                                         self:ontimeout()  -- call timeout listener
142                                         self:_close()
143                                         debug( "new connection failed. id:", self.id, "error:", self.fatalerror )
144                                 else
145                                         if plainssl and ssl then  -- start ssl session
146                                                 self:starttls(nil, true)
147                                         else  -- normal connection
148                                                 self:_start_session(true)
149                                         end
150                                         debug( "new connection established. id:", self.id )
151                                 end
152                                 self.eventconnect = nil
153                                 return -1
154                         end
155                         self.eventconnect = addevent( base, self.conn, EV_WRITE, callback, cfg.CONNECT_TIMEOUT )
156                         return true
157         end
158         function interface_mt:_start_session(call_onconnect) -- new session, for example after startssl
159                 if self.type == "client" then
160                         local callback = function( )
161                                 self:_lock( false,  false, false )
162                                 --vdebug( "start listening on client socket with id:", self.id )
163                                 self.eventread = addevent( base, self.conn, EV_READ, self.readcallback, cfg.READ_TIMEOUT );  -- register callback
164                                 if call_onconnect then
165                                         debug("CALLING ONCONNECT")
166                                         self:onconnect()
167                                 else
168                                         debug("NOT CALLING ONCONNECT");
169                                 end
170                                 self.eventsession = nil
171                                 return -1
172                         end
173                         self.eventsession = addevent( base, nil, EV_TIMEOUT, callback, 0 )
174                 else
175                         self:_lock( false )
176                         --vdebug( "start listening on server socket with id:", self.id )
177                         self.eventread = addevent( base, self.conn, EV_READ, self.readcallback )  -- register callback
178                 end
179                 return true
180         end
181         function interface_mt:_start_ssl(call_onconnect) -- old socket will be destroyed, therefore we have to close read/write events first
182                         --vdebug( "starting ssl session with client id:", self.id )
183                         local _
184                         _ = self.eventread and self.eventread:close( )  -- close events; this must be called outside of the event callbacks!
185                         _ = self.eventwrite and self.eventwrite:close( )
186                         self.eventread, self.eventwrite = nil, nil
187                         local err
188                         self.conn, err = ssl.wrap( self.conn, self._sslctx )
189                         if err then
190                                 self.fatalerror = err
191                                 self.conn = nil  -- cannot be used anymore
192                                 if call_onconnect then
193                                         self.ondisconnect = nil  -- dont call this when client isnt really connected
194                                 end
195                                 self:_close()
196                                 debug( "fatal error while ssl wrapping:", err )
197                                 return false
198                         end
199                         self.conn:settimeout( 0 )  -- set non blocking
200                         local handshakecallback = coroutine_wrap(
201                                 function( event )
202                                         local _, err
203                                         local attempt = 0
204                                         local maxattempt = cfg.MAX_HANDSHAKE_ATTEMPTS
205                                         while attempt < maxattempt do  -- no endless loop
206                                                 attempt = attempt + 1
207                                                 debug( "ssl handshake of client with id:"..tostring(self)..", attempt:"..attempt )
208                                                 if attempt > maxattempt then
209                                                         self.fatalerror = "max handshake attempts exceeded"
210                                                 elseif EV_TIMEOUT == event then
211                                                         self.fatalerror = "timeout during handshake"
212                                                 else
213                                                         _, err = self.conn:dohandshake( )
214                                                         if not err then
215                                                                 self:_lock( false, false, false )  -- unlock the interface; sending, closing etc allowed
216                                                                 self.send = self.conn.send  -- caching table lookups with new client object
217                                                                 self.receive = self.conn.receive
218                                                                 local onsomething
219                                                                 if not call_onconnect then  -- trigger listener
220                                                                         self:onstatus("ssl-handshake-complete");
221                                                                 end
222                                                                 self:_start_session( call_onconnect )
223                                                                 debug( "ssl handshake done" )
224                                                                 self.eventhandshake = nil
225                                                                 return -1
226                                                         end
227                                                         debug( "error during ssl handshake:", err )
228                                                         if err == "wantwrite" then
229                                                                 event = EV_WRITE
230                                                         elseif err == "wantread" then
231                                                                 event = EV_READ
232                                                         else
233                                                                 self.fatalerror = err
234                                                         end
235                                                 end
236                                                 if self.fatalerror then
237                                                         if call_onconnect then
238                                                                 self.ondisconnect = nil  -- dont call this when client isnt really connected
239                                                         end
240                                                         self:_close()
241                                                         debug( "handshake failed because:", self.fatalerror )
242                                                         self.eventhandshake = nil
243                                                         return -1
244                                                 end
245                                                 event = coroutine_yield( event, cfg.HANDSHAKE_TIMEOUT )  -- yield this monster...
246                                         end
247                                 end
248                         )
249                         debug "starting handshake..."
250                         self:_lock( false, true, true )  -- unlock read/write events, but keep interface locked
251                         self.eventhandshake = addevent( base, self.conn, EV_READWRITE, handshakecallback, cfg.HANDSHAKE_TIMEOUT )
252                         return true
253         end
254         function interface_mt:_destroy()  -- close this interface + events and call last listener
255                         debug( "closing client with id:", self.id )
256                         self:_lock( true, true, true )  -- first of all, lock the interface to avoid further actions
257                         local _
258                         _ = self.eventread and self.eventread:close( )  -- close events; this must be called outside of the event callbacks!
259                         if self.type == "client" then
260                                 _ = self.eventwrite and self.eventwrite:close( )
261                                 _ = self.eventhandshake and self.eventhandshake:close( )
262                                 _ = self.eventstarthandshake and self.eventstarthandshake:close( )
263                                 _ = self.eventconnect and self.eventconnect:close( )
264                                 _ = self.eventsession and self.eventsession:close( )
265                                 _ = self.eventwritetimeout and self.eventwritetimeout:close( )
266                                 _ = self.eventreadtimeout and self.eventreadtimeout:close( )
267                                 _ = self.ondisconnect and self:ondisconnect( self.fatalerror ~= "client to close" and self.fatalerror)  -- call ondisconnect listener (wont be the case if handshake failed on connect)
268                                 _ = self.conn and self.conn:close( ) -- close connection, must also be called outside of any socket registered events!
269                                 _ = self._server and self._server:counter(-1);
270                                 self.eventread, self.eventwrite = nil, nil
271                                 self.eventstarthandshake, self.eventhandshake, self.eventclose = nil, nil, nil
272                                 self.readcallback, self.writecallback = nil, nil
273                         else
274                                 self.conn:close( )
275                                 self.eventread, self.eventclose = nil, nil
276                                 self.interface, self.readcallback = nil, nil
277                         end
278                         interfacelist( "delete", self )
279                         return true
280         end
281         
282         function interface_mt:_lock(nointerface, noreading, nowriting)  -- lock or unlock this interface or events
283                         self.nointerface, self.noreading, self.nowriting = nointerface, noreading, nowriting
284                         return nointerface, noreading, nowriting
285         end
286         
287         --TODO: Deprecate
288         function interface_mt:lock_read(switch)
289                 if switch then
290                         return self:pause();
291                 else
292                         return self:resume();
293                 end
294         end
295
296         function interface_mt:pause()
297                 return self:_lock(self.nointerface, true, self.nowriting);
298         end
299
300         function interface_mt:resume()
301                 return self:_lock(self.nointerface, false, self.nowriting);
302         end
303
304         function interface_mt:counter(c)
305                 if c then
306                         self._connections = self._connections + c
307                 end
308                 return self._connections
309         end
310         
311         -- Public methods
312         function interface_mt:write(data)
313                 if self.nowriting then return nil, "locked" end
314                 --vdebug( "try to send data to client, id/data:", self.id, data )
315                 data = tostring( data )
316                 local len = string_len( data )
317                 local total = len + self.writebufferlen
318                 if total > cfg.MAX_SEND_LENGTH then  -- check buffer length
319                         local err = "send buffer exceeded"
320                         debug( "error:", err )  -- to much, check your app
321                         return nil, err
322                 end
323                 self.writebuffer = self.writebuffer .. data -- new buffer
324                 self.writebufferlen = total
325                 if not self.eventwrite then  -- register new write event
326                         --vdebug( "register new write event" )
327                         self.eventwrite = addevent( base, self.conn, EV_WRITE, self.writecallback, cfg.WRITE_TIMEOUT )
328                 end
329                 return true
330         end
331         function interface_mt:close(now)
332                 if self.nointerface then return nil, "locked"; end
333                 debug( "try to close client connection with id:", self.id )
334                 if self.type == "client" then
335                         self.fatalerror = "client to close"
336                         if ( not self.eventwrite ) or now then  -- try to close immediately
337                                 self:_lock( true, true, true )
338                                 self:_close()
339                                 return true
340                         else  -- wait for incomplete write request
341                                 self:_lock( true, true, false )
342                                 debug "closing delayed until writebuffer is empty"
343                                 return nil, "writebuffer not empty, waiting"
344                         end
345                 else
346                         debug( "try to close server with id:", self.id, "args:", now )
347                         self.fatalerror = "server to close"
348                         self:_lock( true )
349                         local count = 0
350                         for _, item in ipairs( interfacelist( ) ) do
351                                 if ( item.type ~= "server" ) and ( item._server == self ) then  -- client/server match
352                                         if item:close( now ) then  -- writebuffer was empty
353                                                 count = count + 1
354                                         end
355                                 end
356                         end
357                         local timeout = 0  -- dont wait for unfinished writebuffers of clients...
358                         if not now then
359                                 timeout = cfg.WRITE_TIMEOUT  -- ...or wait for it
360                         end
361                         self:_close( timeout )  -- add new event to remove the server interface
362                         debug( "seconds remained until server is closed:", timeout )
363                         return count  -- returns finished clients with empty writebuffer
364                 end
365         end
366         
367         function interface_mt:server()
368                 return self._server or self;
369         end
370         
371         function interface_mt:port()
372                 return self._port
373         end
374         
375         function interface_mt:serverport()
376                 return self._serverport
377         end
378         
379         function interface_mt:ip()
380                 return self._ip
381         end
382         
383         function interface_mt:ssl()
384                 return self._usingssl
385         end
386
387         function interface_mt:type()
388                 return self._type or "client"
389         end
390         
391         function interface_mt:connections()
392                 return self._connections
393         end
394         
395         function interface_mt:address()
396                 return self.addr
397         end
398         
399         function interface_mt:set_sslctx(sslctx)
400                 self._sslctx = sslctx;
401                 if sslctx then
402                         self.starttls = nil; -- use starttls() of interface_mt
403                 else
404                         self.starttls = false; -- prevent starttls()
405                 end
406         end
407
408         function interface_mt:set_mode(pattern)
409                 if pattern then
410                         self._pattern = pattern;
411                 end
412                 return self._pattern;
413         end
414         
415         function interface_mt:set_send(new_send)
416                 -- No-op, we always use the underlying connection's send
417         end
418         
419         function interface_mt:starttls(sslctx, call_onconnect)
420                 debug( "try to start ssl at client id:", self.id )
421                 local err
422                 self._sslctx = sslctx;
423                 if self._usingssl then  -- startssl was already called
424                         err = "ssl already active"
425                 end
426                 if err then
427                         debug( "error:", err )
428                         return nil, err
429                 end
430                 self._usingssl = true
431                 self.startsslcallback = function( )  -- we have to start the handshake outside of a read/write event
432                         self.startsslcallback = nil
433                         self:_start_ssl(call_onconnect);
434                         self.eventstarthandshake = nil
435                         return -1
436                 end
437                 if not self.eventwrite then
438                         self:_lock( true, true, true )  -- lock the interface, to not disturb the handshake
439                         self.eventstarthandshake = addevent( base, nil, EV_TIMEOUT, self.startsslcallback, 0 )  -- add event to start handshake
440                 else  -- wait until writebuffer is empty
441                         self:_lock( true, true, false )
442                         debug "ssl session delayed until writebuffer is empty..."
443                 end
444                 self.starttls = false;
445                 return true
446         end
447         
448         function interface_mt:setoption(option, value)
449                 if self.conn.setoption then
450                         return self.conn:setoption(option, value);
451                 end
452                 return false, "setoption not implemented";
453         end
454         
455         function interface_mt:setlistener(listener)
456                 self.onconnect, self.ondisconnect, self.onincoming, self.ontimeout, self.onstatus
457                         = listener.onconnect, listener.ondisconnect, listener.onincoming, listener.ontimeout, listener.onstatus;
458         end
459         
460         -- Stub handlers
461         function interface_mt:onconnect()
462                 return self:onincoming(nil);
463         end
464         function interface_mt:onincoming()
465         end
466         function interface_mt:ondisconnect()
467         end
468         function interface_mt:ontimeout()
469         end
470         function interface_mt:ondrain()
471         end
472         function interface_mt:onstatus()
473         end
474 end
475
476 -- End of client interface methods
477
478 local handleclient;
479 do
480         local string_sub = string.sub  -- caching table lookups
481         local string_len = string.len
482         local addevent = base.addevent
483         local coroutine_wrap = coroutine.wrap
484         local socket_gettime = socket.gettime
485         local coroutine_yield = coroutine.yield
486         function handleclient( client, ip, port, server, pattern, listener, _, sslctx )  -- creates an client interface
487                 --vdebug("creating client interfacce...")
488                 local interface = {
489                         type = "client";
490                         conn = client;
491                         currenttime = socket_gettime( );  -- safe the origin
492                         writebuffer = "";  -- writebuffer
493                         writebufferlen = 0;  -- length of writebuffer
494                         send = client.send;  -- caching table lookups
495                         receive = client.receive;
496                         onconnect = listener.onconnect;  -- will be called when client disconnects
497                         ondisconnect = listener.ondisconnect;  -- will be called when client disconnects
498                         onincoming = listener.onincoming;  -- will be called when client sends data
499                         ontimeout = listener.ontimeout; -- called when fatal socket timeout occurs
500                         onstatus = listener.onstatus; -- called for status changes (e.g. of SSL/TLS)
501                         eventread = false, eventwrite = false, eventclose = false,
502                         eventhandshake = false, eventstarthandshake = false;  -- event handler
503                         eventconnect = false, eventsession = false;  -- more event handler...
504                         eventwritetimeout = false;  -- even more event handler...
505                         eventreadtimeout = false;
506                         fatalerror = false;  -- error message
507                         writecallback = false;  -- will be called on write events
508                         readcallback = false;  -- will be called on read events
509                         nointerface = true;  -- lock/unlock parameter of this interface
510                         noreading = false, nowriting = false;  -- locks of the read/writecallback
511                         startsslcallback = false;  -- starting handshake callback
512                         position = false;  -- position of client in interfacelist
513                         
514                         -- Properties
515                         _ip = ip, _port = port, _server = server, _pattern = pattern,
516                         _serverport = (server and server:port() or nil),
517                         _sslctx = sslctx; -- parameters
518                         _usingssl = false;  -- client is using ssl;
519                 }
520                 if not ssl then interface.starttls = false; end
521                 interface.id = tostring(interface):match("%x+$");
522                 interface.writecallback = function( event )  -- called on write events
523                         --vdebug( "new client write event, id/ip/port:", interface, ip, port )
524                         if interface.nowriting or ( interface.fatalerror and ( "client to close" ~= interface.fatalerror ) ) then  -- leave this event
525                                 --vdebug( "leaving this event because:", interface.nowriting or interface.fatalerror )
526                                 interface.eventwrite = false
527                                 return -1
528                         end
529                         if EV_TIMEOUT == event then  -- took too long to write some data to socket -> disconnect
530                                 interface.fatalerror = "timeout during writing"
531                                 debug( "writing failed:", interface.fatalerror )
532                                 interface:_close()
533                                 interface.eventwrite = false
534                                 return -1
535                         else  -- can write :)
536                                 if interface._usingssl then  -- handle luasec
537                                         if interface.eventreadtimeout then  -- we have to read first
538                                                 local ret = interface.readcallback( )  -- call readcallback
539                                                 --vdebug( "tried to read in writecallback, result:", ret )
540                                         end
541                                         if interface.eventwritetimeout then  -- luasec only
542                                                 interface.eventwritetimeout:close( )  -- first we have to close timeout event which where regged after a wantread error
543                                                 interface.eventwritetimeout = false
544                                         end
545                                 end
546                                 local succ, err, byte = interface.conn:send( interface.writebuffer, 1, interface.writebufferlen )
547                                 --vdebug( "write data:", interface.writebuffer, "error:", err, "part:", byte )
548                                 if succ then  -- writing succesful
549                                         interface.writebuffer = ""
550                                         interface.writebufferlen = 0
551                                         interface:ondrain();
552                                         if interface.fatalerror then
553                                                 debug "closing client after writing"
554                                                 interface:_close()  -- close interface if needed
555                                         elseif interface.startsslcallback then  -- start ssl connection if needed
556                                                 debug "starting ssl handshake after writing"
557                                                 interface.eventstarthandshake = addevent( base, nil, EV_TIMEOUT, interface.startsslcallback, 0 )
558                                         elseif interface.eventreadtimeout then
559                                                 return EV_WRITE, EV_TIMEOUT
560                                         end
561                                         interface.eventwrite = nil
562                                         return -1
563                                 elseif byte and (err == "timeout" or err == "wantwrite") then  -- want write again
564                                         --vdebug( "writebuffer is not empty:", err )
565                                         interface.writebuffer = string_sub( interface.writebuffer, byte + 1, interface.writebufferlen )  -- new buffer
566                                         interface.writebufferlen = interface.writebufferlen - byte
567                                         if "wantread" == err then  -- happens only with luasec
568                                                 local callback = function( )
569                                                         interface:_close()
570                                                         interface.eventwritetimeout = nil
571                                                         return -1;
572                                                 end
573                                                 interface.eventwritetimeout = addevent( base, nil, EV_TIMEOUT, callback, cfg.WRITE_TIMEOUT )  -- reg a new timeout event
574                                                 debug( "wantread during write attempt, reg it in readcallback but dont know what really happens next..." )
575                                                 -- hopefully this works with luasec; its simply not possible to use 2 different write events on a socket in luaevent
576                                                 return -1
577                                         end
578                                         return EV_WRITE, cfg.WRITE_TIMEOUT
579                                 else  -- connection was closed during writing or fatal error
580                                         interface.fatalerror = err or "fatal error"
581                                         debug( "connection failed in write event:", interface.fatalerror )
582                                         interface:_close()
583                                         interface.eventwrite = nil
584                                         return -1
585                                 end
586                         end
587                 end
588                 
589                 interface.readcallback = function( event )  -- called on read events
590                         --vdebug( "new client read event, id/ip/port:", tostring(interface.id), tostring(ip), tostring(port) )
591                         if interface.noreading or interface.fatalerror then  -- leave this event
592                                 --vdebug( "leaving this event because:", tostring(interface.noreading or interface.fatalerror) )
593                                 interface.eventread = nil
594                                 return -1
595                         end
596                         if EV_TIMEOUT == event then  -- took too long to get some data from client -> disconnect
597                                 interface.fatalerror = "timeout during receiving"
598                                 debug( "connection failed:", interface.fatalerror )
599                                 interface:_close()
600                                 interface.eventread = nil
601                                 return -1
602                         else -- can read
603                                 if interface._usingssl then  -- handle luasec
604                                         if interface.eventwritetimeout then  -- ok, in the past writecallback was regged
605                                                 local ret = interface.writecallback( )  -- call it
606                                                 --vdebug( "tried to write in readcallback, result:", tostring(ret) )
607                                         end
608                                         if interface.eventreadtimeout then
609                                                 interface.eventreadtimeout:close( )
610                                                 interface.eventreadtimeout = nil
611                                         end
612                                 end
613                                 local buffer, err, part = interface.conn:receive( interface._pattern )  -- receive buffer with "pattern"
614                                 --vdebug( "read data:", tostring(buffer), "error:", tostring(err), "part:", tostring(part) )
615                                 buffer = buffer or part or ""
616                                 local len = string_len( buffer )
617                                 if len > cfg.MAX_READ_LENGTH then  -- check buffer length
618                                         interface.fatalerror = "receive buffer exceeded"
619                                         debug( "fatal error:", interface.fatalerror )
620                                         interface:_close()
621                                         interface.eventread = nil
622                                         return -1
623                                 end
624                                 interface.onincoming( interface, buffer, err )  -- send new data to listener
625                                 if err and ( err ~= "timeout" and err ~= "wantread" ) then
626                                         if "wantwrite" == err then -- need to read on write event
627                                                 if not interface.eventwrite then  -- register new write event if needed
628                                                         interface.eventwrite = addevent( base, interface.conn, EV_WRITE, interface.writecallback, cfg.WRITE_TIMEOUT )
629                                                 end
630                                                 interface.eventreadtimeout = addevent( base, nil, EV_TIMEOUT,
631                                                         function( )
632                                                                 interface:_close()
633                                                         end, cfg.READ_TIMEOUT
634                                                 )
635                                                 debug( "wantwrite during read attempt, reg it in writecallback but dont know what really happens next..." )
636                                                 -- to be honest i dont know what happens next, if it is allowed to first read, the write etc...
637                                         else  -- connection was closed or fatal error
638                                                 interface.fatalerror = err
639                                                 debug( "connection failed in read event:", interface.fatalerror )
640                                                 interface:_close()
641                                                 interface.eventread = nil
642                                                 return -1
643                                         end
644                                 end
645                                 return EV_READ, cfg.READ_TIMEOUT
646                         end
647                 end
648
649                 client:settimeout( 0 )  -- set non blocking
650                 setmetatable(interface, interface_mt)
651                 interfacelist( "add", interface )  -- add to interfacelist
652                 return interface
653         end
654 end
655
656 local handleserver
657 do
658         function handleserver( server, addr, port, pattern, listener, sslctx )  -- creates an server interface
659                 debug "creating server interface..."
660                 local interface = {
661                         _connections = 0;
662                         
663                         conn = server;
664                         onconnect = listener.onconnect;  -- will be called when new client connected
665                         eventread = false;  -- read event handler
666                         eventclose = false; -- close event handler
667                         readcallback = false; -- read event callback
668                         fatalerror = false; -- error message
669                         nointerface = true;  -- lock/unlock parameter
670                         
671                         _ip = addr, _port = port, _pattern = pattern,
672                         _sslctx = sslctx;
673                 }
674                 interface.id = tostring(interface):match("%x+$");
675                 interface.readcallback = function( event )  -- server handler, called on incoming connections
676                         --vdebug( "server can accept, id/addr/port:", interface, addr, port )
677                         if interface.fatalerror then
678                                 --vdebug( "leaving this event because:", self.fatalerror )
679                                 interface.eventread = nil
680                                 return -1
681                         end
682                         local delay = cfg.ACCEPT_DELAY
683                         if EV_TIMEOUT == event then
684                                 if interface._connections >= cfg.MAX_CONNECTIONS then  -- check connection count
685                                         debug( "to many connections, seconds to wait for next accept:", delay )
686                                         return EV_TIMEOUT, delay  -- timeout...
687                                 else
688                                         return EV_READ  -- accept again
689                                 end
690                         end
691                         --vdebug("max connection check ok, accepting...")
692                         local client, err = server:accept()    -- try to accept; TODO: check err
693                         while client do
694                                 if interface._connections >= cfg.MAX_CONNECTIONS then
695                                         client:close( )  -- refuse connection
696                                         debug( "maximal connections reached, refuse client connection; accept delay:", delay )
697                                         return EV_TIMEOUT, delay  -- delay for next accept attempt
698                                 end
699                                 local client_ip, client_port = client:getpeername( )
700                                 interface._connections = interface._connections + 1  -- increase connection count
701                                 local clientinterface = handleclient( client, client_ip, client_port, interface, pattern, listener, nil, sslctx )
702                                 --vdebug( "client id:", clientinterface, "startssl:", startssl )
703                                 if ssl and sslctx then
704                                         clientinterface:starttls(sslctx, true)
705                                 else
706                                         clientinterface:_start_session( true )
707                                 end
708                                 debug( "accepted incoming client connection from:", client_ip or "<unknown IP>", client_port or "<unknown port>", "to", port or "<unknown port>");
709                                 
710                                 client, err = server:accept()    -- try to accept again
711                         end
712                         return EV_READ
713                 end
714                 
715                 server:settimeout( 0 )
716                 setmetatable(interface, interface_mt)
717                 interfacelist( "add", interface )
718                 interface:_start_session()
719                 return interface
720         end
721 end
722
723 local addserver = ( function( )
724         return function( addr, port, listener, pattern, sslcfg, startssl )  -- TODO: check arguments
725                 --vdebug( "creating new tcp server with following parameters:", addr or "nil", port or "nil", sslcfg or "nil", startssl or "nil")
726                 local server, err = socket.bind( addr, port, cfg.ACCEPT_QUEUE )  -- create server socket
727                 if not server then
728                         debug( "creating server socket failed because:", err )
729                         return nil, err
730                 end
731                 local sslctx
732                 if sslcfg then
733                         if not ssl then
734                                 debug "fatal error: luasec not found"
735                                 return nil, "luasec not found"
736                         end
737                         sslctx, err = sslcfg
738                         if err then
739                                 debug( "error while creating new ssl context for server socket:", err )
740                                 return nil, err
741                         end
742                 end
743                 local interface = handleserver( server, addr, port, pattern, listener, sslctx, startssl )  -- new server handler
744                 debug( "new server created with id:", tostring(interface))
745                 return interface
746         end
747 end )( )
748
749 local addclient, wrapclient
750 do
751         function wrapclient( client, ip, port, listeners, pattern, sslctx, startssl )
752                 local interface = handleclient( client, ip, port, nil, pattern, listeners, sslctx )
753                 interface:_start_session()
754                 return interface, client
755                 --function handleclient( client, ip, port, server, pattern, listener, _, sslctx )  -- creates an client interface
756         end
757         
758         function addclient( addr, serverport, listener, pattern, localaddr, localport, sslcfg, startssl )
759                 local client, err = socket.tcp()  -- creating new socket
760                 if not client then
761                         debug( "cannot create socket:", err )
762                         return nil, err
763                 end
764                 client:settimeout( 0 )  -- set nonblocking
765                 if localaddr then
766                         local res, err = client:bind( localaddr, localport, -1 )
767                         if not res then
768                                 debug( "cannot bind client:", err )
769                                 return nil, err
770                         end
771                 end
772                 local sslctx
773                 if sslcfg then  -- handle ssl/new context
774                         if not ssl then
775                                 debug "need luasec, but not available"
776                                 return nil, "luasec not found"
777                         end
778                         sslctx, err = sslcfg
779                         if err then
780                                 debug( "cannot create new ssl context:", err )
781                                 return nil, err
782                         end
783                 end
784                 local res, err = client:connect( addr, serverport )  -- connect
785                 if res or ( err == "timeout" ) then
786                         local ip, port = client:getsockname( )
787                         local server = function( )
788                                 return nil, "this is a dummy server interface"
789                         end
790                         local interface = wrapclient( client, ip, serverport, listener, pattern, sslctx, startssl )
791                         interface:_start_connection( startssl )
792                         debug( "new connection id:", interface.id )
793                         return interface, err
794                 else
795                         debug( "new connection failed:", err )
796                         return nil, err
797                 end
798         end
799 end
800
801
802 local loop = function( )  -- starts the event loop
803         base:loop( )
804         return "quitting";
805 end
806
807 local newevent = ( function( )
808         local add = base.addevent
809         return function( ... )
810                 return add( base, ... )
811         end
812 end )( )
813
814 local closeallservers = function( arg )
815         for _, item in ipairs( interfacelist( ) ) do
816                 if item.type == "server" then
817                         item:close( arg )
818                 end
819         end
820 end
821
822 local function setquitting(yes)
823         if yes then
824                  -- Quit now
825                  closeallservers();
826                  base:loopexit();
827         end
828 end
829
830 function get_backend()
831         return base:method();
832 end
833
834 -- We need to hold onto the events to stop them
835 -- being garbage-collected
836 local signal_events = {}; -- [signal_num] -> event object
837 function hook_signal(signal_num, handler)
838         local function _handler(event)
839                 local ret = handler();
840                 if ret ~= false then -- Continue handling this signal?
841                         return EV_SIGNAL; -- Yes
842                 end
843                 return -1; -- Close this event
844         end
845         signal_events[signal_num] = base:addevent(signal_num, EV_SIGNAL, _handler);
846         return signal_events[signal_num];
847 end
848
849 local function link(sender, receiver, buffersize)
850         sender:set_mode(buffersize);
851         local sender_locked;
852         
853         function receiver:ondrain()
854                 if sender_locked then
855                         sender:resume();
856                         sender_locked = nil;
857                 end
858         end
859         
860         function sender:onincoming(data)
861                 receiver:write(data);
862                 if receiver.writebufferlen >= buffersize then
863                         sender_locked = true;
864                         sender:pause();
865                 end
866         end
867 end
868
869 return {
870
871         cfg = cfg,
872         base = base,
873         loop = loop,
874         link = link,
875         event = event,
876         event_base = base,
877         addevent = newevent,
878         addserver = addserver,
879         addclient = addclient,
880         wrapclient = wrapclient,
881         setquitting = setquitting,
882         closeall = closeallservers,
883         get_backend = get_backend,
884         hook_signal = hook_signal,
885
886         __NAME = SCRIPT_NAME,
887         __DATE = LAST_MODIFIED,
888         __AUTHOR = SCRIPT_AUTHOR,
889         __VERSION = SCRIPT_VERSION,
890
891 }