File: hpssd.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 (1551 lines) | stat: -rwxr-xr-x 52,022 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
#!/usr/bin/env python
# -*- 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
#
# Authors: Don Welch, Pete Parks
#
# Thanks to Henrique M. Holschuh <hmh@debian.org> for various security patches
#
# ======================================================================
# Async code is Copyright 1996 by Sam Rushing
#
#                         All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Sam
# Rushing not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
#
# SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, 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.
# ======================================================================
#


__version__ = '7.5'
__title__ = "Services and Status Daemon"
__doc__ = "Provides various services to HPLIP client applications."


# Std Lib
import sys, socket, os, os.path, signal, getopt, glob, time, select
import popen2, threading, gettext, re, xml.parsers.expat, fcntl
import cStringIO, pwd

from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
     ENOTCONN, ESHUTDOWN, EINTR, EISCONN

# Local
from base.g import *
from base.codes import *
from base.msg import *
from base import utils, slp, device
from base.strings import string_table

# CUPS support
from prnt import cups

# Per user alert settings
alerts = {}

# Fax temp files
fax_file = {}


class ServerDevice(object):
    def __init__(self, model=''):
        self.history = utils.RingBuffer(prop.history_size)
        self.model = device.normalizeModelName(model)
        self.cache = {}
       

# Active devices - to hold event history
devices = {} # { 'device_uri' : ServerDevice, ... }

# Cache for model query data
model_cache = {} # { 'model_name'(lower) : {mq}, ...}

inter_pat = re.compile(r"""%(.*)%""", re.IGNORECASE)
direct_pat = re.compile(r'direct (.*?) "(.*?)" "(.*?)" "(.*?)"', re.IGNORECASE)

def QueryString(id, typ=0):
    id = str(id)
    try:
        s = string_table[id][typ]
    except KeyError:
        log.debug("String %s not found" % id)
        raise Error(ERROR_STRING_QUERY_FAILED)

    if type(s) == type(''):
        return s

    try:
        return s()
    except:
        raise Error(ERROR_STRING_QUERY_FAILED)



def initStrings():
    cycles = 0

    while True:

        found = False

        for s in string_table:
            short_string, long_string = string_table[s]
            short_replace, long_replace = short_string, long_string

            try:
                short_match = inter_pat.match(short_string).group(1)
            except (AttributeError, TypeError):
                short_match = None

            if short_match is not None:
                found = True

                try:
                    short_replace, dummy = string_table[short_match]
                except KeyError:
                    log.error("String interpolation error: %s" % short_match)

            try:
                long_match = inter_pat.match(long_string).group(1)
            except (AttributeError, TypeError):
                long_match = None

            if long_match is not None:
                found = True

                try:
                    dummy, long_replace = string_table[long_match]
                except KeyError:
                    log.error("String interpolation error: %s" % long_match)

            if found:
                string_table[s] = (short_replace, long_replace)

        if not found:
            break
        else:
            cycles +=1
            if cycles > 1000:
                break
                

class ModelParser:
    def __init__(self):
        self.model = {}
        self.cur_model = None
        self.stack = []
        self.model_found = False

    def startElement(self, name, attrs):
        global models

        if name in ('id', 'models'):
            return

        elif name == 'model':
            #self.model = {}
            self.cur_model = str(attrs['name']).lower()
            if self.cur_model == self.model_name:
                #log.debug( "Model found." )
                self.model_found = True
                self.stack = []
            else:
                self.cur_model = None

        elif self.cur_model is not None:
            self.stack.append(str(name).lower())

            if len(attrs):
                for a in attrs:
                    self.stack.append(str(a).lower())

                    try:
                        i = int(attrs[a])
                    except ValueError:
                        i = str(attrs[a])

                    self.model[str('-'.join(self.stack))] = i
                    self.stack.pop()

    def endElement(self, name):
        global models
        if name == 'model':
            pass
        elif name in ('id', 'models'):
            return
        else:
            if self.cur_model is not None:
                self.stack.pop()


    def charData(self, data):
        data = str(data).strip()

        if data and self.model is not None and \
            self.cur_model is not None and \
            self.stack:

            try:
                i = int(data)
            except ValueError:
                i = str(data)

            self.model[str('-'.join(self.stack))] = i

    def parseModels(self, model_name):
        self.model_name = model_name

        for g in [prop.xml_dir, os.path.join(prop.xml_dir, 'unreleased')]:

            if os.path.exists(g):
                log.debug("Searching directory: %s" % g)

                for f in glob.glob(g + "/*.xml"):
                    log.debug("Searching file: %s" % f)
                    parser = xml.parsers.expat.ParserCreate()
                    parser.StartElementHandler = self.startElement
                    parser.EndElementHandler = self.endElement
                    parser.CharacterDataHandler = self.charData
                    parser.Parse(open(f).read(), True)

                    if self.model_found:
                        log.debug("Found")
                        return self.model

        #log.error("Not found")
        raise Error(ERROR_UNSUPPORTED_MODEL)



def QueryModel(model_name):
    model_name = device.normalizeModelName(model_name).lower()
    log.debug("Query model: %s" % model_name)

    if model_name in model_cache:
        return model_cache[model_name]

    try:
        mq = ModelParser().parseModels(model_name)
    except Error:
        mq = {}
    
    model_cache[model_name] = mq
    
    return mq
    

