// AddPortMapping implements the NAT interface by setting up a port forwarding
// from the UPnP router to the local machine with the given ports and protocol.
340447
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>" + strings.ToUpper(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>"

	response, err := soapRequest(n.serviceURL, "AddPortMapping", message)
	if err != nil {
		return
	}

	// TODO: check response to see if the port was forwarded
	// If the port was not wildcard we don't get an reply with the port in
	// it. Not sure about wildcard yet. miniupnpc just checks for error
	// codes here.
	mappedExternalPort = externalPort
	_ = response
	return
}
585155
func (s *server) removePortForwarding() {
	forwardedPorts := s.natTraversal.ForwardedPorts()
	for _, port := range forwardedPorts {
		if err := s.natTraversal.DeletePortMapping(port); err != nil {
			srvrLog.Errorf("Unable to remove forwarding rules for "+
				"port %d: %v", port, err)
		}
	}
}
1315355
func mapAddressesByPort(subset *api.EndpointSubset, port api.EndpointPort, allAddrs map[addressKey]*api.EndpointAddress, portToAddrReadyMap map[api.EndpointPort]addressSet) {
	for k := range subset.Addresses {
		mapAddressByPort(&subset.Addresses[k], port, true, allAddrs, portToAddrReadyMap)
	}
	for k := range subset.NotReadyAddresses {
		mapAddressByPort(&subset.NotReadyAddresses[k], port, false, allAddrs, portToAddrReadyMap)
	}
}
1024736
func (s *VPCRouterSetting) AddDHCPStaticMapping(ipAddress string, macAddress string) (int, *VPCRouterDHCPStaticMappingConfig) {
	if s.DHCPStaticMapping == nil {
		s.DHCPStaticMapping = &VPCRouterDHCPStaticMapping{
			Enabled: "True",
		}
	}
	if s.DHCPStaticMapping.Config == nil {
		s.DHCPStaticMapping.Config = []*VPCRouterDHCPStaticMappingConfig{}
	}

	c := &VPCRouterDHCPStaticMappingConfig{
		IPAddress:  ipAddress,
		MACAddress: macAddress,
	}
	s.DHCPStaticMapping.Config = append(s.DHCPStaticMapping.Config, c)
	return len(s.DHCPStaticMapping.Config) - 1, c
}
932461
func (pm *PortMapper) AppendForwardingTableEntry(proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error {
	return pm.forward(iptables.Append, proto, sourceIP, sourcePort, containerIP, containerPort)
}
1090910
func networkPortMap(n *structs.NetworkResource) map[string]int {
	m := make(map[string]int, len(n.DynamicPorts)+len(n.ReservedPorts))
	for _, p := range n.ReservedPorts {
		m[p.Label] = p.Value
	}
	for _, p := range n.DynamicPorts {
		m[p.Label] = -1
	}
	return m
}
319835
func (pm *PortMapper) Unmap(host net.Addr) error {
	pm.lock.Lock()
	defer pm.lock.Unlock()

	key := getKey(host)
	data, exists := pm.currentMappings[key]
	if !exists {
		return ErrPortNotMapped
	}

	if data.userlandProxy != nil {
		data.userlandProxy.Stop()
	}

	delete(pm.currentMappings, key)

	containerIP, containerPort := getIPAndPort(data.container)
	hostIP, hostPort := getIPAndPort(data.host)
	if err := pm.DeleteForwardingTableEntry(data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
		logrus.Errorf("Error on iptables delete: %s", err)
	}

	switch a := host.(type) {
	case *net.TCPAddr:
		return pm.Allocator.ReleasePort(a.IP, "tcp", a.Port)
	case *net.UDPAddr:
		return pm.Allocator.ReleasePort(a.IP, "udp", a.Port)
	case *sctp.SCTPAddr:
		if len(a.IP) == 0 {
			return ErrSCTPAddrNoIP
		}
		return pm.Allocator.ReleasePort(a.IP[0], "sctp", a.Port)
	}
	return ErrUnknownBackendAddressType
}
1118888
func (im *IndexMappingImpl) AddDocumentMapping(doctype string, dm *DocumentMapping) {
	im.TypeMapping[doctype] = dm
}
319959
func (s *Service) AddPort(application string, portAddr string, usetls bool, protocol string, isEnabled bool) (*servicedefinition.Port, error) {
	portAddr = ScrubPortString(portAddr)
	if s.Endpoints != nil {
		//find the matching endpoint
		for i := range s.Endpoints {
			ep := &s.Endpoints[i]

			if ep.Application == application && ep.Purpose == "export" {
				var ports = make([]servicedefinition.Port, 0)
				portAddrLower := strings.ToLower(portAddr)
				for _, port := range ep.PortList {
					if strings.ToLower(port.PortAddr) != portAddrLower {
						ports = append(ports, port)
					}
				}
				port := &servicedefinition.Port{PortAddr: portAddr, Enabled: isEnabled, UseTLS: usetls, Protocol: protocol}
				ep.PortList = append(ports, *port)
				return port, nil
			}
		}
	}

	return nil, fmt.Errorf("unable to find application %s in service: %s", application, s.Name)
}
1029734
func (proxier *Proxier) addServiceOnPort(service proxy.ServicePortName, protocol v1.Protocol, proxyPort int, timeout time.Duration) (*ServiceInfo, error) {
	proxier.mu.Lock()
	defer proxier.mu.Unlock()
	return proxier.addServiceOnPortInternal(service, protocol, proxyPort, timeout)
}
1184475
func AddCompilerMappings(mappings flux.CompilerMappings, dbrpMappingSvc platform.DBRPMappingService) error {
	return mappings.Add(CompilerType, func() flux.Compiler {
		return NewCompiler(dbrpMappingSvc)
	})
}
83732
func (sw *OvsSwitch) AddHostPort(intfName string, intfNum, network int, isHostNS bool) (string, error) {
	var err error

	// some error checking
	if sw.netType != "vxlan" {
		log.Fatalf("Can not add host port to OVS type %s.", sw.netType)
	}

	ovsPortType := ""
	ovsPortName := getOvsPortName(intfName, isHostNS)
	if isHostNS {
		ovsPortType = "internal"
	} else {
		log.Infof("Host port in container name space -- ignore")
		return "", nil
	}

	portID := "host" + intfName

	// If the port already exists in OVS, remove it first
	if sw.ovsdbDriver.IsPortNamePresent(ovsPortName) {
		log.Infof("Removing existing interface entry %s from OVS", ovsPortName)

		// Delete it from ovsdb
		err := sw.ovsdbDriver.DeletePort(ovsPortName)
		if err != nil {
			log.Errorf("Error deleting port %s from OVS. Err: %v", ovsPortName, err)
		}
	}

	// Ask OVSDB driver to add the port as an access port
	err = sw.ovsdbDriver.CreatePort(ovsPortName, ovsPortType, portID, hostVLAN, 0, 0)
	if err != nil {
		log.Errorf("Error adding hostport %s to OVS. Err: %v", intfName, err)
		return "", err
	}

	// Get the openflow port number for the interface
	ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(ovsPortName)
	if err != nil {
		log.Errorf("Could not find the OVS port %s. Err: %v", intfName, err)
		return "", err
	}

	// Assign an IP based on the intfnumber
	ipStr, macStr := netutils.PortToHostIPMAC(intfNum, network)
	mac, _ := net.ParseMAC(macStr)

	portInfo := ofnet.HostPortInfo{
		PortNo:  ofpPort,
		MacAddr: mac,
		IpAddr:  ipStr,
		Kind:    "NAT",
	}
	// Add to ofnet if this is the hostNS port.
	netutils.SetInterfaceMac(intfName, macStr)
	netutils.SetInterfaceIP(intfName, ipStr)
	err = setLinkUp(intfName)

	if sw.ofnetAgent != nil {
		err = sw.ofnetAgent.AddHostPort(portInfo)
		if err != nil {
			log.Errorf("Error adding host port %s. Err: %v", intfName, err)
			return "", err
		}
	}

	log.Infof("Added host port %s to OVS switch %s.", intfName, sw.bridgeName)

	defer func() {
		if err != nil {
			sw.ovsdbDriver.DeletePort(intfName)
		}
	}()

	return ipStr, nil
}
58450
func (r *PURuntime) PortMap() map[nat.Port][]string {
	r.Lock()
	defer r.Unlock()

	if r.options != nil {
		return r.options.PortMap
	}

	return nil
}
1069869
func (u *UPnP) DeletePortMapping(port uint16) error {
	u.forwardedPortsMtx.Lock()
	defer u.forwardedPortsMtx.Unlock()

	if _, exists := u.forwardedPorts[port]; !exists {
		return fmt.Errorf("port %d is not being forwarded", port)
	}

	if err := u.device.Clear(port); err != nil {
		return err
	}

	delete(u.forwardedPorts, port)

	return nil
}
1188524
func (a *api) AddHost(config HostConfig) (*host.Host, []byte, error) {
	// if a nat is configured then we connect rpc to the nat, otherwise
	// connect to the host address.
	var rpcAddress string
	if len(config.Nat.Host) > 0 {
		rpcAddress = config.Nat.String()
	} else {
		rpcAddress = config.Address.String()
	}
	agentClient, err := a.connectAgent(rpcAddress)
	if err != nil {
		return nil, nil, err
	}

	req := agent.BuildHostRequest{
		IP:     config.Address.Host,
		Port:   config.Address.Port,
		PoolID: config.PoolID,
		Memory: config.Memory,
	}

	h, err := agentClient.BuildHost(req)
	if err != nil {
		return nil, nil, err
	}

	if len(config.Nat.Host) > 0 {
		h.NatIP = config.Nat.Host
	}

	masterClient, err := a.connectMaster()
	if err != nil {
		return nil, nil, err
	}

	var privateKey []byte
	if privateKey, err = masterClient.AddHost(*h); err != nil {
		return nil, nil, err
	}

	if host_, err := a.GetHost(h.ID); err != nil {
		return nil, nil, err
	} else {
		return host_, privateKey, nil
	}
}
1303431
func (c *Client) EnableRootMapping(
	ctx context.Context, name, user string) error {

	ex, err := c.GetExportByName(ctx, name)
	if err != nil {
		return err
	}
	if ex == nil {
		return nil
	}

	nex := &api.Export{ID: ex.ID, MapRoot: ex.MapRoot}

	setUserMapping(
		nex,
		user,
		true,
		func(e Export) UserMapping { return e.MapRoot },
		func(e Export, m UserMapping) { e.MapRoot = m })

	return api.ExportUpdate(ctx, c.API, nex)
}
901725
func (h *HAproxy) makePortmap(services map[string][]*service.Service) portmap {
	ports := make(portmap)

	for svcName, svcList := range services {
		if _, ok := ports[svcName]; !ok {
			ports[svcName] = make(portset, 5)
		}

		for _, service := range svcList {
			for _, port := range service.Ports {
				// Currently only handle TCP, and we skip ports that aren't exported.
				// That's the effect of not specifying a ServicePort.
				if port.Type == "tcp" && port.ServicePort != 0 {
					svcPort := strconv.FormatInt(port.ServicePort, 10)
					internalPort := strconv.FormatInt(port.Port, 10)
					ports[svcName][svcPort] = internalPort
				}
			}
		}
	}

	return ports
}