// Expose changes the juju-managed firewall to expose any ports that
// were also explicitly marked by units as open.
359211
func (c *Client) Expose(application string) error {
	args := params.ApplicationExpose{ApplicationName: application}
	return c.facade.FacadeCall("Expose", args, nil)
}
1096732
func (api *API) AssignServerIpFirewallPolicy(server_id string, ip_id string, fp_id string) (*Server, error) {
	req := idField{fp_id}
	result := new(Server)
	url := createUrl(api, serverPathSegment, server_id, "ips", ip_id, "firewall_policy")
	err := api.Client.Put(url, &req, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	result.decodeRaws()
	return result, nil
}
1052658
func (c *client) open(rawurl, method string, in, out interface{}) (io.ReadCloser, error) {
	uri, err := url.Parse(rawurl)
	if err != nil {
		return nil, err
	}

	// creates a new http request to bitbucket.
	req, err := http.NewRequest(method, uri.String(), nil)
	if err != nil {
		return nil, err
	}

	// if we are posting or putting data, we need to
	// write it to the body of the request.
	if in != nil {
		rc, ok := in.(io.ReadCloser)
		if ok {
			req.Body = rc
			req.Header.Set("Content-Type", "plain/text")
		} else {
			inJson, err := json.Marshal(in)
			if err != nil {
				return nil, err
			}

			buf := bytes.NewBuffer(inJson)
			req.Body = ioutil.NopCloser(buf)

			req.ContentLength = int64(len(inJson))
			req.Header.Set("Content-Length", strconv.Itoa(len(inJson)))
			req.Header.Set("Content-Type", "application/json")
		}
	}
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode > http.StatusPartialContent {
		defer resp.Body.Close()
		out, _ := ioutil.ReadAll(resp.Body)
		return nil, fmt.Errorf("client error %d: %s", resp.StatusCode, string(out))
	}
	return resp.Body, nil
}
803558
func (b *PolicyResource) Open() (io.Reader, error) {
	// Defensive copy before mutation
	pb := *b.Builder

	if b.DNSZone != nil {
		hostedZoneID := fi.StringValue(b.DNSZone.ZoneID)
		if hostedZoneID == "" {
			// Dependency analysis failure?
			return nil, fmt.Errorf("DNS ZoneID not set")
		}
		pb.HostedZoneID = hostedZoneID
	}

	policy, err := pb.BuildAWSPolicy()
	if err != nil {
		return nil, fmt.Errorf("error building IAM policy: %v", err)
	}
	j, err := policy.AsJSON()
	if err != nil {
		return nil, fmt.Errorf("error building IAM policy: %v", err)
	}
	return bytes.NewReader([]byte(j)), nil
}
320747
func (l *listenPortOpener) OpenLocalPort(lp *utilproxy.LocalPort) (utilproxy.Closeable, error) {
	return openLocalPort(lp)
}
117673
func (h *PublicPortHandler) Serve(protocol string, useTLS bool, certFile, keyFile string) error {
	logger := plog.WithFields(log.Fields{
		"portaddress": h.portAddr,
		"protocol":    protocol,
		"usetls":      useTLS,
	})

	// don't start the server if it is already running
	select {
	case <-h.cancel:
		h.cancel = make(chan struct{})
	default:
		logger.Debug("Port server is already running")
		return ErrPortServerRunning
	}

	var tlsConfig *tls.Config
	if useTLS {

		// get the certificate
		certFile, keyFile = GetCertFiles(certFile, keyFile)
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			logger.WithError(err).Debug("Could not set up certificate")
			return err
		}

		// cipher suites and tls min version change may not be needed with
		// golang 1.5:
		// https://github.com/golang/go/issues/10094
		// https://github.com/golang/go/issues/9364
		tlsConfig = &tls.Config{
			MinVersion:               utils.MinTLS("http"),
			PreferServerCipherSuites: true,
			CipherSuites:             utils.CipherSuites("http"),
			Certificates:             []tls.Certificate{cert},
		}

		logger.Debug("Set up tls certificate")
	}

	// start listening on the port with a non-tls connection
	listener, err := net.Listen("tcp", h.portAddr)
	if err != nil {
		logger.WithError(err).Debug("Could not start TCP listener")
		return err
	}

	h.wg.Add(1)
	go func() {
		logger.Info("Starting port server")
		defer logger.Debug("Port server exited")

		if protocol == "http" || protocol == "https" {
			ServeHTTP(h.cancel, h.portAddr, protocol, listener, tlsConfig, h.exports)
		} else {
			ServeTCP(h.cancel, listener, tlsConfig, h.exports)
		}
		h.wg.Done()
	}()

	return nil
}
836707
func convertFirewallServiceResponse(b []byte) ([]byte, error) {
	var raw map[string]interface{}
	if err := json.Unmarshal(b, &raw); err != nil {
		return nil, err
	}

	if _, ok := raw["firewallrule"]; ok {
		return convertFirewallServiceListResponse(b)
	}

	for _, k := range []string{"endport", "startport"} {
		if sVal, ok := raw[k].(string); ok {
			iVal, err := strconv.Atoi(sVal)
			if err != nil {
				return nil, err
			}
			raw[k] = iVal
		}
	}

	return json.Marshal(raw)
}
503316
func Open(address string) (*Connection, error) {
	c := new(Connection)
	c.Address = address
	resp, err := http.Get(c.Address + "/uptime")
	if err != nil {
		return c, err
	}
	defer resp.Body.Close()
	return c, nil
}
659416
func (m *Machine) OpenedPorts(subnetTag names.SubnetTag) (map[network.PortRange]names.UnitTag, error) {
	var results params.MachinePortsResults
	var subnetTagAsString string
	if subnetTag.Id() != "" {
		subnetTagAsString = subnetTag.String()
	}
	args := params.MachinePortsParams{
		Params: []params.MachinePorts{
			{MachineTag: m.tag.String(), SubnetTag: subnetTagAsString},
		},
	}
	err := m.st.facade.FacadeCall("GetMachinePorts", args, &results)
	if err != nil {
		return nil, err
	}
	if len(results.Results) != 1 {
		return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, result.Error
	}
	// Convert string tags to names.UnitTag before returning.
	endResult := make(map[network.PortRange]names.UnitTag)
	for _, ports := range result.Ports {
		unitTag, err := names.ParseUnitTag(ports.UnitTag)
		if err != nil {
			return nil, err
		}
		endResult[ports.PortRange.NetworkPortRange()] = unitTag
	}
	return endResult, nil
}
660099
func firewallSpec(name, target string, sourceCIDRs []string, ports protocolPorts) *compute.Firewall {
	if len(sourceCIDRs) == 0 {
		sourceCIDRs = []string{"0.0.0.0/0"}
	}
	firewall := compute.Firewall{
		// Allowed is set below.
		// Description is not set.
		Name: name,
		// Network: (defaults to global)
		// SourceTags is not set.
		TargetTags:   []string{target},
		SourceRanges: sourceCIDRs,
	}

	var sortedProtocols []string
	for protocol := range ports {
		sortedProtocols = append(sortedProtocols, protocol)
	}
	sort.Strings(sortedProtocols)

	for _, protocol := range sortedProtocols {
		allowed := compute.FirewallAllowed{
			IPProtocol: protocol,
			Ports:      ports.portStrings(protocol),
		}
		firewall.Allowed = append(firewall.Allowed, &allowed)
	}
	return &firewall
}
365399
func (ac *AMQPConnector) Open(url string, tlsConfig *tls.Config) (*amqp.Connection, *amqp.Channel, error) {
	// Connect
	// From amqp docs: DialTLS will use the provided tls.Config when it encounters an amqps:// scheme
	// and will dial a plain connection when it encounters an amqp:// scheme.
	conn, err := amqp.DialTLS(url, tlsConfig)
	if err != nil {
		return nil, nil, fmt.Errorf("Dial error: %s", err)
	}

	// Open a channel
	channel, err := conn.Channel()
	if err != nil {
		return nil, nil, fmt.Errorf("Open channel error: %s", err)
	}

	return conn, channel, nil
}
251996
func OpenPort(c *Config) (*Port, error) {
	size, par, stop := c.Size, c.Parity, c.StopBits
	if size == 0 {
		size = DefaultSize
	}
	if par == 0 {
		par = ParityNone
	}
	if stop == 0 {
		stop = Stop1
	}
	return openPort(c.Name, c.Baud, size, par, stop, c.ReadTimeout)
}
572944
func convertFirewallServiceListResponse(b []byte) ([]byte, error) {
	var rawList struct {
		Count         int                      `json:"count"`
		FirewallRules []map[string]interface{} `json:"firewallrule"`
	}

	if err := json.Unmarshal(b, &rawList); err != nil {
		return nil, err
	}

	for _, r := range rawList.FirewallRules {
		for _, k := range []string{"endport", "startport"} {
			if sVal, ok := r[k].(string); ok {
				iVal, err := strconv.Atoi(sVal)
				if err != nil {
					return nil, err
				}
				r[k] = iVal
			}
		}
	}

	return json.Marshal(rawList)
}
933409
func (container *Container) ExposePort(portMapping PortMapping) *Container {
	if container.PortMappings == nil {
		container.EmptyPortMappings()
	}

	portMappings := *container.PortMappings
	portMappings = append(portMappings, portMapping)
	container.PortMappings = &portMappings

	return container
}
480327
func (p *WebPage) Open(url string) error {
	req := map[string]interface{}{
		"ref": p.ref.id,
		"url": url,
	}
	var resp struct {
		Status string `json:"status"`
	}
	if err := p.ref.process.doJSON("POST", "/webpage/Open", req, &resp); err != nil {
		return err
	}

	if resp.Status != "success" {
		return errors.New("failed")
	}
	return nil
}
1055497
func Open(c *Config) (p Port, err error) {
	p = New()
	err = p.Open(c)
	return
}
460956
func (m *PublicPortManager) Enable(portAddr, protocol string, useTLS bool) {
	m.mu.Lock()
	defer m.mu.Unlock()

	// get the port handler or create if it doesn't exist
	h, ok := m.ports[portAddr]
	if !ok {
		h = NewPublicPortHandler(portAddr)
		m.ports[portAddr] = h
	}

	// start the port server
	if err := h.Serve(protocol, useTLS, m.certFile, m.keyFile); err != nil {
		m.onFailure(portAddr, err)
	}
}