socket_map = {}
loopback_trigger = None

def loop( timeout=1.0, sleep_time=0.1 ):
    while socket_map:
        r = []; w = []; e = []
        for fd, obj in socket_map.items():
            if obj.readable():
                r.append( fd )
            if obj.writable():
                w.append( fd )
        if [] == r == w == e:
            time.sleep( timeout )
        else:
            try:
                r,w,e = select.select( r, w, e, timeout )
            except select.error, err:
                if err[0] != EINTR:
                    raise Error( ERROR_INTERNAL )
                r = []; w = []; e = []

        for fd in r:
            try:
                obj = socket_map[ fd ]
            except KeyError:
                continue

            try:
                obj.handle_read_event()
            except Error, e:
                obj.handle_error( e )

        for fd in w:
            try:
                obj = socket_map[ fd ]
            except KeyError:
                continue

            try:
                obj.handle_write_event()
            except Error, e:
                obj.handle_error( e )

            time.sleep( sleep_time )


class dispatcher:
    connected = False
    accepting = False
    closing = False
    addr = None

    def __init__ (self, sock=None ):
        self.typ = ''
        self.send_events = False
        self.username = ''
        
        if sock:
            self.set_socket( sock ) 
            self.socket.setblocking( 0 )
            self.connected = True
            try:
                self.addr = sock.getpeername()
            except socket.error:
                # The addr isn't crucial
                pass
        else:
            self.socket = None

    def add_channel ( self ): 
        global socket_map
        socket_map[ self._fileno ] = self

    def del_channel( self ): 
        global socket_map
        fd = self._fileno
        if socket_map.has_key( fd ):
            del socket_map[ fd ]

    def create_socket( self, family, type ):
        self.family_and_type = family, type
        self.socket = socket.socket (family, type)
        self.socket.setblocking( 0 )
        self._fileno = self.socket.fileno()
        self.add_channel()

    def set_socket( self, sock ): 
        self.socket = sock
        self._fileno = sock.fileno()
        self.add_channel()

    def set_reuse_addr( self ):
        try:
            self.socket.setsockopt (
                socket.SOL_SOCKET, socket.SO_REUSEADDR,
                self.socket.getsockopt (socket.SOL_SOCKET,
                                        socket.SO_REUSEADDR) | 1
                )
        except socket.error:
            pass

    def readable (self):
        return True

    def writable (self):
        return True

    def listen (self, num):
        self.accepting = True
        return self.socket.listen( num )

    def bind( self, addr ):
        self.addr = addr
        return self.socket.bind( addr )

    def connect( self, address ):
        self.connected = False
        err = self.socket.connect_ex( address )
        if err in ( EINPROGRESS, EALREADY, EWOULDBLOCK ):
            return
        if err in (0, EISCONN):
            self.addr = address
            self.connected = True
            self.handle_connect()
        else:
            raise socket.error, err

    def accept (self):
        try:
            conn, addr = self.socket.accept()
            return conn, addr
        except socket.error, why:
            if why[0] == EWOULDBLOCK:
                pass
            else:
                raise socket.error, why

    def send (self, data):
        try:
            result = self.socket.send( data )
            return result
        except socket.error, why:
            if why[0] == EWOULDBLOCK:
                return 0
            else:
                raise socket.error, why
            return 0

    def recv( self, buffer_size ):
        try:
            data = self.socket.recv (buffer_size)
            if not data:
                self.handle_close()
                return ''
            else:
                return data
        except socket.error, why:
            if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
                self.handle_close()
                return ''
            else:
                raise socket.error, why

    def close (self):
        self.del_channel()
        self.socket.close()

    # cheap inheritance, used to pass all other attribute
    # references to the underlying socket object.
    #def __getattr__ (self, attr):
    #    return getattr (self.socket, attr)

    def handle_read_event( self ):
        if self.accepting:
            if not self.connected:
                self.connected = True
            self.handle_accept()
        elif not self.connected:
            self.handle_connect()
            self.connected = True
            self.handle_read()
        else:
            self.handle_read()

    def handle_write_event( self ):
        if not self.connected:
            self.handle_connect()
            self.connected = True
        self.handle_write()

    def handle_expt_event( self ):
        self.handle_expt()

    def handle_error( self, e ):
        log.error( "Error processing request." )
        raise Error(ERROR_INTERNAL)

    def handle_expt( self ):
        raise Error

    def handle_read( self ):
        raise Error

    def handle_write( self ):
        raise Error

    def handle_connect( self ):
        raise Error

    def handle_accept( self ):
        raise Error

    def handle_close( self ):
        self.close()


class file_wrapper:
    def __init__(self, fd):
        self.fd = fd

    def recv(self, *args):
        return os.read(self.fd, *args)

    def send(self, *args):
        return os.write(self.fd, *args)

    read = recv
    write = send

    def close(self):
        os.close(self.fd)

    def fileno(self):
        return self.fd


