// OkSend is a wrap of ctx.Send with http.StatusOK
482524
func (ctx *Context) OkSend(val interface{}) error {
	return ctx.Send(http.StatusOK, val)
}
871647
func (s *Server) sendShutdownEvent() {
	s.mu.Lock()
	if s.sys == nil || s.sys.sendq == nil {
		s.mu.Unlock()
		return
	}
	subj := fmt.Sprintf(shutdownEventSubj, s.info.ID)
	sendq := s.sys.sendq
	// Stop any more messages from queueing up.
	s.sys.sendq = nil
	// Unhook all msgHandlers. Normal client cleanup will deal with subs, etc.
	s.sys.subs = nil
	s.mu.Unlock()
	// Send to the internal queue and mark as last.
	sendq <- &pubMsg{subj, _EMPTY_, nil, nil, true}
}
508201
func (p *DNSProxy) sendRefused(scopedLog *logrus.Entry, w dns.ResponseWriter, request *dns.Msg) (err error) {
	refused := new(dns.Msg)
	refused.SetRcode(request, p.rejectReply)

	if err = w.WriteMsg(refused); err != nil {
		scopedLog.WithError(err).Error("Cannot send REFUSED response")
		err = fmt.Errorf("cannot send REFUSED response: %s", err)
	}
	return err
}
1047602
func (c *Conn) seqSend(seqNr uint16) *send {
	if !seqLess(c.lastAck, seqNr) {
		// Presumably already acked.
		return nil
	}
	i := int(seqNr - c.lastAck - 1)
	if i >= len(c.unackedSends) {
		// No such send.
		return nil
	}
	return c.unackedSends[i]
}
198593
func BoxSend(db XODB, v0 pgtypes.Box) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.box_send($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
243914
func PolySend(db XODB, v0 pgtypes.Polygon) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.poly_send($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
731300
func Unknownsend(db XODB, v0 pgtypes.Unknown) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.unknownsend($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
266123
func (s *Service) Send(ctx context.Context, msg Message) {
	go func(ctx context.Context, msg Message) {
		setCurrentIdentity(ctx, &msg)

		u, err := url.Parse(s.config.GetNotificationServiceURL())
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"url": s.config.GetNotificationServiceURL(),
				"err": err,
			}, "unable to parse GetNotificationServiceURL")
		}

		cl := client.New(goaclient.HTTPClientDoer(http.DefaultClient))
		cl.Host = u.Host
		cl.Scheme = u.Scheme
		cl.SetJWTSigner(goasupport.NewForwardSigner(ctx))

		msgID := goauuid.UUID(msg.MessageID)

		resp, err := cl.SendNotify(
			goasupport.ForwardContextRequestID(ctx),
			client.SendNotifyPath(),
			&client.SendNotifyPayload{
				Data: &client.Notification{
					Type: "notifications",
					ID:   &msgID,
					Attributes: &client.NotificationAttributes{
						Type:   msg.MessageType,
						ID:     msg.TargetID,
						Custom: msg.Custom,
					},
				},
			},
		)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"message_id": msg.MessageID,
				"type":       msg.MessageType,
				"target_id":  msg.TargetID,
				"err":        err,
			}, "unable to send notification")
		} else if resp.StatusCode >= 400 {
			log.Error(ctx, map[string]interface{}{
				"status":     resp.StatusCode,
				"message_id": msg.MessageID,
				"type":       msg.MessageType,
				"target_id":  msg.TargetID,
				"err":        err,
			}, "unexpected response code")
		}
		defer rest.CloseResponse(resp)

	}(ctx, msg)
}
898728
func (nfo *info) sendCommand(conn *Connection) error {
	// Write.
	if _, err := conn.Write(nfo.msg.Serialize()); err != nil {
		Logger.Debug("Failed to send command.")
		return err
	}

	// Read - reuse input buffer.
	header := bytes.NewBuffer(make([]byte, MSG_HEADER_SIZE))
	if _, err := conn.Read(header.Bytes(), MSG_HEADER_SIZE); err != nil {
		return err
	}
	if err := binary.Read(header, binary.BigEndian, &nfo.msg.MessageHeader); err != nil {
		Logger.Debug("Failed to read command response.")
		return err
	}

	// Logger.Debug("Header Response: %v %v %v %v", t.Type, t.Version, t.Length(), t.DataLen)
	if err := nfo.msg.Resize(nfo.msg.Length()); err != nil {
		return err
	}
	_, err := conn.Read(nfo.msg.Data, len(nfo.msg.Data))
	return err
}
1099896
func (r *ReporterKBPKI) send(ctx context.Context) {
	sendTicker := time.NewTicker(reporterSendInterval)
	defer sendTicker.Stop()

	for {
		select {
		case notification, ok := <-r.notifyBuffer:
			if !ok {
				return
			}
			nt := notification.NotificationType
			st := notification.StatusCode
			// Only these notifications are used in frontend:
			// https://github.com/keybase/client/blob/0d63795105f64289ba4ef20fbefe56aad91bc7e9/shared/util/kbfs-notifications.js#L142-L154
			if nt != keybase1.FSNotificationType_REKEYING &&
				nt != keybase1.FSNotificationType_INITIALIZED &&
				nt != keybase1.FSNotificationType_CONNECTION &&
				st != keybase1.FSStatusCode_ERROR {
				continue
			}
			// Send them right away rather than staging it and waiting for the
			// ticker, since each of them can be distinct from each other.
			if err := r.config.KeybaseService().Notify(ctx,
				notification); err != nil {
				r.log.CDebugf(ctx, "ReporterDaemon: error sending "+
					"notification: %s", err)
			}
		case online, ok := <-r.onlineStatusBuffer:
			if !ok {
				return
			}
			if err := r.config.KeybaseService().NotifyOnlineStatusChanged(ctx, online); err != nil {
				r.log.CDebugf(ctx, "ReporterDaemon: error sending "+
					"NotifyOnlineStatusChanged: %s", err)
			}
		case <-sendTicker.C:
			select {
			case path, ok := <-r.notifyPathBuffer:
				if !ok {
					return
				}
				if err := r.config.KeybaseService().NotifyPathUpdated(
					ctx, path); err != nil {
					r.log.CDebugf(ctx, "ReporterDaemon: error sending "+
						"notification for path: %s", err)
				}
			default:
			}

			select {
			case status, ok := <-r.notifySyncBuffer:
				if !ok {
					return
				}
				if err := r.config.KeybaseService().NotifySyncStatus(ctx,
					status); err != nil {
					r.log.CDebugf(ctx, "ReporterDaemon: error sending "+
						"sync status: %s", err)
				}
			default:
			}

			select {
			case status, ok := <-r.notifyOverallSyncBuffer:
				if !ok {
					return
				}
				if err := r.config.KeybaseService().NotifyOverallSyncStatus(
					ctx, status); err != nil {
					r.log.CDebugf(ctx, "ReporterDaemon: error sending "+
						"overall sync status: %s", err)
				}
			default:
			}
		case <-ctx.Done():
			return
		}
	}
}
116081
func (sc *serverConn) send(m *msg) error {
	m.Magic = magicSend
	m.ExtraLen = sizeOfExtras(m.iextras)
	m.KeyLen = uint16(len(m.key))
	m.BodyLen = uint32(m.ExtraLen) + uint32(m.KeyLen) + uint32(len(m.val))
	m.Opaque = sc.opq
	sc.opq++

	// Request
	err := binary.Write(sc.buf, binary.BigEndian, m.header)
	if err != nil {
		return wrapError(StatusNetworkError, err)
	}

	for _, e := range m.iextras {
		err = binary.Write(sc.buf, binary.BigEndian, e)
		if err != nil {
			return wrapError(StatusNetworkError, err)
		}
	}

	_, err = io.WriteString(sc.buf, m.key)
	if err != nil {
		return wrapError(StatusNetworkError, err)
	}

	_, err = io.WriteString(sc.buf, m.val)
	if err != nil {
		return wrapError(StatusNetworkError, err)
	}

	// Make sure write does not block forever
	sc.conn.SetWriteDeadline(time.Now().Add(sc.config.ConnectionTimeout))
	_, err = sc.buf.WriteTo(sc.conn)
	if err != nil {
		return wrapError(StatusNetworkError, err)
	}

	return nil
}
170896
func NewSecured(s string) (secured, error) {
	var e secured
	err := e.FromString(s)
	if err != nil {
		return 0, err
	}
	return e, nil
}
312354
func (ctx *Context) OkRender(name string, val interface{}) error {
	return ctx.Render(http.StatusOK, name, val)
}
82991
func (pconn *persistentConn) requestPassive() (string, error) {
	var (
		startIdx   int
		endIdx     int
		port       int
		remoteHost string
		code       int
		msg        string
		err        error
	)

	if pconn.epsvNotSupported {
		goto PASV
	}

	// Extended PaSsiVe (same idea as PASV, but works with IPv6).
	// See http://tools.ietf.org/html/rfc2428.
	code, msg, err = pconn.sendCommand("EPSV")
	if err != nil {
		return "", err
	}

	if code != replyEnteringExtendedPassiveMode {
		pconn.debug("server doesn't support EPSV: %d-%s", code, msg)
		pconn.epsvNotSupported = true
		goto PASV
	}

	startIdx = strings.Index(msg, "|||")
	endIdx = strings.LastIndex(msg, "|")
	if startIdx == -1 || endIdx == -1 || startIdx+3 > endIdx {
		pconn.debug("failed parsing EPSV response: %s", msg)
		goto PASV
	}

	port, err = strconv.Atoi(msg[startIdx+3 : endIdx])
	if err != nil {
		pconn.debug("EPSV response didn't contain port: %s", msg)
		goto PASV
	}

	remoteHost, _, err = net.SplitHostPort(pconn.controlConn.RemoteAddr().String())
	if err != nil {
		pconn.debug("failed determining remote host: %s", err)
		goto PASV
	}

	return fmt.Sprintf("[%s]:%d", remoteHost, port), nil

PASV:
	code, msg, err = pconn.sendCommand("PASV")
	if err != nil {
		return "", err
	}

	if code != replyEnteringPassiveMode {
		return "", ftpError{code: code, msg: msg}
	}

	parseError := ftpError{
		err: fmt.Errorf("error parsing PASV response (%s)", msg),
	}

	// "Entering Passive Mode (162,138,208,11,223,57)."
	startIdx = strings.Index(msg, "(")
	endIdx = strings.LastIndex(msg, ")")
	if startIdx == -1 || endIdx == -1 || startIdx > endIdx {
		return "", parseError
	}

	addrParts := strings.Split(msg[startIdx+1:endIdx], ",")
	if len(addrParts) != 6 {
		return "", parseError
	}

	ip := net.ParseIP(strings.Join(addrParts[0:4], "."))
	if ip == nil {
		return "", parseError
	}

	port = 0
	for i, part := range addrParts[4:6] {
		portOctet, err := strconv.Atoi(part)
		if err != nil {
			return "", parseError
		}
		port |= portOctet << (byte(1-i) * 8)
	}

	return net.JoinHostPort(ip.String(), strconv.Itoa(port)), nil
}
800515
func (a *Remote) ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error {
	err := false
	if len(isError) > 0 {
		err = isError[0]
	}

	if mid <= 0 {
		return constants.ErrSessionOnNotify
	}

	switch d := v.(type) {
	case []byte:
		logger.Log.Debugf("Type=Response, ID=%d, MID=%d, Data=%dbytes",
			a.Session.ID(), mid, len(d))
	default:
		logger.Log.Infof("Type=Response, ID=%d, MID=%d, Data=%+v",
			a.Session.ID(), mid, v)
	}

	return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}, a.reply)
}
766237
func (l *Logger) ErrorD(title string, data map[string]interface{}) {
	data["title"] = title
	l.logWithLevel(Error, data)
}
493904
func (c *Client) SendEvent(event Event, opts ...interface{}) (res StatusMessageRes, err error) {
	return c.SendEvents([]Event{event}, opts...)
}