// ServeMessage implements httpu.Handler, and uses SSDP NOTIFY requests to
// maintain the registry of devices and services.
160796
func (reg *Registry) ServeMessage(r *http.Request) {
	if r.Method != methodNotify {
		return
	}

	nts := r.Header.Get("nts")

	switch nts {
	case ntsAlive:
		reg.handleNTSAlive(r)
	case ntsUpdate:
		reg.handleNTSUpdate(r)
	case ntsByebye:
		reg.handleNTSByebye(r)
	}
}
1154581
func (pl *Payload) BuildMessage() ([]byte, error) {
	plBuf, err := pl.Encode()
	if err != nil {
		return nil, fmt.Errorf("unable to encode payload: %s", err)
	}

	meta := &Meta{Size: uint32(len(plBuf))}
	metaBuf, err := meta.MarshalBinary()
	if err != nil {
		return nil, fmt.Errorf("unable to encode metadata: %s", err)
	}

	return append(metaBuf, plBuf...), nil
}
1358404
func (cli *Client) handleMessage(topicName, message []byte) {
	// Get the string of the Topic Name.
	topicNameStr := string(topicName)

	for topicFilter, handler := range cli.conn.ackedSubs {
		if handler == nil || !match(topicNameStr, topicFilter) {
			continue
		}

		// Execute the handler.
		go handler(topicName, message)
	}
}
364714
func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {

	response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
	if err != nil {
		return
	}

	err = unmarshal(response, &st)
	return
}
1068132
func (f NotifyHandlerFunc) ServeNotify(r Request, n Notifier) {
	f(r, n)
}
643582
func (gw *Gateway) SendMessage(
	rmsg *config.Message,
	dest *bridge.Bridge,
	channel *config.ChannelInfo,
	canonicalParentMsgID string,
) (string, error) {
	msg := *rmsg
	// Only send the avatar download event to ourselves.
	if msg.Event == config.EventAvatarDownload {
		if channel.ID != getChannelID(rmsg) {
			return "", nil
		}
	} else {
		// do not send to ourself for any other event
		if channel.ID == getChannelID(rmsg) {
			return "", nil
		}
	}

	// Too noisy to log like other events
	if msg.Event != config.EventUserTyping {
		gw.logger.Debugf("=> Sending %#v from %s (%s) to %s (%s)", msg, msg.Account, rmsg.Channel, dest.Account, channel.Name)
	}

	msg.Channel = channel.Name
	msg.Avatar = gw.modifyAvatar(rmsg, dest)
	msg.Username = gw.modifyUsername(rmsg, dest)

	msg.ID = gw.getDestMsgID(rmsg.Protocol+" "+rmsg.ID, dest, channel)

	// for api we need originchannel as channel
	if dest.Protocol == apiProtocol {
		msg.Channel = rmsg.Channel
	}

	msg.ParentID = gw.getDestMsgID(rmsg.Protocol+" "+canonicalParentMsgID, dest, channel)
	if msg.ParentID == "" {
		msg.ParentID = canonicalParentMsgID
	}

	// if the parentID is still empty and we have a parentID set in the original message
	// this means that we didn't find it in the cache so set it "msg-parent-not-found"
	if msg.ParentID == "" && rmsg.ParentID != "" {
		msg.ParentID = "msg-parent-not-found"
	}

	err := gw.modifySendMessageTengo(rmsg, &msg, dest)
	if err != nil {
		gw.logger.Errorf("modifySendMessageTengo: %s", err)
	}

	// if we are using mattermost plugin account, send messages to MattermostPlugin channel
	// that can be picked up by the mattermost matterbridge plugin
	if dest.Account == "mattermost.plugin" {
		gw.Router.MattermostPlugin <- msg
	}

	mID, err := dest.Send(msg)
	if err != nil {
		return mID, err
	}

	// append the message ID (mID) from this bridge (dest) to our brMsgIDs slice
	if mID != "" {
		gw.logger.Debugf("mID %s: %s", dest.Account, mID)
		return mID, nil
		//brMsgIDs = append(brMsgIDs, &BrMsgID{dest, dest.Protocol + " " + mID, channel.ID})
	}
	return "", nil
}
669197
func (s *server) BroadcastMessage(msg wire.Message, exclPeers ...*serverPeer) {
	// XXX: Need to determine if this is an alert that has already been
	// broadcast and refrain from broadcasting again.
	bmsg := broadcastMsg{message: msg, excludePeers: exclPeers}
	s.broadcast <- bmsg
}
973874
func serveListener(path string) (net.Listener, error) {
	if path == "" {
		return nil, errors.New("'socket' must be npipe path")
	}
	l, err := winio.ListenPipe(path, nil)
	if err != nil {
		return nil, err
	}
	logrus.WithField("socket", path).Debug("serving api on npipe socket")
	return l, nil
}
661749
func (bh *Handler) ProcessMessage(msg *cb.Envelope, addr string) (resp *ab.BroadcastResponse) {
	tracker := &MetricsTracker{
		ChannelID: "unknown",
		TxType:    "unknown",
		Metrics:   bh.Metrics,
	}
	defer func() {
		// This looks a little unnecessary, but if done directly as
		// a defer, resp gets the (always nil) current state of resp
		// and not the return value
		tracker.Record(resp)
	}()
	tracker.BeginValidate()

	chdr, isConfig, processor, err := bh.SupportRegistrar.BroadcastChannelSupport(msg)
	if chdr != nil {
		tracker.ChannelID = chdr.ChannelId
		tracker.TxType = cb.HeaderType(chdr.Type).String()
	}
	if err != nil {
		logger.Warningf("[channel: %s] Could not get message processor for serving %s: %s", tracker.ChannelID, addr, err)
		return &ab.BroadcastResponse{Status: cb.Status_BAD_REQUEST, Info: err.Error()}
	}

	if !isConfig {
		logger.Debugf("[channel: %s] Broadcast is processing normal message from %s with txid '%s' of type %s", chdr.ChannelId, addr, chdr.TxId, cb.HeaderType_name[chdr.Type])

		configSeq, err := processor.ProcessNormalMsg(msg)
		if err != nil {
			logger.Warningf("[channel: %s] Rejecting broadcast of normal message from %s because of error: %s", chdr.ChannelId, addr, err)
			return &ab.BroadcastResponse{Status: ClassifyError(err), Info: err.Error()}
		}
		tracker.EndValidate()

		tracker.BeginEnqueue()
		if err = processor.WaitReady(); err != nil {
			logger.Warningf("[channel: %s] Rejecting broadcast of message from %s with SERVICE_UNAVAILABLE: rejected by Consenter: %s", chdr.ChannelId, addr, err)
			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
		}

		err = processor.Order(msg, configSeq)
		if err != nil {
			logger.Warningf("[channel: %s] Rejecting broadcast of normal message from %s with SERVICE_UNAVAILABLE: rejected by Order: %s", chdr.ChannelId, addr, err)
			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
		}
	} else { // isConfig
		logger.Debugf("[channel: %s] Broadcast is processing config update message from %s", chdr.ChannelId, addr)

		config, configSeq, err := processor.ProcessConfigUpdateMsg(msg)
		if err != nil {
			logger.Warningf("[channel: %s] Rejecting broadcast of config message from %s because of error: %s", chdr.ChannelId, addr, err)
			return &ab.BroadcastResponse{Status: ClassifyError(err), Info: err.Error()}
		}
		tracker.EndValidate()

		tracker.BeginEnqueue()
		if err = processor.WaitReady(); err != nil {
			logger.Warningf("[channel: %s] Rejecting broadcast of message from %s with SERVICE_UNAVAILABLE: rejected by Consenter: %s", chdr.ChannelId, addr, err)
			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
		}

		err = processor.Configure(config, configSeq)
		if err != nil {
			logger.Warningf("[channel: %s] Rejecting broadcast of config message from %s with SERVICE_UNAVAILABLE: rejected by Configure: %s", chdr.ChannelId, addr, err)
			return &ab.BroadcastResponse{Status: cb.Status_SERVICE_UNAVAILABLE, Info: err.Error()}
		}
	}

	logger.Debugf("[channel: %s] Broadcast has successfully enqueued message of type %s from %s", chdr.ChannelId, cb.HeaderType_name[chdr.Type], addr)

	return &ab.BroadcastResponse{Status: cb.Status_SUCCESS}
}
247256
func (mr *MockAgentMockRecorder) HandleMessage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleMessage", reflect.TypeOf((*MockAgent)(nil).HandleMessage), arg0, arg1, arg2, arg3, arg4)
}
233044
func (sys *NotificationSys) SignalService(sig serviceSignal) []NotificationPeerErr {
	ng := WithNPeers(len(sys.peerClients))
	for idx, client := range sys.peerClients {
		if client == nil {
			continue
		}
		client := client
		ng.Go(context.Background(), func() error {
			return client.SignalService(sig)
		}, idx, *client.host)
	}
	return ng.Wait()
}
880237
func (s *sessionUDP) controlMessage(src *net.UDPAddr) []byte {
	// If the src is definitely an IPv6, then use ipv6's ControlMessage to
	// respond otherwise use ipv4's because ipv6's marshal ignores ipv4
	// addresses.
	if src.IP.To4() == nil {
		cm := new(ipv6.ControlMessage)
		cm.Src = src.IP
		return cm.Marshal()
	}
	cm := new(ipv4.ControlMessage)
	cm.Src = src.IP
	return cm.Marshal()
}
1331084
func ServeListener(listener net.Listener) {
	DefaultMux.Compile()
	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("Goji received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("Goji stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
99761
func NewMessageHandler(out chan *ReceivedMessage, verifyIPs bool) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		if verifyIPs {
			// Check if the request came from Nexmo
			host, _, err := net.SplitHostPort(req.RemoteAddr)
			if !IsTrustedIP(host) || err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
		}

		var err error

		// Check if the query is empty. If it is, it's just Nexmo
		// making sure our service is up, so we don't want to return
		// an error.
		if req.URL.RawQuery == "" {
			return
		}

		req.ParseForm()
		// Decode the form data
		m := new(ReceivedMessage)
		switch req.FormValue("type") {
		case "text":
			m.Text, err = url.QueryUnescape(req.FormValue("text"))
			if err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			m.Type = TextMessage
		case "unicode":
			m.Text, err = url.QueryUnescape(req.FormValue("text"))
			if err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			m.Type = UnicodeMessage

			// TODO: I have no idea if this data stuff works, as I'm unable to
			// send data SMS messages.
		case "binary":
			data, err := url.QueryUnescape(req.FormValue("data"))
			if err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			m.Data = []byte(data)

			udh, err := url.QueryUnescape(req.FormValue("udh"))
			if err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			m.UDH = []byte(udh)
			m.Type = BinaryMessage

		default:
			//error
			http.Error(w, "", http.StatusInternalServerError)
			return
		}

		m.To = req.FormValue("to")
		m.MSISDN = req.FormValue("msisdn")
		m.NetworkCode = req.FormValue("network-code")
		m.ID = req.FormValue("messageId")

		m.Keyword = req.FormValue("keyword")
		t, err := url.QueryUnescape(req.FormValue("message-timestamp"))
		if err != nil {
			http.Error(w, "", http.StatusInternalServerError)
			return
		}

		// Convert the timestamp to a time.Time.
		timestamp, err := time.Parse("2006-01-02 15:04:05", t)
		if err != nil {
			http.Error(w, "", http.StatusInternalServerError)
			return
		}

		m.Timestamp = timestamp

		// TODO: I don't know if this works as I've been unable to send an SMS
		// message longer than 160 characters that doesn't get concatenated
		// automatically.
		if req.FormValue("concat") == "true" {
			m.Concatenated = true
			m.Concat.Reference = req.FormValue("concat-ref")
			m.Concat.Total, err = strconv.Atoi(req.FormValue("concat-total"))
			if err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			m.Concat.Part, err = strconv.Atoi(req.FormValue("concat-part"))
			if err != nil {
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
		}

		// Pass it out on the chan
		out <- m
	}

}
911556
func (router *Router) processMessage(conn *Connection, in []byte) {
	if name, data, err := router.protocol.Unpack(in); err == nil {
		if callback, ok := router.callbacks[name]; ok {
			callback(conn, data)
		}
	} // TODO: else error logging?

	defer recover()
}
920758
func (s *ServerStream) SendMessage(ctx context.Context, msg *StreamMessage) error {
	return s.stream.SendMessage(ctx, msg)
}
709631
func (rm *RegistryMessage) ValidateMessage() bool {
	return rm.RouteServiceURL == "" || strings.HasPrefix(rm.RouteServiceURL, "https")
}