class file_dispatcher(dispatcher):

    def __init__(self, fd):
        dispatcher.__init__(self, None)
        self.connected = True
        self.set_file(fd)
        flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
        flags = flags | os.O_NONBLOCK
        fcntl.fcntl(fd, fcntl.F_SETFL, flags)

    def set_file(self, fd):
        self._fileno = fd
        self.socket = file_wrapper(fd)
        self.add_channel()    


class trigger(file_dispatcher):
        def __init__(self):
            r, w = os.pipe()
            self.trigger = w
            file_dispatcher.__init__(self, r)
            self.send_events = False
            self.typ = 'trigger'

        def readable(self):
            return True

        def writable(self):
            return False

        def handle_connect(self):
            pass

        def pull_trigger(self):
            os.write(self.trigger, '.')

        def handle_read (self):
            self.recv(8192)


class hpssd_server(dispatcher):
    def __init__(self, ip, port):
        self.ip = ip
        self.send_events = False
        

        if port != 0:
            self.port = port
        else:
            self.port = socket.htons(0)

        dispatcher.__init__(self)
        self.typ = 'server'
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()

        try:
            self.bind((ip, port))
        except socket.error:
            raise Error(ERROR_UNABLE_TO_BIND_SOCKET)

        prop.hpssd_port = self.port = self.socket.getsockname()[1]
        self.listen(5)


    def writable(self):
        return False

    def readable(self):
        return self.accepting

    def handle_accept(self):
        try:
            conn, addr = self.accept()
            log.debug("Connected to client: %s:%d (%d)" % (addr[0], addr[1], self._fileno))
        except socket.error:
            log.error("Socket error on accept()")
            return
        except TypeError:
            log.error("EWOULDBLOCK exception on accept()")
            return
        handler = hpssd_handler(conn, addr, self)

    def handle_close(self):
        dispatcher.handle_close(self)


