aboutsummaryrefslogtreecommitdiffstats
path: root/natupnp.go
blob: e4072d0ddb6d966cf9e99eeb7d8b6cbd8a8f38de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package eth

// Just enough UPnP to be able to forward ports
//

import (
    "bytes"
    "encoding/xml"
    "errors"
    "net"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

type upnpNAT struct {
    serviceURL string
    ourIP      string
}

func Discover() (nat NAT, err error) {
    ssdp, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900")
    if err != nil {
        return
    }
    conn, err := net.ListenPacket("udp4", ":0")
    if err != nil {
        return
    }
    socket := conn.(*net.UDPConn)
    defer socket.Close()

    err = socket.SetDeadline(time.Now().Add(10 * time.Second))
    if err != nil {
        return
    }

    st := "ST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n"
    buf := bytes.NewBufferString(
        "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: 239.255.255.250:1900\r\n" +
            st +
            "MAN: \"ssdp:discover\"\r\n" +
            "MX: 2\r\n\r\n")
    message := buf.Bytes()
    answerBytes := make([]byte, 1024)
    for i := 0; i < 3; i++ {
        _, err = socket.WriteToUDP(message, ssdp)
        if err != nil {
            return
        }
        var n int
        n, _, err = socket.ReadFromUDP(answerBytes)
        if err != nil {
            continue
            // socket.Close()
            // return
        }
        answer := string(answerBytes[0:n])
        if strings.Index(answer, "\r\n"+st) < 0 {
            continue
        }
        // HTTP header field names are case-insensitive.
        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
        locString := "\r\nlocation: "
        answer = strings.ToLower(answer)
        locIndex := strings.Index(answer, locString)
        if locIndex < 0 {
            continue
        }
        loc := answer[locIndex+len(locString):]
        endIndex := strings.Index(loc, "\r\n")
        if endIndex < 0 {
            continue
        }
        locURL := loc[0:endIndex]
        var serviceURL string
        serviceURL, err = getServiceURL(locURL)
        if err != nil {
            return
        }
        var ourIP string
        ourIP, err = getOurIP()
        if err != nil {
            return
        }
        nat = &upnpNAT{serviceURL: serviceURL, ourIP: ourIP}
        return
    }
    err = errors.New("UPnP port discovery failed.")
    return
}

// service represents the Service type in an UPnP xml description.
// Only the parts we care about are present and thus the xml may have more
// fields than present in the structure.
type service struct {
    ServiceType string `xml:"serviceType"`
    ControlURL  string `xml:"controlURL"`
}

// deviceList represents the deviceList type in an UPnP xml description.
// Only the parts we care about are present and thus the xml may have more
// fields than present in the structure.
type deviceList struct {
    XMLName xml.Name `xml:"deviceList"`
    Device  []device `xml:"device"`
}

// serviceList represents the serviceList type in an UPnP xml description.
// Only the parts we care about are present and thus the xml may have more
// fields than present in the structure.
type serviceList struct {
    XMLName xml.Name  `xml:"serviceList"`
    Service []service `xml:"service"`
}

// device represents the device type in an UPnP xml description.
// Only the parts we care about are present and thus the xml may have more
// fields than present in the structure.
type device struct {
    XMLName     xml.Name    `xml:"device"`
    DeviceType  string      `xml:"deviceType"`
    DeviceList  deviceList  `xml:"deviceList"`
    ServiceList serviceList `xml:"serviceList"`
}

// specVersion represents the specVersion in a UPnP xml description.
// Only the parts we care about are present and thus the xml may have more
// fields than present in the structure.
type specVersion struct {
    XMLName xml.Name `xml:"specVersion"`
    Major   int      `xml:"major"`
    Minor   int      `xml:"minor"`
}

// root represents the Root document for a UPnP xml description.
// Only the parts we care about are present and thus the xml may have more
// fields than present in the structure.
type root struct {
    XMLName     xml.Name `xml:"root"`
    SpecVersion specVersion
    Device      device
}

func getChildDevice(d *device, deviceType string) *device {
    dl := d.DeviceList.Device
    for i := 0; i < len(dl); i++ {
        if dl[i].DeviceType == deviceType {
            return &dl[i]
        }
    }
    return nil
}

func getChildService(d *device, serviceType string) *service {
    sl := d.ServiceList.Service
    for i := 0; i < len(sl); i++ {
        if sl[i].ServiceType == serviceType {
            return &sl[i]
        }
    }
    return nil
}

func getOurIP() (ip string, err error) {
    hostname, err := os.Hostname()
    if err != nil {
        return
    }
    p, err := net.LookupIP(hostname)
    if err != nil && len(p) > 0 {
        return
    }
    return p[0].String(), nil
}

func getServiceURL(rootURL string) (url string, err error) {
    r, err := http.Get(rootURL)
    if err != nil {
        return
    }
    defer r.Body.Close()
    if r.StatusCode >= 400 {
        err = errors.New(string(r.StatusCode))
        return
    }
    var root root
    err = xml.NewDecoder(r.Body).Decode(&root)

    if err != nil {
        return
    }
    a := &root.Device
    if a.DeviceType != "urn:schemas-upnp-org:device:InternetGatewayDevice:1" {
        err = errors.New("No InternetGatewayDevice")
        return
    }
    b := getChildDevice(a, "urn:schemas-upnp-org:device:WANDevice:1")
    if b == nil {
        err = errors.New("No WANDevice")
        return
    }
    c := getChildDevice(b, "urn:schemas-upnp-org:device:WANConnectionDevice:1")
    if c == nil {
        err = errors.New("No WANConnectionDevice")
        return
    }
    d := getChildService(c, "urn:schemas-upnp-org:service:WANIPConnection:1")
    if d == nil {
        err = errors.New("No WANIPConnection")
        return
    }
    url = combineURL(rootURL, d.ControlURL)
    return
}

func combineURL(rootURL, subURL string) string {
    protocolEnd := "://"
    protoEndIndex := strings.Index(rootURL, protocolEnd)
    a := rootURL[protoEndIndex+len(protocolEnd):]
    rootIndex := strings.Index(a, "/")
    return rootURL[0:protoEndIndex+len(protocolEnd)+rootIndex] + subURL
}

func soapRequest(url, function, message string) (r *http.Response, err error) {
    fullMessage := "<?xml version=\"1.0\" ?>" +
        "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" +
        "<s:Body>" + message + "</s:Body></s:Envelope>"

    req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage))
    if err != nil {
        return nil, err
    }
    req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"")
    req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3")
    //req.Header.Set("Transfer-Encoding", "chunked")
    req.Header.Set("SOAPAction", "\"urn:schemas-upnp-org:service:WANIPConnection:1#"+function+"\"")
    req.Header.Set("Connection", "Close")
    req.Header.Set("Cache-Control", "no-cache")
    req.Header.Set("Pragma", "no-cache")

    // log.Stderr("soapRequest ", req)
    //fmt.Println(fullMessage)

    r, err = http.DefaultClient.Do(req)
    if r.Body != nil {
        defer r.Body.Close()
    }

    if r.StatusCode >= 400 {
        // log.Stderr(function, r.StatusCode)
        err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function)
        r = nil
        return
    }
    return
}

