// openedPortsChanged handles port change notifications
774400
func (fw *Firewaller) openedPortsChanged(machineTag names.MachineTag, subnetTag names.SubnetTag) (err error) {
	defer func() {
		if params.IsCodeNotFound(err) {
			err = nil
		}
	}()
	machined, ok := fw.machineds[machineTag]
	if !ok {
		// It is common to receive a port change notification before
		// registering the machine, so if a machine is not found in
		// firewaller's list, just skip the change.  Look up will also
		// fail if it's a manual machine.
		logger.Debugf("failed to lookup %q, skipping port change", machineTag)
		return nil
	}

	m, err := machined.machine()
	if err != nil {
		return err
	}

	ports, err := m.OpenedPorts(subnetTag)
	if err != nil {
		return err
	}

	newPortRanges := make(map[names.UnitTag]portRanges)
	for portRange, unitTag := range ports {
		unitd, ok := machined.unitds[unitTag]
		if !ok {
			// It is common to receive port change notification before
			// registering a unit. Skip handling the port change - it will
			// be handled when the unit is registered.
			logger.Debugf("failed to lookup %q, skipping port change", unitTag)
			return nil
		}
		ranges, ok := newPortRanges[unitd.tag]
		if !ok {
			ranges = make(portRanges)
			newPortRanges[unitd.tag] = ranges
		}
		ranges[portRange] = true
	}

	if !unitPortsEqual(machined.definedPorts, newPortRanges) {
		machined.definedPorts = newPortRanges
		return fw.flushMachine(machined)
	}
	return nil
}
776698
func (service *VboxPortType) IEventSourceChangedEventgetAdd(request *IEventSourceChangedEventgetAdd) (*IEventSourceChangedEventgetAddResponse, error) {
	response := new(IEventSourceChangedEventgetAddResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
989279
func (res *Resolver) RestPorts(req *restful.Request, resp *restful.Response) {
	err := resp.WriteErrorString(http.StatusNotImplemented, "To be implemented...")
	if err != nil {
		logging.Error.Println(err)
	}
}
860540
func (n *NotifyRouter) HandleKeyfamilyChanged(uid keybase1.UID) {
	if n == nil {
		return
	}

	n.G().Log.Debug("+ Sending keyfamily changed notification")
	// For all connections we currently have open...
	n.cm.ApplyAll(func(id ConnectionID, xp rpc.Transporter) bool {
		// If the connection wants the `Favorites` notification type
		if n.getNotificationChannels(id).Keyfamily {
			// In the background do...
			go func() {
				(keybase1.NotifyKeyfamilyClient{
					Cli: rpc.NewClient(xp, NewContextifiedErrorUnwrapper(n.G()), nil),
				}).KeyfamilyChanged(context.Background(), uid)
			}()
		}
		return true
	})

	n.runListeners(func(listener NotifyListener) {
		listener.KeyfamilyChanged(uid)
	})
	n.G().Log.Debug("- Sent keyfamily changed notification")
}
273204
func (r *ReporterKBPKI) OnlineStatusChanged(ctx context.Context, online bool) {
	r.onlineStatusBuffer <- online
}
791018
func (e ErrPortAlreadyAllocated) IPPort() string {
	return fmt.Sprintf("%s:%d", e.ip, e.port)
}
637769
func (inst *azureInstance) OpenPorts(ctx context.ProviderCallContext, machineId string, rules []jujunetwork.IngressRule) error {
	nsgClient := network.SecurityGroupsClient{inst.env.network}
	securityRuleClient := network.SecurityRulesClient{inst.env.network}
	primaryNetworkAddress, err := inst.primaryNetworkAddress()
	if err != nil {
		return errors.Trace(err)
	}

	securityGroupName := internalSecurityGroupName
	sdkCtx := stdcontext.Background()
	nsg, err := nsgClient.Get(sdkCtx, inst.env.resourceGroup, securityGroupName, "")
	if err != nil {
		return errorutils.HandleCredentialError(errors.Annotate(err, "querying network security group"), ctx)
	}

	var securityRules []network.SecurityRule
	if nsg.SecurityRules != nil {
		securityRules = *nsg.SecurityRules
	} else {
		nsg.SecurityRules = &securityRules
	}

	// Create rules one at a time; this is necessary to avoid trampling
	// on changes made by the provisioner. We still record rules in the
	// NSG in memory, so we can easily tell which priorities are available.
	vmName := resourceName(names.NewMachineTag(machineId))
	prefix := instanceNetworkSecurityRulePrefix(instance.Id(vmName))

	singleSourceIngressRules := explodeIngressRules(rules)
	for _, rule := range singleSourceIngressRules {
		ruleName := securityRuleName(prefix, rule)

		// Check if the rule already exists; OpenPorts must be idempotent.
		var found bool
		for _, rule := range securityRules {
			if to.String(rule.Name) == ruleName {
				found = true
				break
			}
		}
		if found {
			logger.Debugf("security rule %q already exists", ruleName)
			continue
		}
		logger.Debugf("creating security rule %q", ruleName)

		priority, err := nextSecurityRulePriority(nsg, securityRuleInternalMax+1, securityRuleMax)
		if err != nil {
			return errors.Annotatef(err, "getting security rule priority for %q", rule)
		}

		var protocol network.SecurityRuleProtocol
		switch rule.Protocol {
		case "tcp":
			protocol = network.SecurityRuleProtocolTCP
		case "udp":
			protocol = network.SecurityRuleProtocolUDP
		default:
			return errors.Errorf("invalid protocol %q", rule.Protocol)
		}

		var portRange string
		if rule.FromPort != rule.ToPort {
			portRange = fmt.Sprintf("%d-%d", rule.FromPort, rule.ToPort)
		} else {
			portRange = fmt.Sprint(rule.FromPort)
		}

		// rule has a single source CIDR
		from := rule.SourceCIDRs[0]
		securityRule := network.SecurityRule{
			SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
				Description:              to.StringPtr(rule.String()),
				Protocol:                 protocol,
				SourcePortRange:          to.StringPtr("*"),
				DestinationPortRange:     to.StringPtr(portRange),
				SourceAddressPrefix:      to.StringPtr(from),
				DestinationAddressPrefix: to.StringPtr(primaryNetworkAddress.Value),
				Access:                   network.SecurityRuleAccessAllow,
				Priority:                 to.Int32Ptr(priority),
				Direction:                network.SecurityRuleDirectionInbound,
			},
		}
		_, err = securityRuleClient.CreateOrUpdate(
			sdkCtx,
			inst.env.resourceGroup, securityGroupName, ruleName, securityRule,
		)
		if err != nil {
			return errorutils.HandleCredentialError(errors.Annotatef(err, "creating security rule for %q", ruleName), ctx)
		}
		securityRules = append(securityRules, securityRule)
	}
	return nil
}
733752
func (t *peerThunk) NotifyStatusChanged(pid peer.Identifier) {
	t.list.notifyStatusChanged(pid)

	s := t.Subscriber()
	if s != nil {
		s.NotifyStatusChanged(pid)
	}
}
802052
func (gce Connection) OpenPortsWithNamer(target string, namer FirewallNamer, rules ...network.IngressRule) error {
	if len(rules) == 0 {
		return nil
	}

	// First gather the current ingress rules.
	currentRuleSet, err := gce.firewallRules(target)
	if err != nil {
		return errors.Trace(err)
	}
	// From the input rules, compose the firewall specs we want to add.
	inputRuleSet := newRuleSetFromRules(rules...)

	// For each input rule, either create a new firewall or update
	// an existing one depending on what exists already.
	// The rules are keyed by a hash of the source CIDRs.
	var sortedKeys []string
	for key := range inputRuleSet {
		sortedKeys = append(sortedKeys, key)
	}
	sort.Strings(sortedKeys)

	allNames := currentRuleSet.allNames()

	// Get the rules by sorted key for deterministic testing.
	for _, key := range sortedKeys {
		inputFirewall := inputRuleSet[key]

		// First check to see if there's any existing firewall with the same ports as what we want.
		existingFirewall, ok := currentRuleSet.matchProtocolPorts(inputFirewall.AllowedPorts)
		if !ok {
			// If not, look for any existing firewall with the same source CIDRs.
			existingFirewall, ok = currentRuleSet.matchSourceCIDRs(inputFirewall.SourceCIDRs)
		}

		if !ok {
			// Create a new firewall.
			name, err := namer(inputFirewall, target, allNames)
			if err != nil {
				return errors.Trace(err)
			}
			allNames.Add(name)
			spec := firewallSpec(name, target, inputFirewall.SourceCIDRs, inputFirewall.AllowedPorts)
			if err := gce.raw.AddFirewall(gce.projectID, spec); err != nil {
				return errors.Annotatef(err, "opening port(s) %+v", rules)
			}
			continue
		}

		// An existing firewall exists with either same same ports or the same source
		// CIDRs as what we have been asked to open. Either way, we just need to update
		// the existing firewall.

		// Merge the ports.
		allowedPorts := existingFirewall.AllowedPorts.union(inputFirewall.AllowedPorts)

		// Merge the CIDRs
		cidrs := set.NewStrings(existingFirewall.SourceCIDRs...)
		combinedCIDRs := cidrs.Union(set.NewStrings(inputFirewall.SourceCIDRs...)).SortedValues()

		// Copy new firewall details into required firewall spec.
		spec := firewallSpec(existingFirewall.Name, target, combinedCIDRs, allowedPorts)
		if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil {
			return errors.Annotatef(err, "opening port(s) %+v", rules)
		}
	}
	return nil
}
639657
func (n *NotifyRouter) HandleTrackingChanged(uid keybase1.UID, username NormalizedUsername, isTracking bool) {
	if n == nil {
		return
	}
	arg := keybase1.TrackingChangedArg{
		Uid:        uid,
		Username:   username.String(),
		IsTracking: isTracking,
	}
	// For all connections we currently have open...
	n.cm.ApplyAll(func(id ConnectionID, xp rpc.Transporter) bool {
		// If the connection wants the `Tracking` notification type
		if n.getNotificationChannels(id).Tracking {
			// In the background do...
			go func() {
				// A send of a `TrackingChanged` RPC with the user's UID
				(keybase1.NotifyTrackingClient{
					Cli: rpc.NewClient(xp, NewContextifiedErrorUnwrapper(n.G()), nil),
				}).TrackingChanged(context.Background(), arg)
			}()
		}
		return true
	})
	n.runListeners(func(listener NotifyListener) {
		listener.TrackingChanged(uid, username)
	})
}
28165
func (u *Unit) OpenPort(protocol string, number int) error {
	return u.OpenPortOnSubnet("", protocol, number)
}
511563
func NewUnbindArgs(port int) *UnbindArgs {
	args := new(UnbindArgs)
	args.Port = port
	return args
}
58424
func (f Firewall) OpenPortsOnInstance(ctx context.ProviderCallContext, machineId string, rules []network.IngressRule) error {
	machineGroup := f.machineGroupName(machineId)
	seclist, err := f.ensureSecList(f.client.ComposeName(machineGroup))
	if err != nil {
		return errors.Trace(err)
	}
	err = f.ensureSecRules(seclist, rules)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
1114844
func (c *Client) UpdatePortForwardingRule(p *UpdatePortForwardingRuleParameter) (*PortForwardingRule, error) {
	obj, err := c.Request("updatePortForwardingRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*PortForwardingRule), err
}
1151433
func (k *KeybaseServiceBase) ReachabilityChanged(ctx context.Context,
	reachability keybase1.Reachability) error {
	k.log.CDebugf(ctx, "CheckReachability invoked: %v", reachability)
	if reachability.Reachable == keybase1.Reachable_YES {
		k.config.KBFSOps().PushConnectionStatusChange(GregorServiceName, nil)
	} else {
		k.config.KBFSOps().PushConnectionStatusChange(
			GregorServiceName, errDisconnected{})
	}
	mdServer := k.config.MDServer()
	if mdServer != nil {
		mdServer.CheckReachability(ctx)
	}
	return nil
}
1173459
func OpenPort(c *Config) (io.ReadWriteCloser, error) {
	return openPort(c.Name, c.Baud, c.ReadTimeout)
}
1200237
func (fbo *folderBranchOps) PushConnectionStatusChange(service string, newStatus error) {
	switch service {
	case KeybaseServiceName, GregorServiceName:
	default:
		return
	}

	if newStatus != nil {
		return
	}

	monitoringCh := fbo.getEditMonitoringChannel()
	if monitoringCh == nil {
		return
	}

	fbo.vlog.CLogf(
		nil, libkb.VLog1, "Asking for an edit re-init after reconnection")
	fbo.editActivity.Add(1)
	select {
	case fbo.editChannels <- editChannelActivity{nil, "", ""}:
	case <-monitoringCh:
		fbo.editActivity.Done()
		fbo.log.CDebugf(nil, "Edit monitoring stopped while trying to "+
			"ask for a re-init")
	}
}