class hpssd_handler(dispatcher):
    def __init__(self, conn, addr, server):
        dispatcher.__init__(self, sock=conn)
        self.addr = addr
        self.in_buffer = ''
        self.out_buffer = ''
        self.server = server
        self.fields = {}
        self.payload = ''
        self.signal_exit = False
        self.typ = ''
        self.send_events = False 
        self.username = ''
        
        # handlers for all the messages we expect to receive
        self.handlers = {
            # Request/Reply Messages
            'probedevicesfiltered' : self.handle_probedevicesfiltered,
            'setalerts'            : self.handle_setalerts,
            'testemail'            : self.handle_test_email,
            'querymodel'           : self.handle_querymodel, # By device URI
            'modelquery'           : self.handle_modelquery, # By model (backwards compatibility)
            'queryhistory'         : self.handle_queryhistory,
            'querystring'          : self.handle_querystring,
            'setvalue'             : self.handle_setvalue, # device cache
            'getvalue'             : self.handle_getvalue, # device cache
            'injectvalue'          : self.handle_injectvalue, # model query data (debugging use)

            # Event Messages (no reply message)
            'event'                : self.handle_event,
            'registerguievent'     : self.handle_registerguievent, # register for events
            'unregisterguievent'   : self.handle_unregisterguievent,
            'exitevent'            : self.handle_exit,

            # Fax
            'hpfaxbegin'           : self.handle_hpfaxbegin,
            'hpfaxdata'            : self.handle_hpfaxdata,
            'hpfaxend'             : self.handle_hpfaxend,
            'faxgetdata'           : self.handle_faxgetdata,
            
            # Misc
            'unknown'              : self.handle_unknown,
        }


    def handle_read(self):
        log.debug("Reading data on channel (%d)" % self._fileno)
        self.in_buffer = self.recv(prop.max_message_read)

        log.debug(repr(self.in_buffer))

        if not self.in_buffer:
            return False

        remaining_msg = self.in_buffer

        while True:
            try:
                self.fields, self.payload, remaining_msg = parseMessage(remaining_msg)
            except Error, e:
                err = e.opt
                log.warn("Message parsing error: %s (%d)" % (e.msg, err))
                self.out_buffer = self.handle_unknown(err)
                log.debug(self.out_buffer)
                return True

            msg_type = self.fields.get('msg', 'unknown').lower()
            log.debug("Handling: %s %s %s" % ("*"*20, msg_type, "*"*20))
            log.debug(repr(self.in_buffer))

            try:
                self.handlers.get(msg_type, self.handle_unknown)()
            except Error:
                log.error("Unhandled exception during processing:")
                log.exception()

            try:
                self.handle_write()
            except socket.error, why:
                log.error("Socket error: %s" % why)
            
            if not remaining_msg:
                break

        return True

    def handle_unknown(self, err=ERROR_INVALID_MSG_TYPE):
        pass


    def handle_write(self):
        if not self.out_buffer:
            return

        log.debug("Sending data on channel (%d)" % self._fileno)
        log.debug(repr(self.out_buffer))
        
        while self.out_buffer:
            sent = self.send(self.out_buffer)
            self.out_buffer = self.out_buffer[sent:]

        if self.signal_exit:
            self.handle_close()


    def __checkdevice(self, device_uri):
        try:
            devices[device_uri]
        except KeyError:
            log.debug("New device: %s" % device_uri)
            try:
                back_end, is_hp, bus, model, serial, dev_file, host, port = \
                    device.parseDeviceURI(device_uri)
            except Error:
                log.error("Invalid device URI")
                return ERROR_INVALID_DEVICE_URI

            devices[device_uri] = ServerDevice(model)
        
        return ERROR_SUCCESS
            

    def handle_getvalue(self):
        device_uri = self.fields.get('device-uri', '').replace('hpfax:', 'hp:')
        value = ''
        key = self.fields.get('key', '')
        result_code = self.__checkdevice(device_uri)
        
        if result_code == ERROR_SUCCESS:
            try:
                value = devices[device_uri].cache[key]
            except KeyError:
                value, result_code = '', ERROR_INTERNAL
            
        self.out_buffer = buildResultMessage('GetValueResult', value, result_code)
        
    def handle_setvalue(self):
        device_uri = self.fields.get('device-uri', '').replace('hpfax:', 'hp:')
        key = self.fields.get('key', '')
        value = self.fields.get('value', '')
        result_code = self.__checkdevice(device_uri)
        
        if result_code == ERROR_SUCCESS:    
            devices[device_uri].cache[key] = value
        
        self.out_buffer = buildResultMessage('SetValueResult', None, ERROR_SUCCESS)
        
    def handle_queryhistory(self):
        device_uri = self.fields.get('device-uri', '').replace('hpfax:', 'hp:')
        payload = ''
        result_code = self.__checkdevice(device_uri)

        if result_code == ERROR_SUCCESS:    
            for h in devices[device_uri].history.get():
                payload = '\n'.join([payload, ','.join([str(x) for x in h])])

        self.out_buffer = buildResultMessage('QueryHistoryResult', payload, result_code)

    def handle_querymodel(self): # By device URI (used by toolbox, info, etc)
        device_uri = self.fields.get('device-uri', '').replace('hpfax:', 'hp:')
        result_code = self.__checkdevice(device_uri)
        mq = {}
        
        if result_code == ERROR_SUCCESS:    
            try:
                back_end, is_hp, bus, model, \
                    serial, dev_file, host, port = \
                    device.parseDeviceURI(device_uri)
            except Error:
                result_code = e.opt
            else:
                try:
                    mq = QueryModel(model)
                except Error, e:
                    mq = {}
                    result_code = e.opt
    
        self.out_buffer = buildResultMessage('QueryModelResult', None, result_code, mq)


    def handle_modelquery(self): # By model (used by hp: backend)
        model = self.fields.get('model', '')
        result_code = ERROR_SUCCESS

        try:
            mq = QueryModel(model)
        except Error, e:
            mq = {}
            result_code = e.opt

        self.out_buffer = buildResultMessage('ModelQueryResult', None, result_code, mq)

    def handle_injectvalue(self): # Tweak MQ values at runtime
        device_uri = self.fields.get('device-uri', '').replace('hpfax:', 'hp:')
        model = self.fields.get('model', '')
        result_code = ERROR_INTERNAL
        
        if not model and device_uri:
            try:
                back_end, is_hp, bus, model, \
                    serial, dev_file, host, port = \
                    device.parseDeviceURI(device_uri)
            except Error:
                result_code = e.opt
        
        log.debug(model)
        
        if model:
            key = self.fields.get('key', '')
            value = self.fields.get('value', '')
            
            if key and value: 
                if QueryModel(model):
                    if model.lower() in model_cache:
                        model_cache[model.lower()][key] = value
                        result_code = ERROR_SUCCESS
                
        self.out_buffer = buildResultMessage('InjectValueResult', None, result_code)
        

    # TODO: Need to load alerts at start-up
    def handle_setalerts(self):
        result_code = ERROR_SUCCESS
        username = self.fields.get('username', '')

        alerts[username] = {'email-alerts'       : utils.to_bool(self.fields.get('email-alerts', '0')),
                            'email-from-address' : self.fields.get('email-from-address', ''),
                            'email-to-addresses' : self.fields.get('email-to-addresses', ''),
                           }

        self.out_buffer = buildResultMessage('SetAlertsResult', None, result_code)


    # EVENT
    def handle_registerguievent(self):
        username = self.fields.get('username', '')
        typ = self.fields.get('type', 'unknown')
        self.typ = typ
        self.username = username
        self.send_events = True
        log.debug("Registering GUI for events: (%s, %s, %d)" % (username, typ, self._fileno))

    # EVENT
    def handle_unregisterguievent(self):
        username = self.fields.get('username', '')
        self.send_events = False


    def handle_test_email(self):
        result_code = ERROR_SUCCESS
        username = self.fields.get('username', prop.username)

        try:
            message = QueryString('email_test_message')
        except Error:
            message = ''
            
        try:
            subject = QueryString('email_test_subject')
        except Error:
            subject = ''

        result_code = self.sendEmail(username, subject, message, True)
        self.out_buffer = buildResultMessage('TestEmailResult', None, result_code)


    def handle_querystring(self):
        payload, result_code = '', ERROR_SUCCESS
        string_id = self.fields['string-id']
        try:
            payload = QueryString(string_id)
        except Error:
            log.error("String query failed for id %s" % string_id)
            payload = None
            result_code = ERROR_STRING_QUERY_FAILED

        self.out_buffer = buildResultMessage('QueryStringResult', payload, result_code)

        
    def createHistory(self, device_uri, code, jobid=0, username=prop.username):
        result_code = self.__checkdevice(device_uri)
        
        if result_code == ERROR_SUCCESS:    
            try:
                short_string = QueryString(code, 0)
            except Error:
                short_string, long_string = '', ''
            else:
                try:
                    long_string = QueryString(code, 1)
                except Error:
                    pass

            devices[device_uri].history.append(tuple(time.localtime()) +
                                                (jobid, username, code,
                                                 short_string, long_string))
                                                 
            # return True if added code is the same 
            # as the previous code (dup_event)
            try:
                prev_code = devices[device_uri].history.get()[-2][11]
            except IndexError:
                return False
            else:
                return code == prev_code
                
        
    # sent by hpfax: to indicate the start of a complete fax rendering job
    def handle_hpfaxbegin(self):      
        global fax_file
        username = self.fields.get('username', prop.username)
        job_id = self.fields.get('job-id', 0)
        printer_name = self.fields.get('printer', '')
        device_uri = self.fields.get('device-uri', '').replace('hp:', 'hpfax:')
        title = self.fields.get('title', '')
        
        # Send an early warning to the hp-sendfax UI so that
        # the response time to something happening is as short as possible
        result_code = ERROR_GUI_NOT_AVAILABLE
        
        for handler in socket_map:
            handler_obj = socket_map[handler]        
            
            log.debug("sendevents=%s, type=%s, username=%s" % (handler_obj.send_events, handler_obj.typ, handler_obj.username))
            
            if handler_obj.send_events and \
                handler_obj.typ == 'fax' and \
                handler_obj.username == username:
                
                # send event to already running hp-sendfax
                handler_obj.out_buffer = \
                    buildMessage('EventGUI', 
                                '\n\n',
                                {'job-id' : job_id,
                                 'event-code' : EVENT_FAX_RENDER_DISTANT_EARLY_WARNING,
                                 'event-type' : 'event',
                                 'retry-timeout' : 0,
                                 'device-uri' : device_uri,
                                 'printer' : printer_name,
                                 'title' : title,
                                })
                
                loopback_trigger.pull_trigger()        
                result_code = ERROR_SUCCESS

                # Only create a data store if a UI was found
                log.debug("Creating data store for %s:%d" % (username, job_id))
                fax_file[(username, job_id)] = cStringIO.StringIO()
                
                break
        
        # hpfax: will repeatedly send HPFaxBegin messages until it gets a 
        # ERROR_SUCCESS result code. (every 30sec)
        self.out_buffer = buildResultMessage('HPFaxBeginResult', None, result_code)
        
        
    # sent by hpfax: to transfer completed fax rendering data
    def handle_hpfaxdata(self):
        global fax_file
        username = self.fields.get('username', prop.username)
        job_id = self.fields.get('job-id', 0)
        
        if self.payload and (username, job_id) in fax_file:
            fax_file[(username, job_id)].write(self.payload)
            
        self.out_buffer = buildResultMessage('HPFaxDataResult', None, ERROR_SUCCESS)
        
            
    # sent by hpfax: to indicate the end of a complete fax rendering job
    def handle_hpfaxend(self):
        global fax_file
        
        username = self.fields.get('username', '')
        job_id = self.fields.get('job-id', 0)
        printer_name = self.fields.get('printer', '')
        device_uri = self.fields.get('device-uri', '').replace('hp:', 'hpfax:')
        title = self.fields.get('title', '')
        job_size = self.fields.get('job-size', 0)
        
        fax_file[(username, job_id)].seek(0)
        
        #print username, job_id, printer_name, device_uri, title, job_size
        
        for handler in socket_map:
            handler_obj = socket_map[handler]        
            
            #print handler_obj.send_events, handler_obj.typ, handler_obj.username
            
            if handler_obj.send_events and \
                handler_obj.typ == 'fax' and \
                handler_obj.username == username:
                
                # send event to already running hp-sendfax
                handler_obj.out_buffer = \
                    buildMessage('EventGUI', 
                                '\n\n',
                                {'job-id' : job_id,
                                 'event-code' : EVENT_FAX_RENDER_COMPLETE,
                                 'event-type' : 'event',
                                 'retry-timeout' : 0,
                                 'device-uri' : device_uri,
                                 'printer' : printer_name,
                                 'title' : title,
                                 'job-size': job_size,
                                })        
                
                loopback_trigger.pull_trigger()
                break

        self.out_buffer = buildResultMessage('HPFaxEndResult', None, ERROR_SUCCESS)

        
    # sent by hp-sendfax to retrieve a complete fax rendering job
    # sent in response to the EVENT_FAX_RENDER_COMPLETE event or
    # after being run with --job param, both after a hpfaxend message
    def handle_faxgetdata(self):
        global fax_file
        result_code = ERROR_SUCCESS
        username = self.fields.get('username', '')
        job_id = self.fields.get('job-id', 0)
        
        try:
            fax_file[(username, job_id)]
        except KeyError:
            result_code, data = ERROR_NO_DATA_AVAILABLE, ''
        else:
            data = fax_file[(username, job_id)].read(prop.max_message_len)
        
        if not data:
            result_code = ERROR_NO_DATA_AVAILABLE
            log.debug("Deleting data store for %s:%d" % (username, job_id))
            del fax_file[(username, job_id)]
        
        self.out_buffer = buildResultMessage('FaxGetDataResult', data, result_code)
        
    
    # EVENT
    def handle_event(self):
        gui_port, gui_host = None, None
        event_type = self.fields.get('event-type', 'event')
        event_code = self.fields.get('event-code', 0)
        device_uri = self.fields.get('device-uri', '').replace('hpfax:', 'hp:')
        log.debug("Device URI: %s" % device_uri)

        try:
            error_string_short = QueryString(str(event_code), 0)
        except Error:
            error_string_short, error_string_long = '', ''
        else:
            try:
                error_string_long = QueryString(str(event_code), 1)
            except Error:
                pass

        log.debug("Short/Long: %s/%s" % (error_string_short, error_string_long))

        job_id = self.fields.get('job-id', 0)

        try:
            username = self.fields['username']
        except KeyError:
            if job_id == 0:
                username = prop.username
            else:
                jobs = cups.getAllJobs()
                for j in jobs:
                    if j.id == job_id:
                        username = j.user
                        break
                else:
                    username = prop.username


        no_fwd = self.fields.get('no-fwd', False)
        log.debug("Username (jobid): %s (%d)" % (username, job_id))
        retry_timeout = self.fields.get('retry-timeout', 0)
        user_alerts = alerts.get(username, {})        

        dup_event = False
        if event_code <= EVENT_MAX_USER_EVENT:
            dup_event = self.createHistory(device_uri, event_code, job_id, username)

        pull = False
        if not no_fwd:
            for handler in socket_map:
                handler_obj = socket_map[handler]
                
                if handler_obj.send_events:
                    log.debug("Sending event to client: (%s, %s, %d)" % (handler_obj.username, handler_obj.typ, handler_obj._fileno))
                    pull = True

                    if handler_obj.typ == 'fax':
                        t = device_uri.replace('hp:', 'hpfax:')
                    else:
                        t = device_uri.replace('hpfax:', 'hp:')
                    
                    handler_obj.out_buffer = \
                        buildMessage('EventGUI', 
                            '%s\n%s\n' % (error_string_short, error_string_long),
                            {'job-id' : job_id,
                             'event-code' : event_code,
                             'event-type' : event_type,
                             'retry-timeout' : retry_timeout,
                             'device-uri' : t,
                            })

            if pull:
                loopback_trigger.pull_trigger()

            if event_code <= EVENT_MAX_USER_EVENT and \
                user_alerts.get('email-alerts', False) and \
                event_type == 'error' and \
                not dup_event:

                try:
                    subject = QueryString('email_alert_subject') + device_uri
                except Error:
                    subject = device_uri
                
                message = '\n'.join([device_uri, 
                                     time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()),
                                     error_string_short, 
                                     error_string_long,
                                     str(event_code)])
                                     
                self.sendEmail(username, subject, message, False)
                
                
    def sendEmail(self, username, subject, message, wait):
        msg = cStringIO.StringIO()
        result_code = ERROR_SUCCESS
        
        user_alerts = alerts.get(username, {}) 
        from_address = user_alerts.get('email-from-address', '')
        to_addresses = user_alerts.get('email-to-addresses', from_address)
        
        t = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
        UUID = file("/proc/sys/kernel/random/uuid").readline().rstrip("\n")
        
        msg.write("Date: %s\n" % t)
        msg.write("From: <%s>\n" % from_address)
        msg.write("To: %s\n" % to_addresses)
        msg.write("Message-Id: <%s %s>\n" % (UUID, t))
        msg.write('Content-Type: text/plain\n')
        msg.write("Content-Transfer-Encoding: 7bit\n")
        msg.write('Mime-Version: 1.0\n')
        msg.write("Subject: %s\n" % subject)
        msg.write('\n')
        msg.write(message)
        #msg.write('\n')
        email_message = msg.getvalue()
        log.debug(repr(email_message))

        mt = MailThread(email_message, from_address)
        mt.start()
        
        if wait:
            mt.join() # wait for thread to finish
            result_code = mt.result
            
        return result_code


    def handle_probedevicesfiltered(self):
        payload, result_code = '', ERROR_SUCCESS
        num_devices, ret_devices = 0, {}

        buses = self.fields.get('bus', 'cups,usb,par').split(',')
        format = self.fields.get('format', 'default')
        search = str(self.fields.get('search', ''))
        
        if search:
            try:
                search_pat = re.compile(search, re.IGNORECASE)
            except:
                log.error("Invalid search pattern. Search uses standard regular expressions. For more info, see: http://www.amk.ca/python/howto/regex/")
                search = ''

        for b in buses:
            bus = b.lower().strip()
            
            if bus == 'net':
                ttl = int(self.fields.get('ttl', 4))
                timeout = int(self.fields.get('timeout', 5))

                try:
                    detected_devices = slp.detectNetworkDevices(ttl, timeout)
                except Error:
                    log.error("An error occured during network probe.")
                else:
                    for ip in detected_devices:
                        hn = detected_devices[ip].get('hn', '?UNKNOWN?')
                        num_devices_on_jd = detected_devices[ip].get('num_devices', 0)
                        num_ports_on_jd = detected_devices[ip].get('num_ports', 1)

                        if num_devices_on_jd > 0:
                            for port in range(num_ports_on_jd):
                                dev = detected_devices[ip].get('device%d' % (port+1), '0')

                                if dev is not None and dev != '0':
                                    device_id = device.parseDeviceID(dev)
                                    model = device.normalizeModelName(device_id.get('MDL', '?UNKNOWN?'))

                                    if num_ports_on_jd == 1:
                                        device_uri = 'hp:/net/%s?ip=%s' % (model, ip)
                                    else:
                                        device_uri = 'hp:/net/%s?ip=%s&port=%d' % (model, ip, (port+1))

                                    device_filter = self.fields.get('filter', 'none')
                                    include = True
                                    
                                    try:
                                        mq = QueryModel(model)
                                    except Error:
                                        mq = {}
                                    
                                    if not mq:
                                        log.debug("Not found.")
                                        include = False
                                        
                                    elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
                                        log.debug("Not supported.")
                                        include = False
                                    
                                    elif device_filter not in ('none', 'print'):
                                        for f in device_filter.split(','):
                                            filter_type = int(mq.get('%s-type' % f.lower().strip(), 0))
                                            
                                            if filter_type == 0:
                                                log.debug("Filtered out.")
                                                include = False
                                                break

                                    if include:
                                        ret_devices[device_uri] = (model, model, hn)

            elif bus in ('usb', 'par'):
                log.debug(bus)
                try:
                    prop.hpiod_port = int(file(os.path.join(prop.run_dir, 'hpiod.port'), 'r').read())
                except:
                    prop.hpiod_port = 0
                
                log.debug("Connecting to hpiod (%s:%d)..." % (prop.hpiod_host, prop.hpiod_port))
                hpiod_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                hpiod_sock.connect((prop.hpiod_host, prop.hpiod_port))
            
                fields, data, result_code = \
                    xmitMessage(hpiod_sock, "ProbeDevices", None, {'bus' : bus,})
                
                hpiod_sock.close()

                if result_code == ERROR_SUCCESS:
                    for x in data.splitlines():
                        m = direct_pat.match(x)
                        
                        uri = m.group(1) or ''
                        mdl = m.group(2) or ''
                        desc = m.group(3) or ''
                        devid = m.group(4) or ''
                        
                        try:
                            back_end, is_hp, bus, model, serial, dev_file, host, port = \
                                device.parseDeviceURI(uri)
                        except Error:
                            continue
                        
                        if mdl and uri and is_hp:
                            device_filter = self.fields.get('filter', 'none')
                            include = True
                            
                            try:
                                mq = QueryModel(model)
                            except Error:
                                mq = {}
                                
                            if not mq:
                                log.debug("Not found.")
                                include = False
                                
                            elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
                                log.debug("Not supported.")
                                include = False

                            elif device_filter not in ('none', 'print'):
                                
                                for f in device_filter.split(','):
                                    filter_type = int(mq.get('%s-type' % f.lower().strip(), 0))
                                    
                                    if filter_type == 0:
                                        log.debug("Filtered out.")
                                        include = False
                                        break
    
                            if include:
                                ret_devices[uri] = (mdl, desc, devid) # model w/ _'s, mdl w/o

            elif bus == 'cups':
                cups_printers = cups.getPrinters()
                x = len(cups_printers)

                for p in cups_printers:
                    device_uri = p.device_uri

                    if p.device_uri != '':
                        device_filter = self.fields.get('filter', 'none')

                        try:
                            back_end, is_hp, bs, model, serial, dev_file, host, port = \
                                device.parseDeviceURI(device_uri)
                        except Error:
                            log.warning("Inrecognized URI: %s" % device_uri)
                            continue

                        if not is_hp:
                            continue
                            
                        include = True
                        
                        try:
                            mq = QueryModel(model)
                        except Error:
                            mq = {}
                            
                        if not mq:
                            include = False
                            log.debug("Not found.")
                            
                        elif int(mq.get('support-type', SUPPORT_TYPE_NONE)) == SUPPORT_TYPE_NONE:
                            log.debug("Not supported.")
                            include = False
                        
                        elif device_filter not in ('none', 'print'):
                            for f in device_filter.split(','):
                                filter_type = int(mq.get('%s-type' % f.lower().strip(), 0))
                                
                                if filter_type == 0:
                                    log.debug("Filtered out.")
                                    include = False
                                    break

                        if include:
                            ret_devices[device_uri] = (model, model, '')


        for uri in ret_devices:
            num_devices += 1
            mdl, model, devid_or_hn = ret_devices[uri]
            
            include = True
            if search:
                match_obj = search_pat.search("%s %s %s %s" % (mdl, model, devid_or_hn, uri))
                
                if match_obj is None:
                    log.debug("%s %s %s %s: Does not match search '%s'." % (mdl, model, devid_or_hn, uri, search))
                    include = False
                    
            if include:
                if format == 'cups':
                    payload = ''.join([payload, uri, ' ', utils.dquote(mdl), ' ', utils.dquote(model), ' ',utils.dquote(devid_or_hn), '\n'])
                else: # default
                    payload = ''.join([payload, uri, ',', mdl, '\n'])
            

        self.out_buffer = buildResultMessage('ProbeDevicesFilteredResult', payload,
                                             result_code, {'num-devices' : num_devices})

    # EVENT
    def handle_exit(self):
        self.signal_exit = True

    def handle_messageerror(self):
        pass

    def writable(self):
        return not (not self.out_buffer and self.connected)


    def handle_close(self):
        log.debug("Closing channel (%d)" % self._fileno)
        self.connected = False
        self.close()