type statusInfo struct {
    externalIpAddress string
}

func (n *upnpNAT) getStatusInfo() (info statusInfo, err error) {

    message := "<u:GetStatusInfo xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" +
        "</u:GetStatusInfo>"

    var response *http.Response
    response, err = soapRequest(n.serviceURL, "GetStatusInfo", message)
    if err != nil {
        return
    }

    // TODO: Write a soap reply parser. It has to eat the Body and envelope tags...

    response.Body.Close()
    return
}

func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) {
    info, err := n.getStatusInfo()
    if err != nil {
        return
    }
    addr = net.ParseIP(info.externalIpAddress)
    return
}

func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) {
    // A single concatenation would break ARM compilation.
    message := "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" +
        "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort)
    message += "</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>"
    message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" +
        "<NewInternalClient>" + n.ourIP + "</NewInternalClient>" +
        "<NewEnabled>1</NewEnabled><NewPortMappingDescription>"
    message += description +
        "</NewPortMappingDescription><NewLeaseDuration>" + strconv.Itoa(timeout) +
        "</NewLeaseDuration></u:AddPortMapping>"

    var response *http.Response
    response, err = soapRequest(n.serviceURL, "AddPortMapping", message)
    if err != nil {
        return
    }

    // TODO: check response to see if the port was forwarded
    // log.Println(message, response)
    mappedExternalPort = externalPort
    _ = response
    return
}

