Add needed package
This commit is contained in:
parent
8da8881825
commit
dc15faabe3
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,275 @@
|
|||
/*
|
||||
Copyright 2011 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package netutil identifies the system userid responsible for
|
||||
// localhost TCP connections.
|
||||
package netutil // import "camlistore.org/pkg/netutil"
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("netutil: connection not found")
|
||||
ErrUnsupportedOS = errors.New("netutil: not implemented on this operating system")
|
||||
)
|
||||
|
||||
// ConnUserid returns the uid that owns the given localhost connection.
|
||||
// The returned error is ErrNotFound if the connection wasn't found.
|
||||
func ConnUserid(conn net.Conn) (uid int, err error) {
|
||||
return AddrPairUserid(conn.LocalAddr(), conn.RemoteAddr())
|
||||
}
|
||||
|
||||
// HostPortToIP parses a host:port to a TCPAddr without resolving names.
|
||||
// If given a context IP, it will resolve localhost to match the context's IP family.
|
||||
func HostPortToIP(hostport string, ctx *net.TCPAddr) (hostaddr *net.TCPAddr, err error) {
|
||||
host, port, err := net.SplitHostPort(hostport)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
iport, err := strconv.Atoi(port)
|
||||
if err != nil || iport < 0 || iport > 0xFFFF {
|
||||
return nil, fmt.Errorf("invalid port %d", iport)
|
||||
}
|
||||
var addr net.IP
|
||||
if ctx != nil && host == "localhost" {
|
||||
if ctx.IP.To4() != nil {
|
||||
addr = net.IPv4(127, 0, 0, 1)
|
||||
} else {
|
||||
addr = net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
|
||||
}
|
||||
} else if addr = net.ParseIP(host); addr == nil {
|
||||
return nil, fmt.Errorf("could not parse IP %s", host)
|
||||
}
|
||||
|
||||
return &net.TCPAddr{IP: addr, Port: iport}, nil
|
||||
}
|
||||
|
||||
// AddrPairUserid returns the local userid who owns the TCP connection
|
||||
// given by the local and remote ip:port (lipport and ripport,
|
||||
// respectively). Returns ErrNotFound for the error if the TCP connection
|
||||
// isn't found.
|
||||
func AddrPairUserid(local, remote net.Addr) (uid int, err error) {
|
||||
lAddr, lOk := local.(*net.TCPAddr)
|
||||
rAddr, rOk := remote.(*net.TCPAddr)
|
||||
if !(lOk && rOk) {
|
||||
return -1, fmt.Errorf("netutil: Could not convert Addr to TCPAddr.")
|
||||
}
|
||||
|
||||
localv4 := (lAddr.IP.To4() != nil)
|
||||
remotev4 := (rAddr.IP.To4() != nil)
|
||||
if localv4 != remotev4 {
|
||||
return -1, fmt.Errorf("netutil: address pairs of different families; localv4=%v, remotev4=%v",
|
||||
localv4, remotev4)
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
return uidFromLsof(lAddr.IP, lAddr.Port, rAddr.IP, rAddr.Port)
|
||||
case "freebsd":
|
||||
return uidFromSockstat(lAddr.IP, lAddr.Port, rAddr.IP, rAddr.Port)
|
||||
case "linux":
|
||||
file := "/proc/net/tcp"
|
||||
if !localv4 {
|
||||
file = "/proc/net/tcp6"
|
||||
}
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("Error opening %s: %v", file, err)
|
||||
}
|
||||
defer f.Close()
|
||||
return uidFromProcReader(lAddr.IP, lAddr.Port, rAddr.IP, rAddr.Port, f)
|
||||
}
|
||||
return 0, ErrUnsupportedOS
|
||||
}
|
||||
|
||||
func toLinuxIPv4Order(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b, binary.LittleEndian.Uint32(b))
|
||||
return b
|
||||
}
|
||||
|
||||
func toLinuxIPv6Order(b []byte) []byte {
|
||||
for i := 0; i < 16; i += 4 {
|
||||
sb := b[i : i+4]
|
||||
binary.BigEndian.PutUint32(sb, binary.LittleEndian.Uint32(sb))
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
type maybeBrackets net.IP
|
||||
|
||||
func (p maybeBrackets) String() string {
|
||||
s := net.IP(p).String()
|
||||
if strings.Contains(s, ":") {
|
||||
return "[" + s + "]"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Changed by tests.
|
||||
var uidFromUsername = uidFromUsernameFn
|
||||
|
||||
func uidFromUsernameFn(username string) (uid int, err error) {
|
||||
if uid := os.Getuid(); uid != 0 && username == os.Getenv("USER") {
|
||||
return uid, nil
|
||||
}
|
||||
u, err := user.Lookup(username)
|
||||
if err == nil {
|
||||
uid, err := strconv.Atoi(u.Uid)
|
||||
return uid, err
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
|
||||
func uidFromLsof(lip net.IP, lport int, rip net.IP, rport int) (uid int, err error) {
|
||||
seek := fmt.Sprintf("%s:%d->%s:%d", maybeBrackets(lip), lport, maybeBrackets(rip), rport)
|
||||
seekb := []byte(seek)
|
||||
if _, err = exec.LookPath("lsof"); err != nil {
|
||||
return
|
||||
}
|
||||
cmd := exec.Command("lsof",
|
||||
"-b", // avoid system calls that could block
|
||||
"-w", // and don't warn about cases where -b fails
|
||||
"-n", // don't resolve network names
|
||||
"-P", // don't resolve network ports,
|
||||
// TODO(bradfitz): pass down the uid we care about, then do: ?
|
||||
//"-a", // AND the following together:
|
||||
// "-u", strconv.Itoa(uid) // just this uid
|
||||
"-itcp") // we only care about TCP connections
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer cmd.Wait()
|
||||
defer stdout.Close()
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer cmd.Process.Kill()
|
||||
br := bufio.NewReader(stdout)
|
||||
for {
|
||||
line, err := br.ReadSlice('\n')
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
if !bytes.Contains(line, seekb) {
|
||||
continue
|
||||
}
|
||||
// SystemUIS 276 bradfitz 15u IPv4 0xffffff801a7c74e0 0t0 TCP 127.0.0.1:56718->127.0.0.1:5204 (ESTABLISHED)
|
||||
f := bytes.Fields(line)
|
||||
if len(f) < 8 {
|
||||
continue
|
||||
}
|
||||
username := string(f[2])
|
||||
return uidFromUsername(username)
|
||||
}
|
||||
return -1, ErrNotFound
|
||||
|
||||
}
|
||||
|
||||
func uidFromSockstat(lip net.IP, lport int, rip net.IP, rport int) (int, error) {
|
||||
cmd := exec.Command("sockstat", "-Ptcp")
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer cmd.Wait()
|
||||
defer stdout.Close()
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer cmd.Process.Kill()
|
||||
|
||||
return uidFromSockstatReader(lip, lport, rip, rport, stdout)
|
||||
}
|
||||
|
||||
func uidFromSockstatReader(lip net.IP, lport int, rip net.IP, rport int, r io.Reader) (int, error) {
|
||||
pat, err := regexp.Compile(fmt.Sprintf(`^([^ ]+).*%s:%d *%s:%d$`,
|
||||
lip.String(), lport, rip.String(), rport))
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
l := scanner.Text()
|
||||
m := pat.FindStringSubmatch(l)
|
||||
if len(m) == 2 {
|
||||
return uidFromUsername(m[1])
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return -1, ErrNotFound
|
||||
}
|
||||
|
||||
func uidFromProcReader(lip net.IP, lport int, rip net.IP, rport int, r io.Reader) (uid int, err error) {
|
||||
buf := bufio.NewReader(r)
|
||||
|
||||
localHex := ""
|
||||
remoteHex := ""
|
||||
ipv4 := lip.To4() != nil
|
||||
if ipv4 {
|
||||
// In the kernel, the port is run through ntohs(), and
|
||||
// the inet_request_socket in
|
||||
// include/net/inet_socket.h says the "loc_addr" and
|
||||
// "rmt_addr" fields are __be32, but get_openreq4's
|
||||
// printf of them is raw, without byte order
|
||||
// converstion.
|
||||
localHex = fmt.Sprintf("%08X:%04X", toLinuxIPv4Order([]byte(lip.To4())), lport)
|
||||
remoteHex = fmt.Sprintf("%08X:%04X", toLinuxIPv4Order([]byte(rip.To4())), rport)
|
||||
} else {
|
||||
localHex = fmt.Sprintf("%032X:%04X", toLinuxIPv6Order([]byte(lip.To16())), lport)
|
||||
remoteHex = fmt.Sprintf("%032X:%04X", toLinuxIPv6Order([]byte(rip.To16())), rport)
|
||||
}
|
||||
|
||||
for {
|
||||
line, err := buf.ReadString('\n')
|
||||
if err != nil {
|
||||
return -1, ErrNotFound
|
||||
}
|
||||
parts := strings.Fields(strings.TrimSpace(line))
|
||||
if len(parts) < 8 {
|
||||
continue
|
||||
}
|
||||
// log.Printf("parts[1] = %q; localHex = %q", parts[1], localHex)
|
||||
if parts[1] == localHex && parts[2] == remoteHex {
|
||||
uid, err = strconv.Atoi(parts[7])
|
||||
return uid, err
|
||||
}
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
|
@ -0,0 +1,141 @@
|
|||
/*
|
||||
Copyright 2014 The Camlistore Authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package netutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AwaitReachable tries to make a TCP connection to addr regularly.
|
||||
// It returns an error if it's unable to make a connection before maxWait.
|
||||
func AwaitReachable(addr string, maxWait time.Duration) error {
|
||||
done := time.Now().Add(maxWait)
|
||||
for time.Now().Before(done) {
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err == nil {
|
||||
c.Close()
|
||||
return nil
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("%v unreachable for %v", addr, maxWait)
|
||||
}
|
||||
|
||||
// HostPort takes a urlStr string URL, and returns a host:port string suitable
|
||||
// to passing to net.Dial, with the port set as the scheme's default port if
|
||||
// absent.
|
||||
func HostPort(urlStr string) (string, error) {
|
||||
// TODO: rename this function to URLHostPort instead, like
|
||||
// ListenHostPort below.
|
||||
u, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not parse %q as a url: %v", urlStr, err)
|
||||
}
|
||||
if u.Scheme == "" {
|
||||
return "", fmt.Errorf("url %q has no scheme", urlStr)
|
||||
}
|
||||
hostPort := u.Host
|
||||
if hostPort == "" || strings.HasPrefix(hostPort, ":") {
|
||||
return "", fmt.Errorf("url %q has no host", urlStr)
|
||||
}
|
||||
idx := strings.Index(hostPort, "]")
|
||||
if idx == -1 {
|
||||
idx = 0
|
||||
}
|
||||
if !strings.Contains(hostPort[idx:], ":") {
|
||||
if u.Scheme == "https" {
|
||||
hostPort += ":443"
|
||||
} else {
|
||||
hostPort += ":80"
|
||||
}
|
||||
}
|
||||
return hostPort, nil
|
||||
}
|
||||
|
||||
// ListenHostPort maps a listen address into a host:port string.
|
||||
// If the host part in listenAddr is empty or 0.0.0.0, localhost
|
||||
// is used instead.
|
||||
func ListenHostPort(listenAddr string) (string, error) {
|
||||
hp := listenAddr
|
||||
if strings.HasPrefix(hp, ":") {
|
||||
hp = "localhost" + hp
|
||||
} else if strings.HasPrefix(hp, "0.0.0.0:") {
|
||||
hp = "localhost:" + hp[len("0.0.0.0:"):]
|
||||
}
|
||||
if _, _, err := net.SplitHostPort(hp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hp, nil
|
||||
}
|
||||
|
||||
// ListenOnLocalRandomPort returns a TCP listener on a random
|
||||
// localhost port.
|
||||
func ListenOnLocalRandomPort() (net.Listener, error) {
|
||||
ip, err := Localhost()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return net.ListenTCP("tcp", &net.TCPAddr{IP: ip, Port: 0})
|
||||
}
|
||||
|
||||
// Localhost returns the first address found when
|
||||
// doing a lookup of "localhost". If not successful,
|
||||
// it looks for an ip on the loopback interfaces.
|
||||
func Localhost() (net.IP, error) {
|
||||
if ip := localhostLookup(); ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
if ip := loopbackIP(); ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
return nil, errors.New("No loopback ip found.")
|
||||
}
|
||||
|
||||
// localhostLookup looks for a loopback IP by resolving localhost.
|
||||
func localhostLookup() net.IP {
|
||||
if ips, err := net.LookupIP("localhost"); err == nil && len(ips) > 0 {
|
||||
return ips[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loopbackIP returns the first loopback IP address sniffing network
|
||||
// interfaces or nil if none is found.
|
||||
func loopbackIP() net.IP {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, inf := range interfaces {
|
||||
const flagUpLoopback = net.FlagUp | net.FlagLoopback
|
||||
if inf.Flags&flagUpLoopback == flagUpLoopback {
|
||||
addrs, _ := inf.Addrs()
|
||||
for _, addr := range addrs {
|
||||
ip, _, err := net.ParseCIDR(addr.String())
|
||||
if err == nil && ip.IsLoopback() {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -18,6 +18,12 @@
|
|||
"path": "appengine_internal/base",
|
||||
"revision": ""
|
||||
},
|
||||
{
|
||||
"checksumSHA1": "ZjT4/uxN8N5WXikTtY1LdmMtL9Q=",
|
||||
"path": "camlistore.org/pkg/netutil",
|
||||
"revision": "c332b2881d09003e01491f2658ccf1dbbb006169",
|
||||
"revisionTime": "2016-06-29T15:04:51Z"
|
||||
},
|
||||
{
|
||||
"path": "context",
|
||||
"revision": ""
|
||||
|
|
Loading…
Reference in New Issue