class MailThread(threading.Thread):
    def __init__(self, message, from_address):
        threading.Thread.__init__(self)
        self.message = message
        self.from_address = from_address
        self.result = ERROR_SUCCESS

    def run(self):
        log.debug("Starting Mail Thread...")
        sendmail = utils.which('sendmail')
        
        if sendmail:
            sendmail = os.path.join(sendmail, 'sendmail')
            sendmail += ' -t -r %s' % self.from_address
            
            log.debug(sendmail)
            std_out, std_in, std_err = popen2.popen3(sendmail) 
            log.debug(repr(self.message))
            std_in.write(self.message)
            std_in.close()
            
            r, w, e = select.select([std_err], [], [], 2.0)
            
            if r:
                err = std_err.read()
                if err:
                    log.error(repr(err))
                    self.result = ERROR_TEST_EMAIL_FAILED
            
        else:
            log.error("Mail send failed. sendmail not found.")
            self.result = ERROR_TEST_EMAIL_FAILED
            
        log.debug("Exiting mail thread")


def reInit():
    initStrings()


def handleSIGHUP(signo, frame):
    log.info("SIGHUP")
    reInit()


def exitAllGUIs():
    pass

    
USAGE = [(__doc__, "", "name", True),
         ("Usage: hpssd.py [OPTIONS]", "", "summary", True),
         utils.USAGE_OPTIONS,
         ("Do not daemonize:", "-x", "option", False),
         ("Port to listen on:", "-p<port> or --port=<port> (overrides value in /etc/hp/hplip.conf)", "option", False),
         utils.USAGE_LOGGING1, utils.USAGE_LOGGING2,
         ("Run in debug mode:", "-g (same as options: -ldebug -x)", "option", False),
         utils.USAGE_HELP,
        ]
        

