This repository has been archived by the owner on Dec 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
96 lines (77 loc) · 2.23 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bitbucket.org/evolutek/cellaserv2-protobuf"
"bytes"
"github.com/golang/protobuf/proto"
"encoding/binary"
"encoding/json"
"net"
"strings"
)
// Log utils
type connJson struct {
Addr string
}
func connToJson(conn net.Conn) []byte {
ret, _ := json.Marshal(connJson{conn.RemoteAddr().String()})
return ret
}
// connDesribe returns all the information cellaserv have on the connection
func connDescribe(conn net.Conn) string {
if name, ok := connNameMap[conn]; ok {
return name
}
services, ok := servicesConn[conn]
if !ok {
// This connection is not associated with a service
return conn.RemoteAddr().String()
}
var servcs []string
for _, srvc := range services {
servcs = append(servcs, srvc.Name)
}
return strings.Join(servcs, ", ")
}
// Send utils
func sendReply(conn net.Conn, req *cellaserv.Request, data []byte) {
rep := &cellaserv.Reply{Id: req.Id, Data: data}
repBytes, err := proto.Marshal(rep)
if err != nil {
log.Error("[Message] Could not marshal outgoing reply")
}
msgType := cellaserv.Message_Reply
msg := &cellaserv.Message{Type: &msgType, Content: repBytes}
sendMessage(conn, msg)
}
func sendReplyError(conn net.Conn, req *cellaserv.Request, err_t cellaserv.Reply_Error_Type) {
err := &cellaserv.Reply_Error{Type: &err_t}
reply := &cellaserv.Reply{Error: err, Id: req.Id}
replyBytes, _ := proto.Marshal(reply)
msgType := cellaserv.Message_Reply
msg := &cellaserv.Message{
Type: &msgType,
Content: replyBytes,
}
sendMessage(conn, msg)
}
func sendMessage(conn net.Conn, msg *cellaserv.Message) {
log.Debug("[Net] Sending message to %s", conn.RemoteAddr())
msgBytes, err := proto.Marshal(msg)
if err != nil {
log.Error("[Message] Could not marshal outgoing message")
}
dumpOutgoing(conn, msgBytes)
sendRawMessage(conn, msgBytes)
}
func sendRawMessage(conn net.Conn, msg []byte) {
// Create temporary buffer
var buf bytes.Buffer
// Write the size of the message...
binary.Write(&buf, binary.BigEndian, uint32(len(msg)))
// ...concatenate with message content
buf.Write(msg)
// Send the whole message at once (avoid race condition)
// Any IO error will be detected by the main loop trying to read from the conn
conn.Write(buf.Bytes())
}
// vim: set nowrap tw=100 noet sw=8: