github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/lnp2p/msg.go (about)

     1  package lnp2p
     2  
     3  import (
     4  	"github.com/mit-dci/lit/lnutil"
     5  	"github.com/mit-dci/lit/logging"
     6  )
     7  
     8  // FIXME This is a stub function that just calls out to the lnutil lib for later.
     9  func processMessage(b []byte, peer *Peer) (lnutil.LitMsg, error) {
    10  	m, err := lnutil.LitMsgFromBytes(b, peer.GetIdx())
    11  	return m, err
    12  }
    13  
    14  // Message is any kind of message that can go over the network.
    15  type Message interface {
    16  	Type() uint8
    17  	Bytes() []byte
    18  }
    19  
    20  type outgoingmsg struct {
    21  	peer       *Peer
    22  	message    *Message
    23  	finishchan *chan error
    24  }
    25  
    26  func sendMessages(queue chan outgoingmsg) {
    27  
    28  	// NOTE Should we really be using the "peermgr" for log messages here?
    29  
    30  	for {
    31  		recv := <-queue
    32  		m := *recv.message
    33  
    34  		// Sending a message with a nil peer is how we signal to "stop sending things".
    35  		if recv.peer == nil {
    36  			if recv.finishchan != nil {
    37  				*recv.finishchan <- nil
    38  			}
    39  			break
    40  		}
    41  
    42  		// Sanity check.
    43  		if recv.message == nil {
    44  			logging.Warnf("peermgr: Directed to send nil message, somehow\n")
    45  			if recv.finishchan != nil {
    46  				*recv.finishchan <- nil
    47  			}
    48  			continue
    49  		}
    50  
    51  		// Assemble the final message, with type prepended.
    52  		outbytes := m.Bytes()
    53  		buf := make([]byte, len(outbytes)+1)
    54  		buf[0] = m.Type()
    55  		copy(buf[1:], outbytes)
    56  
    57  		// Make sure the connection isn't closed.  This can happen if the message was queued but then we disconnected from the peer before it was sent.
    58  		conn := recv.peer.conn
    59  		if conn == nil {
    60  			logging.Warnf("peermgr: Tried to send message to disconnected peer %s\n", recv.peer.GetPrettyName())
    61  			if recv.finishchan != nil {
    62  				*recv.finishchan <- nil
    63  			}
    64  			continue
    65  		}
    66  
    67  		// Actually write it.
    68  		_, err := conn.Write(buf)
    69  		if err != nil {
    70  			logging.Warnf("peermgr: Error sending message to peer: %s\n", err.Error())
    71  		}
    72  
    73  		// Responses, if applicable.
    74  		if recv.finishchan != nil {
    75  			*recv.finishchan <- err
    76  		}
    77  
    78  	}
    79  
    80  	logging.Infof("peermgr: send message queue terminating")
    81  }