def usage(typ='text'):
    if typ == 'text':
        utils.log_title(__title__, __version__)
        
    utils.format_text(USAGE, typ, __title__, 'hpssd.py', __version__)
    sys.exit(0)



def main(args):
    log.set_module('hpssd')

    prop.prog = sys.argv[0]
    prop.daemonize = True

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'l:xhp:g', 
            ['level=', 'help', 'help-man', 'help-rest', 'port=', 'help-desc'])

    except getopt.GetoptError:
        usage()

    if os.getenv("HPLIP_DEBUG"):
        log.set_level('debug')
    
    for o, a in opts:
        if o in ('-l', '--logging'):
            log_level = a.lower().strip()
            if not log.set_level(log_level):
                usage()
                
        elif o == '-g':
            log.set_level('debug')
            prop.daemonize = False

        elif o in ('-x',):
            prop.daemonize = False

        elif o in ('-h', '--help'):
            usage()
            
        elif o == '--help-rest':
            usage('rest')
            
        elif o == '--help-man':
            usage('man')
            
        elif o == '--help-desc':
            print __doc__,
            sys.exit(0)
            
        elif o in ('-p', '--port'):
            try:
                prop.hpssd_cfg_port = int(a)
            except ValueError:
                log.error('Port must be a numeric value')
                usage()


    utils.log_title(__title__, __version__)

    prop.history_size = 32

    # Lock pidfile before we muck around with system state
    # Patch by Henrique M. Holschuh <hmh@debian.org>
    utils.get_pidfile_lock(os.path.join(prop.run_dir, 'hpssd.pid'))

    # Spawn child right away so that boot up sequence
    # is as fast as possible
    if prop.daemonize:
        utils.daemonize()


    # configure the various data stores
    gettext.install('hplip')
    reInit()

    # hpssd server dispatcher object
    try:
        server = hpssd_server(prop.hpssd_host, prop.hpssd_cfg_port)
    except Error, e:
        log.error("Server exited with error: %s" % e.msg)
        sys.exit(1)

    global loopback_trigger
    try:
        loopback_trigger = trigger()
    except Error, e:
        log.error("Server exited with error: %s" % e.msg)
        sys.exit(1)

    os.umask(0133)
    file(os.path.join(prop.run_dir, 'hpssd.port'), 'w').write('%d\n' % prop.hpssd_port)
    os.umask (0077)
    log.debug('port=%d' % prop.hpssd_port)
    log.info("Listening on %s:%d" % (prop.hpssd_host, prop.hpssd_port))

    signal.signal(signal.SIGHUP, handleSIGHUP)

    try:
        log.debug("Starting async loop...")
        try:
            loop(timeout=0.5)
        except KeyboardInterrupt:
            log.warn("Ctrl-C hit, exiting...")
        except Exception:
            log.exception()

        log.debug("Cleaning up...")
    finally:
        os.remove(os.path.join(prop.run_dir, 'hpssd.pid'))
        os.remove(os.path.join(prop.run_dir, 'hpssd.port'))
        server.close()
        return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))