luci-app-olsr: handle empty result for non-status tables
[oweals/luci.git] / applications / luci-app-openvpn / luasrc / controller / openvpn.lua
1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
3 -- Licensed to the public under the Apache License 2.0.
4
5 module("luci.controller.openvpn", package.seeall)
6
7 function index()
8         entry( {"admin", "services", "openvpn"}, cbi("openvpn"), _("OpenVPN") )
9         entry( {"admin", "services", "openvpn", "basic"},    cbi("openvpn-basic"),    nil ).leaf = true
10         entry( {"admin", "services", "openvpn", "advanced"}, cbi("openvpn-advanced"), nil ).leaf = true
11         entry( {"admin", "services", "openvpn", "file"},     form("openvpn-file"),    nil ).leaf = true
12         entry( {"admin", "services", "openvpn", "upload"},   call("ovpn_upload"))
13 end
14
15 function ovpn_upload()
16         local fs     = require("nixio.fs")
17         local http   = require("luci.http")
18         local util   = require("luci.util")
19         local uci    = require("luci.model.uci").cursor()
20         local upload = http.formvalue("ovpn_file")
21         local name   = http.formvalue("instance_name2")
22         local file   = "/etc/openvpn/" ..name.. ".ovpn"
23
24         if name and upload then
25                 local fp
26
27                 http.setfilehandler(
28                         function(meta, chunk, eof)
29                                 local data = util.trim(chunk:gsub("\r\n", "\n")) .. "\n"
30                                 data = util.trim(data:gsub("[\128-\255]", ""))
31
32                                 if not fp and meta and meta.name == "ovpn_file" then
33                                         fp = io.open(file, "w")
34                                 end
35                                 if fp and data then
36                                         fp:write(data)
37                                 end
38                                 if fp and eof then
39                                         fp:close()
40                                 end
41                         end
42                 )
43
44                 if fs.access(file) then
45                         if not uci:get_first("openvpn", name) then
46                                 uci:set("openvpn", name, "openvpn")
47                                 uci:set("openvpn", name, "config", file)
48                                 uci:save("openvpn")
49                                 uci:commit("openvpn")
50                         end
51                 end
52         end
53         http.redirect(luci.dispatcher.build_url('admin/services/openvpn'))
54 end