GSoC: Documentation #1
[project/luci.git] / libs / lucid / luasrc / lucid / tcpserver.lua
1 --[[
2 LuCI - Lua Development Framework
3
4 Copyright 2009 Steven Barth <steven@midlink.org>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 $Id$
13 ]]
14
15 local os = require "os"
16 local fs = require "nixio.fs"
17 local nixio = require "nixio"
18 local lucid = require "luci.lucid"
19
20 local ipairs, type, require, setmetatable = ipairs, type, require, setmetatable
21 local pairs, print, tostring, unpack = pairs, print, tostring, unpack
22 local pcall = pcall
23
24 module "luci.lucid.tcpserver"
25
26 local cursor = lucid.cursor
27 local UCINAME = lucid.UCINAME
28
29 local tcpsockets = {}
30
31 --- Prepare a daemon and allocate its resources. (superserver callback)
32 -- @param config configuration table
33 -- @param server LuCId basemodule
34 -- @return binary data
35 function prepare_daemon(config, server)
36         nixio.syslog("info", "Preparing TCP-Daemon " .. config[".name"])
37         if type(config.address) ~= "table" then
38                 config.address = {config.address}
39         end
40         
41         local sockets, socket, code, err = {}
42         local sopts = {reuseaddr = 1}
43         for _, addr in ipairs(config.address) do
44                 local host, port = addr:match("(.-):?([^:]*)")
45                 if not host then
46                         nixio.syslog("err", "Invalid address: " .. addr)
47                         return nil, -5, "invalid address format"
48                 elseif #host == 0 then
49                         host = nil
50                 end
51                 socket, code, err = prepare_socket(config.family, host, port, sopts)
52                 if socket then
53                         sockets[#sockets+1] = socket
54                 end
55         end
56         
57         nixio.syslog("info", "Sockets bound for " .. config[".name"])
58         
59         if #sockets < 1 then
60                 return nil, -6, "no sockets bound"
61         end
62         
63         nixio.syslog("info", "Preparing publishers for " .. config[".name"])
64         
65         local publisher = {}
66         for k, pname in ipairs(config.publisher) do
67                 local pdata = cursor:get_all(UCINAME, pname)
68                 if pdata then
69                         publisher[#publisher+1] = pdata
70                 else
71                         nixio.syslog("err", "Publisher " .. pname .. " not found")
72                 end
73         end
74         
75         nixio.syslog("info", "Preparing TLS for " .. config[".name"])
76         
77         local tls = prepare_tls(config.tls)
78         if not tls and config.encryption == "enable" then
79                 for _, s in ipairs(sockets) do
80                         s:close()
81                 end
82                 return nil, -4, "Encryption requested, but no TLS context given"
83         end
84         
85         nixio.syslog("info", "Invoking daemon factory for " .. config[".name"])
86         local handler, err = config.slave.module.factory(publisher, config)
87         if not handler then
88                 for _, s in ipairs(sockets) do
89                         s:close()
90                 end
91                 return nil, -3, err
92         else
93                 local pollin = nixio.poll_flags("in")
94                 for _, s in ipairs(sockets) do
95                         server.register_pollfd({
96                                 fd = s,
97                                 events = pollin,
98                                 revents = 0,
99                                 handler = accept,
100                                 accept = handler,
101                                 config = config,
102                                 publisher = publisher,
103                                 tls = tls
104                         })
105                 end
106                 return true
107         end
108 end
109
110 --- Accept a new TCP connection. (server callback)
111 -- @param polle Poll descriptor
112 -- @return handler process id or nil, error code, error message 
113 function accept(polle)
114         local socket, host, port = polle.fd:accept()
115         if not socket then
116                 return nixio.syslog("warn", "accept() failed: " .. port)
117         end
118         
119         socket:setblocking(true)
120         
121         local function thread()
122                 lucid.close_pollfds()
123                 local inst = setmetatable({
124                         host = host, port = port, interfaces = lucid.get_interfaces() 
125                 }, {__index = polle})
126                 if polle.config.encryption then
127                         socket = polle.tls:create(socket)
128                         if not socket:accept() then
129                                 socket:close()
130                                 return nixio.syslog("warning", "TLS handshake failed: " .. host)
131                         end
132                 end
133                 
134                 return polle.accept(socket, inst)
135         end
136         
137         local stat = {lucid.create_process(thread)}
138         socket:close()
139         return unpack(stat)
140 end
141
142 --- Prepare a TCP server socket.
143 -- @param family protocol family ["inetany", "inet6", "inet"]
144 -- @param host host
145 -- @param port port
146 -- @param opts table of socket options
147 -- @param backlog socket backlog
148 -- @return socket, final socket family
149 function prepare_socket(family, host, port, opts, backlog)
150         nixio.syslog("info", "Preparing socket for port " .. port)
151         backlog = backlog or 1024
152         family = family or "inetany"
153         opts = opts or {}
154         
155         local inetany = family == "inetany"
156         family = inetany and "inet6" or family
157
158         local socket, code, err = nixio.socket(family, "stream")
159         if not socket and inetany then
160                 family = "inet"
161                 socket, code, err = nixio.socket(family, "stream")
162         end
163         
164         if not socket then
165                 return nil, code, err
166         end
167
168         for k, v in pairs(opts) do
169                 socket:setsockopt("socket", k, v)
170         end
171         
172         local stat, code, err = socket:bind(host, port)
173         if not stat then
174                 return nil, code, err
175         end
176         
177         stat, code, err = socket:listen(backlog)
178         if not stat then
179                 return nil, code, err
180         end
181         
182         socket:setblocking(false)
183
184         return socket, family
185 end
186
187 --- Prepare a TLS server context and load keys and certificates.
188 -- May invoke px5g to create keys and certificate on demand if available.
189 -- @param tlskey TLS configuration identifier
190 -- @return TLS server conext or nil
191 function prepare_tls(tlskey)
192         local tls
193         if tlskey and cursor:get(UCINAME, tlskey) then
194                 tls = nixio.tls("server")
195                 
196                 local make = cursor:get(UCINAME, tlskey, "generate") == "1"
197                 local key = cursor:get(UCINAME, tlskey, "key")
198                 local xtype = make and "asn1" or cursor:get(UCINAME, tlskey, "type")
199                 local cert = cursor:get(UCINAME, tlskey, "cert")
200                 local ciphers = cursor:get(UCINAME, tlskey, "ciphers")
201                 
202                 if make and (not fs.access(key) or not fs.access(cert)) then
203                         local CN = cursor:get(UCINAME, tlskey, "CN")
204                         local O = cursor:get(UCINAME, tlskey, "O")
205                         local bits = 2048
206                         
207                         local data = {
208                                 CN = CN or nixio.uname().nodename,
209                                 O = not O and "LuCId Keymaster" or #O > 0 and O
210                         }
211                         
212                         local stat, px5g = pcall(require, "px5g")
213                         if not stat then
214                                 return nixio.syslog("err", "Unable to load PX5G Keymaster")
215                         end
216                         
217                         nixio.syslog("warning", "PX5G: Generating private key")
218                         local rk = px5g.genkey(bits)
219                         local keyfile = nixio.open(key, "w", 600)
220                         if not rk or not keyfile or not keyfile:writeall(rk:asn1()) then
221                                 return nixio.syslog("err", "Unable to generate private key")
222                         end
223                         keyfile:close()
224                         
225                         nixio.syslog("warning", "PX5G: Generating self-signed certificate")
226                         if not fs.writefile(cert, rk:create_selfsigned(data,
227                                         os.time(), os.time() + 3600 * 24 * 366 * 15)) then
228                                 return nixio.syslog("err", "Unable to generate certificate")
229                         end
230                 end
231                 
232                 if cert then
233                         if not tls:set_cert(cert, xtype) then
234                                 nixio.syslog("err", "Unable to load certificate: " .. cert)
235                         end
236                 end
237                 if key then
238                         if not tls:set_key(key, xtype) then
239                                 nixio.syslog("err", "Unable to load private key: " .. key)
240                         end
241                 end
242
243                 if ciphers then
244                         if type(ciphers) == "table" then
245                                 ciphers = table.concat(ciphers, ":")
246                         end
247                         tls:set_ciphers(ciphers)
248                 end
249         end
250         return tls
251 end