session.py 5.01 KB
Newer Older
Michael Graff's avatar
Michael Graff committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright (C) 2009  Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Shane Kerr's avatar
Shane Kerr committed
16
17
18
19
# XXX
import pprint
from ISC.Util import hexdump

Michael Graff's avatar
Michael Graff committed
20
21
22
23
import sys
import socket
import struct

Jelte Jansen's avatar
Jelte Jansen committed
24
from ISC.CC import Message
Michael Graff's avatar
Michael Graff committed
25
26

class ProtocolError(Exception): pass
Jelte Jansen's avatar
Jelte Jansen committed
27
class NetworkError(Exception): pass
28
class SessionError(Exception): pass
Michael Graff's avatar
Michael Graff committed
29
30
31
32
33

class Session:
    def __init__(self):
        self._socket = None
        self._lname = None
Shane Kerr's avatar
Shane Kerr committed
34
        self._recvbuffer = bytearray()
Michael Graff's avatar
Michael Graff committed
35
        self._recvlength = None
Shane Kerr's avatar
Shane Kerr committed
36
        self._sendbuffer = bytearray()
Michael Graff's avatar
Michael Graff committed
37
38
        self._sequence = 1

39
40
41
        try:
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._socket.connect(tuple(['127.0.0.1', 9912]))
Michael Graff's avatar
Michael Graff committed
42

43
44
45
46
47
            self.sendmsg({ "type": "getlname" })
            msg = self.recvmsg(False)
            self._lname = msg["lname"]
            if not self._lname:
                raise ProtocolError("Could not get local name")
Shane Kerr's avatar
Shane Kerr committed
48
        except socket.error as se:
49
                raise SessionError(se)
Michael Graff's avatar
Michael Graff committed
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

    @property
    def lname(self):
        return self._lname

    def sendmsg(self, msg):
        if type(msg) == dict:
            msg = Message.to_wire(msg)
        self._socket.setblocking(1)
        self._socket.send(struct.pack("!I", len(msg)))
        self._socket.send(msg)

    def recvmsg(self, nonblock = True):
        data = self._receive_full_buffer(nonblock)
        if data:
            return Message.from_wire(data)
        return None

    def _receive_full_buffer(self, nonblock):
        if nonblock:
            self._socket.setblocking(0)
        else:
            self._socket.setblocking(1)

        if self._recvlength == None:
            length = 4
            length -= len(self._recvbuffer)
            try:
                data = self._socket.recv(length)
            except:
                return None
Jelte Jansen's avatar
Jelte Jansen committed
81
82
            if data == "": # server closed connection
                raise ProtocolError("Read of 0 bytes: connection closed")
Michael Graff's avatar
Michael Graff committed
83
84
85
86
87

            self._recvbuffer += data
            if len(self._recvbuffer) < 4:
                return None
            self._recvlength = struct.unpack('>I', self._recvbuffer)[0]
Shane Kerr's avatar
Shane Kerr committed
88
            self._recvbuffer = bytearray()
Michael Graff's avatar
Michael Graff committed
89
90
91

        length = self._recvlength - len(self._recvbuffer)
        while (length > 0):
Jelte Jansen's avatar
Jelte Jansen committed
92
93
94
95
96
97
            try:
                data = self._socket.recv(length)
            except:
                return None
            if data == "": # server closed connection
                raise ProtocolError("Read of 0 bytes: connection closed")
Michael Graff's avatar
Michael Graff committed
98
99
100
            self._recvbuffer += data
            length -= len(data)
        data = self._recvbuffer
Shane Kerr's avatar
Shane Kerr committed
101
        self._recvbuffer = bytearray()
Michael Graff's avatar
Michael Graff committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
        self._recvlength = None
        return (data)

    def _next_sequence(self):
        self._sequence += 1
        return self._sequence

    def group_subscribe(self, group, instance = "*", subtype = "normal"):
        self.sendmsg({
            "type": "subscribe",
            "group": group,
            "instance": instance,
            "subtype": subtype,
        })

    def group_unsubscribe(self, group, instance = "*"):
        self.sendmsg({
            "type": "unsubscribe",
            "group": group,
            "instance": instance,
        })

    def group_sendmsg(self, msg, group, instance = "*", to = "*"):
Jelte Jansen's avatar
Jelte Jansen committed
125
        seq = self._next_sequence()
Michael Graff's avatar
Michael Graff committed
126
127
128
129
130
131
        self.sendmsg({
            "type": "send",
            "from": self._lname,
            "to": to,
            "group": group,
            "instance": instance,
Jelte Jansen's avatar
Jelte Jansen committed
132
            "seq": seq,
Michael Graff's avatar
Michael Graff committed
133
134
            "msg": Message.to_wire(msg),
        })
Jelte Jansen's avatar
Jelte Jansen committed
135
        return seq
Michael Graff's avatar
Michael Graff committed
136
137

    def group_recvmsg(self, nonblock = True):
Jelte Jansen's avatar
Jelte Jansen committed
138
139
        env = self.recvmsg(nonblock)
        if env == None:
140
141
142
            # return none twice to match normal return value
            # (so caller won't get a type error on no data)
            return (None, None)
Jelte Jansen's avatar
Jelte Jansen committed
143
        msg = Message.from_wire(env["msg"].encode('ascii'))
Jelte Jansen's avatar
Jelte Jansen committed
144
        return (msg, env)
Michael Graff's avatar
Michael Graff committed
145

Jelte Jansen's avatar
Jelte Jansen committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    def group_reply(self, routing, msg):
        seq = self._next_sequence()
        self.sendmsg({
            "type": "send",
            "from": self._lname,
            "to": routing["from"],
            "group": routing["group"],
            "instance": routing["instance"],
            "seq": seq,
            "reply": routing["seq"],
            "msg": Message.to_wire(msg),
        })
        return seq

Michael Graff's avatar
Michael Graff committed
160
161
162
if __name__ == "__main__":
    import doctest
    doctest.testmod()