better warnings
[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
32 function prepare_daemon(config, server)
33         nixio.syslog("info", "Preparing TCP-Daemon " .. config[".name"])
34         if type(config.address) ~= "table" then
35                 config.address = {config.address}
36         end
37         
38         local sockets, socket, code, err = {}
39         local sopts = {reuseaddr = 1}
40         for _, addr in ipairs(config.address) do
41                 local host, port = addr:match("(.-):?([^:]*)")
42                 if not host then
43                         nixio.syslog("err", "Invalid address: " .. addr)
44                         return nil, -5, "invalid address format"
45                 elseif #host == 0 then
46                         host = nil
47                 end
48                 socket, code, err = prepare_socket(config.family, host, port, sopts)
49                 if socket then
50                         sockets[#sockets+1] = socket
51                 end
52         end
53         
54         nixio.syslog("info", "Sockets bound for " .. config[".name"])
55         
56         if #sockets < 1 then
57                 return nil, -6, "no sockets bound"
58         end
59         
60         nixio.syslog("info", "Preparing publishers for " .. config[".name"])
61         
62         local publisher = {}
63         for k, pname in ipairs(config.publisher) do
64                 local pdata = cursor:get_all(UCINAME, pname)
65                 if pdata then
66                         publisher[#publisher+1] = pdata
67                 else
68                         nixio.syslog("err", "Publisher " .. pname .. " not found")
69                 end
70         end
71         
72         nixio.syslog("info", "Preparing TLS for " .. config[".name"])
73         
74         local tls = prepare_tls(config.tls)
75         if not tls and config.encryption == "enable" then
76                 for _, s in ipairs(sockets) do
77                         s:close()
78                 end
79                 return nil, -4, "Encryption requested, but no TLS context given"
80         end
81         
82         nixio.syslog("info", "Invoking daemon factory for " .. config[".name"])
83         local handler, err = config.slave.module.factory(publisher, config)
84         if not handler then
85                 for _, s in ipairs(sockets) do
86                         s:close()
87                 end
88                 return nil, -3, err
89         else
90                 local pollin = nixio.poll_flags("in")
91                 for _, s in ipairs(sockets) do
92                         server.register_pollfd({
93                                 fd = s,
94                                 events = pollin,
95                                 revents = 0,
96                                 handler = accept,
97                                 accept = handler,
98                                 config = config,
99                                 publisher = publisher,
100                                 tls = tls
101                         })
102                 end
103                 return true
104         end
105 end
106
107 function accept(polle)
108         local socket, host, port = polle.fd:accept()
109         if not socket then
110                 return nixio.syslog("warn", "accept() failed: " .. port)
111         end
112         
113         socket:setblocking(true)
114         
115         local function thread()
116                 lucid.close_pollfds()
117                 local inst = setmetatable({
118                         host = host, port = port, interfaces = lucid.get_interfaces() 
119                 }, {__index = polle})
120                 if polle.config.encryption then
121                         socket = polle.tls:create(socket)
122                         if not socket:accept() then
123                                 socket:close()
124                                 return nixio.syslog("warning", "TLS handshake failed: " .. host)
125                         end
126                 end
127                 
128                 return polle.accept(socket, inst)
129         end
130         
131         local stat = {lucid.create_process(thread)}
132         socket:close()
133         return unpack(stat)
134 end
135
136 function prepare_socket(family, host, port, opts, backlog)
137         nixio.syslog("info", "Preparing socket for port " .. port)
138         backlog = backlog or 1024
139         family = family or "inetany"
140         opts = opts or {}
141         
142         local inetany = family == "inetany"
143         family = inetany and "inet6" or family
144
145         local socket, code, err = nixio.socket(family, "stream")
146         if not socket and inetany then
147                 family = "inet"
148                 socket, code, err = nixio.socket(family, "stream")
149         end
150         
151         if not socket then
152                 return nil, code, err
153         end
154
155         for k, v in pairs(opts) do
156                 socket:setsockopt("socket", k, v)
157         end
158         
159         local stat, code, err = socket:bind(host, port)
160         if not stat then
161                 return nil, code, err
162         end
163         
164         stat, code, err = socket:listen(backlog)
165         if not stat then
166                 return nil, code, err
167         end
168         
169         socket:setblocking(false)
170
171         return socket, family
172 end
173
174 function prepare_tls(tlskey)
175         local tls
176         if tlskey and cursor:get(UCINAME, tlskey) then
177                 tls = nixio.tls("server")
178                 
179                 local make = cursor:get(UCINAME, tlskey, "generate") == "1"
180                 local key = cursor:get(UCINAME, tlskey, "key")
181                 local xtype = make and "asn1" or cursor:get(UCINAME, tlskey, "type")
182                 local cert = cursor:get(UCINAME, tlskey, "cert")
183                 local ciphers = cursor:get(UCINAME, tlskey, "ciphers")
184                 
185                 if make and (not fs.access(key) or not fs.access(cert)) then
186                         local CN = cursor:get(UCINAME, tlskey, "CN")
187                         local O = cursor:get(UCINAME, tlskey, "O")
188                         local bits = 2048
189                         
190                         local data = {
191                                 CN = CN or nixio.uname().nodename,
192                                 O = not O and "LuCId Keymaster" or #O > 0 and O
193                         }
194                         
195                         local stat, px5g = pcall(require, "px5g")
196                         if not stat then
197                                 return nixio.syslog("err", "Unable to load PX5G Keymaster")
198                         end
199                         
200                         nixio.syslog("warning", "PX5G: Generating private key")
201                         local rk = px5g.genkey(bits)
202                         local keyfile = nixio.open(key, "w", 600)
203                         if not rk or not keyfile or not keyfile:writeall(rk:asn1()) then
204                                 return nixio.syslog("err", "Unable to generate private key")
205                         end
206                         keyfile:close()
207                         
208                         nixio.syslog("warning", "PX5G: Generating self-signed certificate")
209                         if not fs.writefile(cert, rk:create_selfsigned(data,
210                                         os.time(), os.time() + 3600 * 24 * 366 * 15)) then
211                                 return nixio.syslog("err", "Unable to generate certificate")
212                         end
213                 end
214                 
215                 if cert then
216                         if not tls:set_cert(cert, xtype) then
217                                 nixio.syslog("err", "Unable to load certificate: " .. cert)
218                         end
219                 end
220                 if key then
221                         if not tls:set_key(key, xtype) then
222                                 nixio.syslog("err", "Unable to load private key: " .. key)
223                         end
224                 end
225
226                 if ciphers then
227                         if type(ciphers) == "table" then
228                                 ciphers = table.concat(ciphers, ":")
229                         end
230                         tls:set_ciphers(ciphers)
231                 end
232         end
233         return tls
234 end