net.go (2451B)
1 package damlib 2 3 /* 4 * Copyright (c) 2017-2018 Dyne.org Foundation 5 * tor-dam is written and maintained by Ivan Jelincic <parazyd@dyne.org> 6 * 7 * This file is part of tor-dam 8 * 9 * This program is free software: you can redistribute it and/or modify 10 * it under the terms of the GNU Affero General Public License as published by 11 * the Free Software Foundation, either version 3 of the License, or 12 * (at your option) any later version. 13 * 14 * This program is distributed in the hope that it will be useful, 15 * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 * GNU Affero General Public License for more details. 18 * 19 * You should have received a copy of the GNU Affero General Public License 20 * along with this program. If not, see <http://www.gnu.org/licenses/>. 21 */ 22 23 import ( 24 "bytes" 25 "io/ioutil" 26 "log" 27 "net/http" 28 "net/url" 29 "strings" 30 31 "golang.org/x/net/proxy" 32 ) 33 34 // HTTPPost sends an HTTP POST request to the given host. 35 // Takes the host to request and the data to post as arguments. 36 // If the host ends with ".onion", it will enable the request to be performed 37 // over a SOCKS proxy, defined in ProxyAddr. 38 // On success, it will return the http.Response. Otherwise, it returns an error. 39 func HTTPPost(host string, data []byte) (*http.Response, error) { 40 socksify := false 41 parsedHost, err := url.Parse(host) 42 if err != nil { 43 return nil, err 44 } 45 hostname := parsedHost.Hostname() 46 if strings.HasSuffix(hostname, ".onion") { 47 socksify = true 48 } 49 httpTransp := &http.Transport{} 50 httpClient := &http.Client{Transport: httpTransp} 51 if socksify { 52 log.Println("Detected a .onion request. Using SOCKS proxy.") 53 dialer, err := proxy.SOCKS5("tcp", ProxyAddr, nil, proxy.Direct) 54 if err != nil { 55 return nil, err 56 } 57 httpTransp.Dial = dialer.Dial 58 } 59 request, err := http.NewRequest("POST", host, bytes.NewBuffer(data)) 60 if err != nil { 61 return nil, err 62 } 63 request.Header.Set("Content-Type", "application/json") 64 65 resp, err := httpClient.Do(request) 66 if err != nil { 67 return nil, err 68 } 69 70 return resp, nil 71 } 72 73 // HTTPDownload tries to download a given uri and return it as a slice of bytes. 74 // On failure it will return an error. 75 func HTTPDownload(uri string) ([]byte, error) { 76 res, err := http.Get(uri) 77 if err != nil { 78 return nil, err 79 } 80 defer res.Body.Close() 81 d, err := ioutil.ReadAll(res.Body) 82 if err != nil { 83 return nil, err 84 } 85 return d, nil 86 }