File: msg.py

package info (click to toggle)
hplip 1.6.10-3etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 35,140 kB
  • ctags: 10,985
  • sloc: ansic: 48,004; cpp: 40,938; python: 29,973; xml: 14,675; sh: 9,841; perl: 4,257; makefile: 786
file content (274 lines) | stat: -rw-r--r-- 7,723 bytes parent folder | download | duplicates (2)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# -*- coding: utf-8 -*-
#
# (c) Copyright 2003-2006 Hewlett-Packard Development Company, L.P.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Author: Don Welch
#


# Std Lib
import sys, cStringIO, select, socket

# Local
from g import *
from codes import *

valid_encodings = ('', 'none', 'base64')
valid_char_encodings = ('', 'utf-8', 'latin-1')


def buildResultMessage(msg_type, payload=None, result_code=ERROR_SUCCESS, other_fields={}):
    other_fields.update({'result-code' : result_code})
    return buildMessage(msg_type, payload, other_fields)

def buildMessage(msg_type, payload=None, other_fields={}):

    if msg_type is None or not msg_type:
        raise Error(ERROR_INVALID_MSG_TYPE)

    msg = cStringIO.StringIO()
    msg.write("msg=%s\n" % msg_type.lower())

    if other_fields:
        for k in other_fields:
            msg.write('%s=%s\n' % (k, str(other_fields[k])))

    if payload is not None:
        msg.write("encoding=none\n")
        msg.write("length=%d\n" % len(str(payload)))
        msg.write("data:\n%s" % str(payload))

    return msg.getvalue()


def parseMessage(message):
    fields, data_found, data, remaining_msg = {}, False, '', ''
    msg_key_found, second_msg_key = False, False
    
    try:
        msg = cStringIO.StringIO(message)
    except TypeError:
        raise Error(ERROR_INVALID_MSG_TYPE)

    while True:
        pos = msg.tell()
        line = msg.readline().strip()

        if line == "":
            break

        if line.startswith('data:'):
            data = msg.read(fields['length']) or ''
            data_found = True
            continue

        if line.startswith('#'):
            continue

        try:
            key, value = line.split('=', 1)
            key = key.strip().lower()
        except ValueError:
            raise Error(ERROR_INVALID_MSG_TYPE)
        
        if key == 'msg':
            if msg_key_found:
                # already found, another message...
                second_msg_key = True
                break
            else:
                msg_key_found = True

        # If it looks like a number, convert it, otherwise leave it alone
        try:
            fields[key] = int(value)
        except ValueError:
            fields[key] = value
    
    if second_msg_key:
        msg.seek(pos)
        remaining_msg = msg.read() or ''

    return fields, data, remaining_msg


def sendEvent(sock, msg_type, payload=None, other_fields={}, 
              timeout=prop.read_timeout):
              
    m = buildMessage(msg_type, payload, other_fields)
    
    log.debug("Sending data on channel (%d)" % sock.fileno())
    log.debug(repr(m))

    r, w, e = select.select([], [sock], [], timeout)

    if w == []:
        raise Error(ERROR_INTERNAL)

    try:
        sock.send(m)
    except socket.error:
        log.exception()
        raise Error(ERROR_INTERNAL)


def xmitMessage(sock, msg_type, payload=None,
                 other_fields={},
                 timeout=prop.read_timeout):

    fields, data, result_code = {}, '', ERROR_INTERNAL
    
    msg_type = msg_type.lower().strip()
    m = buildMessage(msg_type, payload, other_fields)

    log.debug("(xmit) Sending data on channel (%d)" % sock.fileno())
    log.debug(repr(m))

    r, w, e = select.select([], [sock], [], timeout)

    if w == []:
        raise Error(ERROR_INTERNAL)

    try:
        sock.send(m)
    except socket.error:
        log.exception()
        raise Error(ERROR_INTERNAL)
    
    read_tries = 0
    read_flag = True
    
    while read_flag:
        remaining = ''
        read_tries += 1
        
        if read_tries > 3:
            break
        
        r, w, e = select.select([sock], [], [], timeout)
    
        if r == []:
            raise Error(ERROR_INTERNAL)
    
        m = sock.recv(prop.max_message_read)
        
        if m == '':
            continue

        log.debug("(xmit) Reading data on channel (%d)" % sock.fileno())
                
        while True:
            log.debug(repr(m))
            fields, data, remaining = parseMessage(m)
            
            try:
                result_code = fields['result-code']
            except KeyError:
                result_code = ERROR_INTERNAL
            else:
                del fields['result-code']
            
            try:
                result_msg_type = fields['msg'].lower().strip()
            except KeyError:
                result_msg_type = ''
            else:
                del fields['msg']
                
            # Found the msg we were looking for or error
            if result_msg_type == ''.join([msg_type, 'result']) or \
                result_msg_type == 'messageerror': 
                read_flag = False # exit read loop
                break
            else:
                log.debug("Ignored out of sequence message")
                
            if remaining: # more messages to look at in this read
                log.debug("Remaining message")
                m = remaining # parse remainder
            else:
                # keep reading until we find the result msg...
                break
            
            
    return fields, data, result_code


    
           
def recvMessage(sock, timeout=prop.read_timeout):
    fields, data, result_code = {}, '', ERROR_INTERNAL
    
    read_tries = 0
    read_flag = True
    
    while read_flag:
        remaining = ''
        read_tries += 1
        
        if read_tries > 3:
            break
        
        r, w, e = select.select([sock], [], [], timeout)
    
        if r == []:
            #raise Error(ERROR_INTERNAL)
            continue
    
        m = sock.recv(prop.max_message_read)
        
        if m == '':
            continue

        log.debug("(xmit) Reading data on channel (%d)" % sock.fileno())
                
        while True:
            #print "parse"
            log.debug(repr(m))
            fields, data, remaining = parseMessage(m)
            
            try:
                result_code = fields['result-code']
            except KeyError:
                result_code = ERROR_INTERNAL
            else:
                del fields['result-code']
            
            try:
                result_msg_type = fields['msg'].lower().strip()
            except KeyError:
                result_msg_type = ''
            else:
                del fields['msg']
                
            # Found the msg we were looking for or error
            #if result_msg_type == ''.join([msg_type, 'result']) or \
            if result_msg_type == 'messageerror': 
                read_flag = False # exit read loop
                break
            #else:
            #    log.debug("Ignored out of sequence message")
                
            if remaining: # more messages to look at in this read
                log.debug("Remaining message")
                m = remaining # parse remainder
            else:
                # keep reading until we find the result msg...
                break    
    
    return fields, data, result_code