func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) {

    message := "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" +
        "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) +
        "</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>" +
        "</u:DeletePortMapping>"

    var response *http.Response
    response, err = soapRequest(n.serviceURL, "DeletePortMapping", message)
    if err != nil {
        return
    }

    // TODO: check response to see if the port was deleted
    // log.Println(message, response)
    _ = response
    return
}
d>-10/+12 | | * | cmd/mist, eth, javascript, p2p: use Node URLs for peer suggestionsFelix Lange2015-02-072-44/+12 | | * | cmd/ethereum, cmd/mist, core, eth, javascript, xeth: fixes for new p2p APIFelix Lange2015-02-068-49/+38 | | * | cmd/peerserver: is goneFelix Lange2015-02-061-58/+0 | * | | mergeobscuren2015-02-13109-6623/+6883 | |\ \ \ | | * | | removed messagesobscuren2015-02-133-46/+0 | | * | | cmd + t switches to new dapp windowobscuren2015-02-121-2/+3 | * | | | Add LogFormat flagTaylor Gerring2015-01-222-0/+3 * | | | | Merge branch 'develop' into minerobscuren2015-02-1223-932/+1511 |\ \ \ \ \ | | |/ / / | |/| | | | * | | | Documented methods & removed old manifestobscuren2015-02-121-0/+1 | * | | | Merge branch 'develop' of github.com-obscure:ethereum/go-ethereum into developobscuren2015-02-123-119/+96 | |\ \ \ \ | | | |_|/ | | |/| | | | * | | Catalog Page BehaviourAlexandre Van de Sande2015-02-123-119/+96 | * | | | updated coinobscuren2015-02-111-12/+7 | |/ / / | * | | removed icomoonAlexandre Van de Sande2015-02-101-0/+0 | * | | Recreated the changes on a new branchAlexandre Van de Sande2015-02-1022-920/+1526 * | | | Basic structure minerobscuren2015-02-102-9/+12 * | | | mergedobscuren2015-02-0912-169/+179 |\| | | | * | | Updated coinobscuren2015-02-081-30/+66 | * | | API changed to use Pubkey only. Reflected that change in the rest of the apiobscuren2015-02-061-1/+2 | | |/ | |/| | * | Merge branch 'develop' of github.com-obscure:ethereum/go-ethereum into developobscuren2015-02-066-9/+9 | |\ \ | | * \ Merge pull request #287 from ethereum/system-testingJeffrey Wilcke2015-02-066-9/+9 | | |\ \ | | | * | Move hardcoded seed node address to app flagTaylor Gerring2015-02-036-9/+9 | * | | | updated homeobscuren2015-02-061-1/+1 | * | | | Merge commit '9d84609b3faf797f4a611587abdda3d6b3b07917' into developobscuren2015-02-064-51/+17 | * | | | pending / chain eventobscuren2015-02-061-1/+9 | * | | | Merge branch 'develop' of https://github.com/tgerring/go-ethereum into tgerri...obscuren2015-02-063-3/+3 | |\ \ \ \ | | |/ / / | |/| | | | | * | | Merge branch 'develop' of github.com:tgerring/go-ethereum into developTaylor Gerring2015-02-051-1/+1 | | |\ \ \ | | | * \ \ Merge branch 'develop' of github.com:tgerring/go-ethereum into developTaylor Gerring2015-02-041-1/+1 | | | |\ \ \ | | | | * | | Update signature for rpc websocketsTaylor Gerring2015-02-021-1/+1 | | | | |/ / | | * | / / Use different default RPC port per #186Taylor Gerring2015-02-052-2/+2 | | |/ / / * | | | | Merge branch 'develop' into minerobscuren2015-02-062-2/+3 |\| | | | | * | | | Default gas price and default gas for rpcobscuren2015-02-051-2/+2 | * | | | fixed testobscuren2015-02-051-0/+1 * | | | | wipobscuren2015-02-062-81/+81 |/ / / / * | | | Propagate known transactions to new peers on connectobscuren2015-02-051-4/+4 * | | | Merge branch 'develop' into minerobscuren2015-02-0527-477/+1203 |\ \ \ \ | * | | | updated testsobscuren2015-02-0528-946/+2130 | |/ / / * / / / Filteringobscuren2015-02-054-475/+950 |/ / / * | | Removed minimum height. Closes #282obscuren2015-02-031-2/+1 * | | Fixed whisper "to" filtering. Closes #283obscuren2015-02-031-0/+10 * | | Added a different default home pageobscuren2015-02-033-2/+77 * | | Raw data for existing blocksobscuren2015-02-031-1/+1 * | | Removed some VMEnv & Added VmType() to vm.Environmentobscuren2015-02-012-102/+8 |/ / * | added new default faviconobscuren2015-01-301-0/+0 * | "fixed" transaction viewobscuren2015-01-303-6/+5 * | Bumped version numberobscuren2015-01-302-2/+2 * | Added whisper messagesobscuren2015-01-301-2/+20 * | Added whisper interface for xeth, added examples, updated RPCobscuren2015-01-304-3/+48 * | Fixed issue with Storage()obscuren2015-01-301-1/+2 * | default values removedobscuren2015-01-301-11/+19 * | Merge branch 'qt5.4' of github.com-obscure:ethereum/go-ethereum into qt5.4obscuren2015-01-301-3/+0 |\ \ | * \ Merge branch 'qt5.4' of github.com:ethereum/go-ethereum into qt5.4Taylor Gerring2015-01-3049-3016/+240 | |\ \ | * | | Remove old websocket implementationTaylor Gerring2015-01-291-3/+0 * | | | More dapp samplesobscuren2015-01-302-0/+161 | |/ / |/| | * | | Reimplemented message filters for rpc callsobscuren2015-01-291-1/+1 * | | Samples and disams cmd for evm codeobscuren2015-01-293-4/+89 * | | Added RPC "Call" for JS calls to contractsobscuren2015-01-291-2/+1 * | | Added abi exampleobscuren2015-01-291-0/+44 * | | implement transactobscuren2015-01-292-5/+2 * | | updated ethereum.js and moved to subfolderobscuren2015-01-294-2/+101 * | | Add 'cmd/mist/assets/ext/ethereum.js/' from commit '63d9c070ef7637a3d570a5a45...obscuren2015-01-2934-0/+4018 * | | removed old js yet againobscuren2015-01-2939-7018/+0 * | | default http rpc onobscuren2015-01-291-1/+1 |/ / * | Added webengine initializerobscuren2015-01-292-0/+694 * | removed key while in the process of moving to the new key storageobscuren2015-01-296-698/+5 * | Merge branch 'jsonrpc' into qt5.4obscuren2015-01-296-17/+17 |\ \ | * | further cleaned up xeth interfaceobscuren2015-01-296-17/+17 * | | merge jsonrpcobscuren2015-01-2910-129/+59 |\| | | * | moving to a better xethobscuren2015-01-294-118/+41 | * | Rename transport to wsTaylor Gerring2015-01-281-1/+1 | * | Add wsport flag to MistTaylor Gerring2015-01-282-1/+3 | * | Update CLI to use new Websocket RPCTaylor Gerring2015-01-283-5/+15 | * | Move HTTP transport to sub package of RPCTaylor Gerring2015-01-281-2/+2 * | | switched to obscuren/qmlobscuren2015-01-288-8/+8 * | | Updated assets & moved messagesobscuren2015-01-289-65/+81 * | | Added big numbersobscuren2015-01-281-0/+2 * | | Merge branch 'develop' into qt5.4obscuren2015-01-2834-0/+4018 |\ \ \ | * | | new ethereum.jsobscuren2015-01-2834-0/+4018 * | | | removed old ethereum.jsobscuren2015-01-2825-2938/+0 * | | | Merge branch 'jsonrpc' into qt5.4obscuren2015-01-282-220/+8 |\ \ \ \ | | |/ / | |/| | | * | | Merge branch 'develop' into jsonrpcobscuren2015-01-234-281/+268 | |\| | | * | | Move websockets out of cmd/utilTaylor Gerring2015-01-212-220/+8 | | |/ | |/| * | | Reworking browserobscuren2015-01-253-38/+241 | |/ |/| * | UI Updatesobscuren2015-01-224-66/+39 * | Updated browser & pass view to callback functionobscuren2015-01-222-231/+245 |/ * fixed url bug in browserobscuren2015-01-211-5/+0 * StdVm by defaultobscuren2015-01-203-4/+8 * Hide browser bar when coming from a DApp urlobscuren2015-01-201-24/+28 * Minor browser improvementsobscuren2015-01-193-6/+30 * Add defer rescued back inobscuren2015-01-161-0/+5 * updated testsobscuren2015-01-151-0/+3 * Changed public whisper api not to reveal temporary private keysobscuren2015-01-151-402/+435 * Default datadir for mist is now shared with CLI (.ethereum)obscuren2015-01-131-1/+1 * Fixed whisper messagesobscuren2015-01-131-1/+3 * Added manual triggering of filtersobscuren2015-01-132-2/+9 * removed accidental qt depobscuren2015-01-111-2/+2 * Implemented filter for ws + fixesobscuren2015-01-103-11/+46 * Updated to new ethereum.js apiobscuren2015-01-091-1/+1 * mergedobscuren2015-01-091-1/+0 * new switchobscuren2015-01-091-40/+26 * updated ethereum.jsobscuren2015-01-0925-0/+2938 * removedobscuren2015-01-0925-2931/+0 * Updated ethereum.jsobscuren2015-01-0934-951/+2924 * Support input from argsobscuren2015-01-091-1/+6 * Fixed some whisper issuesobscuren2015-01-09