cjdns: import package from github.com:SeattleMeshnet/meshbox
[feed/routing.git] / cjdns / lua / cjdns / udp.lua
1 -- Cjdns admin module for Lua
2 -- Written by Philip Horger
3
4 common = require 'cjdns/common'
5
6 UDPInterface = {}
7 UDPInterface.__index = UDPInterface
8 common.UDPInterface = UDPInterface
9
10 function UDPInterface.new(ai, config, ptype)
11 properties = {
12 ai = ai,
13 config = config or ai.config,
14 ptype = ptype or "ai"
15 }
16
17 return setmetatable(properties, UDPInterface)
18 end
19
20 function UDPInterface:call(name, args)
21 local func = self[name .. "_" .. self.ptype]
22 return func(self, unpack(args))
23 end
24
25 function UDPInterface:newBind(...)
26 return self:call("newBind", arg)
27 end
28
29 function UDPInterface:beginConnection(...)
30 return self:call("beginConnection", arg)
31 end
32
33 function UDPInterface:newBind_ai(address)
34 local response, err = self.ai:auth({
35 q = "UDPInterface_new",
36 bindAddress = address
37 })
38 if not response then
39 return nil, err
40 elseif response.error ~= "none" then
41 return nil, response.error
42 elseif response.interfaceNumber then
43 return response.interfaceNumber
44 else
45 return nil, "bad response format"
46 end
47 end
48
49 function UDPInterface:newBind_config(address)
50 local udpif = self.config.contents.interfaces.UDPInterface
51 local new_interface = {
52 bind = address,
53 connectTo = {}
54 }
55 table.insert(udpif, new_interface)
56 return (#udpif - 1), new_interface
57 end
58
59 function UDPInterface:newBind_perm(...)
60 return
61 self:newBind_config(unpack(arg)),
62 self:newBind_ai(unpack(arg))
63 end
64
65 function UDPInterface:beginConnection_ai(pubkey, addr, password, interface)
66 local request = {
67 q = "UDPInterface_beginConnection",
68 publicKey = pubkey,
69 address = addr,
70 password = password
71 }
72 if interface then
73 request.interfaceNumber = interface
74 end
75
76 local response, err = self.ai:auth(request)
77 if not response then
78 return nil, err
79 elseif response.error == "none" then
80 -- Unfortunately, no real success indicator either.
81 return "No error"
82 else
83 return nil, response.error
84 end
85 end
86
87 function UDPInterface:beginConnection_config(pubkey, addr, password, interface)
88 local udpif = self.config.contents.interfaces.UDPInterface
89 local connections = udpif[(interface or 0) + 1].connectTo
90 local this_conn = {
91 password = password,
92 publicKey = pubkey
93 }
94 connections[addr] = this_conn
95 return this_conn -- allows adding metadata fields afterwards
96 end
97
98 function UDPInterface:beginConnection_perm(...)
99 return
100 self:beginConnection_config(unpack(arg)),
101 self:beginConnection_ai(unpack(arg))
102 end