-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrscankeyd.py
More file actions
executable file
·842 lines (744 loc) · 31.9 KB
/
Copy pathbrscankeyd.py
File metadata and controls
executable file
·842 lines (744 loc) · 31.9 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
LICENSE="""brscankeyd: Scan Key Daemon for Brother Inc. Network Scanners
Copyright (C) 2016 Frank Abelbeck <frank.abelbeck@googlemail.com>
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 3 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, see <http://www.gnu.org/licenses/>."""
import sys,os,os.path,subprocess,argparse,configparser
import socket
import select
import signal
import syslog
import shlex
import errno
import fcntl
import multiprocessing
import time
import logging
import logging.handlers
EPOLLRDHUP = 0x2000 # see /usr/include/sys/epoll.h, defined since kernel 2.6.17
# directory this script lives in; used as a fallback location for the config
# file and for resolving relative scan-script paths, so the daemon can be run
# straight from its source directory without a system-wide installation
BASEDIR = os.path.dirname(os.path.abspath(__file__))
PIDFILE = "/var/run/brscankeyd.pid"
TMPPIDFILE = "/tmp/brscankeyd.pid" # fallback if /var/run is not accessible
LOCKFILE = "/tmp/brscankeyd.lock" # exclusive flock guarantees one instance
CONFIGFILE = "/etc/brscankeyd.ini"
LOCALCONFIGFILE = os.path.join(BASEDIR,"brscankeyd.ini") # fallback config
LOGDEV = "/dev/log"
CONFIGHELP = """Configuration file layout (ini file style):
[General]
; General parameters; this example shows the default values if a parameter is
; not specified
; first cycle: delay in seconds until first SNMP request is sent;
; cycle: delay in seconds between consecutive SNMP requests;
; buffer size: number of bytes to read when new UDP packets arrive.
first cycle = 3
cycle = 300
buffer size = 4096
hostname = <try to determine own IPv4 automatically>
port = 54925
; If one or all of these parameters are not defined, the program will fall
; back to the default values.
[Device Name]
; Definition of a device "Device Name".
; (any leading/trailing whitespace characters of the name are ignored)
; If no devices are specified, the program will terminate (nothing to do).
ip = hostname.or.ip.address
dev = sane device address
; What follows are optional entries for the scanners' various scan-to menus;
; definitions here will create an entry of given name below the given menu
; of each device defined above.
; When activated, the given _absolute_ script path is called and the device
; address is passed as first argument; if any arguments are specified
; (cf. FILE/"Another entry"), these will be passed as 2nd arg and following.
;
; To define a device-specific menu entry, prepend a colon : and the device
; name (see above) to FILE|IMAGE|OCR|EMAIL (cf. example entry OCR).
;
; Any leading/trailing whitespace characters of the section name or its
; device/menu names are ignored).
;
; If no entries are specified, or entries refer non-existing devices,
; the program will terminate (nothing to do).
;
; menu: scan to file
[FILE]
Entry name = /absolute/path/to/scanscript
Another entry = /absolute/path/to/scanscript arg1 arg2
; menu: scan to image
[IMAGE]
Entry name = /absolute/path/to/scanscript
; menu: scan to OCR/text file; here only specific to device "Device Name"
[Device Name:OCR]
Entry name = /absolute/path/to/scanscript
; menu: scan to e-mail
[EMAIL]
Entry name = /absolute/path/to/scanscript
"""
class ConsoleHandler(logging.StreamHandler):
def __init__(self):
super().__init__(sys.stdout)
formatter = logging.Formatter("%(message)s")
self.setFormatter(formatter)
def format(self,record):
message = super().format(record)
if record.levelno <= logging.INFO:
return "\033[0m{0}\033[0m".format(message)
#return "\033[97m{0}\033[0m".format(message)
elif record.levelno == logging.WARNING:
return "\033[93m{0}\033[0m".format(message)
elif record.levelno >= logging.ERROR:
return "\033[91m{0}\033[0m".format(message)
# ---------------------------------------------------------------------------
# Minimal SNMPv1 SET encoder (replaces the external net-snmp "snmpset" tool).
#
# An SNMPv1 message is BER-encoded ASN.1 with this structure:
#
# SEQUENCE {
# version INTEGER -- 0 means SNMPv1
# community OCTET STRING -- "internal" for Brother scanners
# SetRequest-PDU [3] IMPLICIT SEQUENCE {
# request-id INTEGER
# error-status INTEGER -- 0
# error-index INTEGER -- 0
# variable-bindings SEQUENCE OF SEQUENCE { name OBJECT-IDENTIFIER, value }
# }
# }
#
# We only ever send a single OCTET STRING binding, so a few small BER helpers
# are enough; no third-party library is required.
def _ber_length(length):
"""Encode a BER length field (short or long form)."""
if length < 0x80:
return bytes((length,))
out = b""
while length > 0:
out = bytes((length & 0xFF,)) + out
length >>= 8
return bytes((0x80 | len(out),)) + out
def _ber_tlv(tag,value):
"""Wrap a value in a BER tag-length-value triple."""
return bytes((tag,)) + _ber_length(len(value)) + value
def _ber_integer(number):
"""Encode a (small, non-negative) integer as a BER INTEGER (tag 0x02)."""
if number == 0:
content = b"\x00"
else:
length = (number.bit_length() + 8) // 8 # leave room for the sign bit
content = number.to_bytes(length,"big",signed=True)
# strip redundant leading bytes
while len(content) > 1 and content[0] == 0 and not (content[1] & 0x80):
content = content[1:]
return _ber_tlv(0x02,content)
def _ber_oid(oid):
"""Encode a dotted object identifier string as a BER OID (tag 0x06)."""
parts = [int(p) for p in oid.split(".")]
body = bytes((40 * parts[0] + parts[1],)) # first two sub-ids share one octet
for sub in parts[2:]:
chunk = bytes((sub & 0x7F,))
sub >>= 7
while sub > 0:
chunk = bytes((0x80 | (sub & 0x7F),)) + chunk
sub >>= 7
body += chunk
return _ber_tlv(0x06,body)
def buildSNMPSetRequest(community,request_id,oid,value):
"""Build a complete SNMPv1 SET request datagram setting an OCTET STRING.
Args:
community: a string; the SNMP community (Brother uses "internal").
request_id: an integer; an arbitrary request identifier.
oid: a string; the dotted object identifier to set.
value: a string; the us-ascii value to write as an OCTET STRING.
Returns:
A bytes object ready to be sent to UDP port 161 of the scanner."""
binding = _ber_tlv(0x30,_ber_oid(oid) + _ber_tlv(0x04,value.encode("ascii")))
varbinds = _ber_tlv(0x30,binding)
pdu = _ber_tlv(0xA3, # [3] IMPLICIT SEQUENCE = SetRequest-PDU
_ber_integer(request_id) + _ber_integer(0) + _ber_integer(0) + varbinds)
return _ber_tlv(0x30,
_ber_integer(0) + _ber_tlv(0x04,community.encode("ascii")) + pdu)
class Daemon:
def __init__(self,logger):
"""Create a Daemon process on this machine."""
try:
# check if a PID file already exists
with open(PIDFILE,"r") as f:
self._pid = int(f.read())
pidfile = PIDFILE
except FileNotFoundError:
# standard PID file not found
# perhaps a former instance used TMPPIDFILE?
try:
with open(TMPPIDFILE,"r") as f:
self._pid = int(f.read())
pidfile = TMPPIDFILE
except FileNotFoundError:
# still no PID file: reset _pid
self._pid = None
if self._pid:
# check if given PID points to an existing process
if subprocess.call(["/bin/ps","--pid",str(self._pid)],stdout=subprocess.DEVNULL) > 0:
# /bin/ps failed: there is no process with this PID;
# assume invalid PID file: remove it, reset _pid
os.remove(pidfile) # this might fail if PIDFILE is not accessible
self._pid = None
self._logger = logger
def start(self,configfile,hostname,port,doLog,daemonise=False):
"""Start the daemon.
Args:
configfile: a file-type object refering to an existing configuration file.
port: an integer; the UDP port to be used by this daemon.
doLog: a boolean; if True, the daemon will print messages to syslog.
daemonise: a boolean; if True, the daemon will detach itself from the
controlling terminal and continue as a background process."""
# ensure only one instance can run: grab an exclusive, non-blocking
# advisory lock that the kernel holds for this process's whole lifetime
# (and releases automatically if it crashes). This is atomic -- no
# startup race, no stale-PID false positives -- and catches a second
# instance whether it was launched manually or via the systemd service.
# (The UDP bind further below is a second backstop.)
try:
self._lockfile = open(LOCKFILE,"w")
except OSError as e:
self._logger.error("Cannot open lock file {0}: {1}".format(LOCKFILE,e))
sys.exit(1)
try:
fcntl.flock(self._lockfile,fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
self._logger.error("Won't start because another brscankeyd process is already running.")
sys.exit(1)
# modify logger if syslogging is desired
if doLog:
syslogger = logging.handlers.SysLogHandler(address=LOGDEV)
syslogger.setLevel(logging.DEBUG)
# format for metalog: "time name: message"
sysformatter = logging.Formatter('%(asctime)s %(name)s: %(message)s')
syslogger.setFormatter(sysformatter)
syslogger.ident = self._logger.name
self._logger.addHandler(syslogger)
# process program configuration
self._logger.info("Processing configuation file")
if not configfile:
# no config file given: try the system-wide config in /etc first,
# then fall back to the config shipped next to this script so the
# daemon can be run straight from its source directory
try:
configfile = open(CONFIGFILE,"r")
except FileNotFoundError:
try:
configfile = open(LOCALCONFIGFILE,"r")
except FileNotFoundError:
self._logger.error("No configuration file found ({0} or {1}). Terminating.".format(CONFIGFILE,LOCALCONFIGFILE))
sys.exit(1)
self._logger.info("Reading configuration from {0}".format(configfile.name))
try:
# parse config
cfg = configparser.RawConfigParser()
cfg.optionxform = lambda option: option # don't convert to lowercase
cfg.read_file(configfile)
#
# accepted ini structure:
# - section General
# - one or more Device sections not named "General" and not ending in :IMAGE, :FILE, :OCR or :EMAIL
# - zero or more sections ending with :IMAGE
# - zero or more sections ending with :FILE
# - zero or more sections ending with :OCR
# - zero or more sections ending with :EMAIL
#
# check section "General"
self._firstcycle = cfg.getint("General","first cycle",fallback=3)
self._cycle = cfg.getint("General","cycle",fallback=300)
self._buffersize = cfg.getint("General","buffer size",fallback=4096)
hostname = cfg.get("General","hostname",fallback=hostname)
port = cfg.getint("General","port",fallback=port)
# optional target directory for scans: if set, it is exported as the
# SCANDIR environment variable, which the scan scripts pick up (so the
# location is configured here in one place rather than in each script;
# if unset, the scripts fall back to the XDG "Pictures" folder)
scandir = cfg.get("General","scan dir",fallback="").strip()
if scandir:
os.environ["SCANDIR"] = os.path.expanduser(scandir)
self._logger.info("Scans will be written to {0}".format(os.environ["SCANDIR"]))
# collect all device sections
self._devices = dict()
secDevs = list()
secEntries = list()
for section in cfg.sections():
try:
dev,sec = [i.strip() for i in section.rsplit(":",1)]
except ValueError:
# no : inside section --> no device namespace
dev,sec = "",section.strip()
if section == "General":
# ignore general parameters, already processed
continue
elif sec in ("IMAGE","FILE","OCR","EMAIL"):
# section named IMAGE|FILE|OCR|EMAIL or ending in these strings after a colon:
# a menu definition, strip leading and trailing whitespace and add to entries
secEntries.append(section)
elif "ip" in cfg[section].keys() and "dev" in cfg[section].keys():
# any remaining section containing fields "ip" and "dev" is a device definition
secDevs.append(section)
# iterate over all device definitions
devips = dict()
devnames = dict()
for device in secDevs:
# map scanner's IP address to a device name (used when processing notifications)
if cfg[device]["ip"] in self._devices or cfg[device]["dev"] in self._devices.values():
self._logger.warning("Not adding device {devname} (parameters already in use)".format(devname=device))
else:
self._devices[cfg[device]["ip"]] = cfg[device]["dev"]
devips[device] = cfg[device]["ip"]
devnames[cfg[device]["ip"]] = device
self._logger.info("Adding device {devname} (IP={ip},dev={address})...".format(devname=device,ip=cfg[device]["ip"],address=cfg[device]["dev"]))
if len(devips) == 0:
self._logger.info("No devices defined. Nothing to do, terminating.")
sys.exit(0)
# iterate over all entry definitions
self._config = dict()
for menutype in secEntries:
try:
devname,menu = [i.strip() for i in menutype.rsplit(":",1)]
devs = [devips[devname]]
except ValueError:
# tuple unpacking failed: must be a global IMAGE|FILE|OCR|EMAIL
menutype.strip()
menu = menutype
devs = self._devices.keys()
except KeyError:
# unknown device: ignore
self._logger.warning("Ignoring entry definition {device} / {menu} (device unknown)".format(device=devname,menu=menu))
continue
# iterate over all found devices
for dev in devs:
# iterate over all entries beneath the menu type
for entry,path in cfg[menutype].items():
pathargs = shlex.split(path) # split path according to BASh syntax
script = pathargs[0] # isolate script name
if not os.path.isabs(script):
# resolve relative script paths against this script's
# directory, so e.g. "scan2pdf.sh" refers to the copy
# shipped alongside the daemon
script = os.path.join(BASEDIR,script)
pathargs[0] = script # store the resolved (absolute) path
pathargs.insert(1,self._devices[dev]) # inject device name
# pathargs.insert(1,shlex.quote(self._devices[dev])) # inject device name (quoted)
# pathargs = " ".join(pathargs) # DEBUG: shell=True --> reconstruct argument string
if os.path.isfile(script):
# script file exists: create entry
# check if entry name can be expressed as octet string
# (i.e. can be presented in us-ascii)
try:
entry = entry.encode("ascii").decode()
except UnicodeError:
self._logger.warning("Ignoring entry {device} / {menu} / {entry} (entry not encodable with us-ascii)".format(entry=entry,menu=menu,device=devnames[dev]))
continue
try:
# add path to script for this device's menu entry
self._config[dev][menu][entry] = pathargs
except KeyError:
try:
# one of the dictionarys uninitialised:
# step one level up, create dict
self._config[dev][menu] = dict()
self._config[dev][menu][entry] = pathargs
except KeyError:
# still one of the dictionarys uninitialised:
# step one level up, create dict
self._config[dev] = dict()
self._config[dev][menu] = dict()
self._config[dev][menu][entry] = pathargs
self._logger.info("Adding entry {device} / {menu} / {entry}...".format(entry=entry,menu=menu,device=devnames[dev]))
else:
# script file does not exist (neither as given nor relative to BASEDIR)
self._logger.warning("Ignoring entry {device} / {menu} / {entry} (script {script} not found)".format(entry=entry,menu=menu,device=devnames[dev],script=script))
# clean up device list: remove devices without any entry definitions
for dev in tuple(self._devices.keys()):
if dev not in self._config:
self._logger.info("Removing unused device {0}".format(devnames[dev]))
del self._devices[dev]
if len(self._devices) == 0:
self._logger.info("Final device list is empty. Nothing to do, terminating.")
sys.exit(0)
elif len(self._config) == 0:
self._logger.info("Final entry list is empty. Nothing to do, terminating.")
sys.exit(0)
except configparser.DuplicateSectionError:
# one duplicate section found: invalid config, exit with error
self._logger.error("Duplicate Section found in configuration file. Terminating.")
sys.exit(1)
except (ValueError,TypeError,KeyError,configparser.Error):
# invalid config: since there are no scan targets further program execution is futile
if os.path.isfile(configfile):
self._logger.error("Error reading the configuration file. Terminating.")
else:
self._logger.error("Default configuration file {} missing. Terminating.".format(CONFIGFILE))
sys.exit(1)
# create non-blocking server socket
try:
if not hostname:
# no hostname argument given: try to obtain it automatically
# (read about it on StackOverflow...)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.connect(("1.1.1.1",0))
hostname = s.getsockname()[0]
s.close()
self._socket_server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self._logger.debug("Trying to bind UDP port at {0}:{1}".format(hostname,port))
self._socket_server.bind(( hostname,port ))
self._socket_server.setblocking(False)
# read back actual hostname/port information
self._hostname,self._port = self._socket_server.getsockname()
self._logger.info("Opened UDP socket at {0}:{1}".format(self._hostname,self._port))
# socket used to send SNMP SET requests to the scanners (UDP port 161)
self._socket_snmp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self._socket_snmp.setblocking(False)
self._reqid = 0
except OSError as e:
if e.errno == errno.EADDRINUSE: # error: address already in use
# another process is using this address
self._logger.error("Address {hostname} already in use!".format(hostname=self._hostname))
sys.exit(1)
elif e.errno == errno.EACCES: # error: permission denied
# most probably a port <1024 should be bound by a non-root process
self._logger.error("Permission denied!")
sys.exit(1)
elif isinstance(e,socket.gaierror):
# unexpected error...
self._logger.error("Socket error: {}".format(e))
sys.exit(1)
else:
self._logger.error("OS error: {}".format(e))
sys.exit(1)
if daemonise:
self._logger.info("Daemonising...")
self.daemonise() # detach from terminal
self.main() # start main loop
def stop(self):
"""Stop the daemon by sending a SIGTERM signal"""
if self._pid:
os.kill(self._pid,signal.SIGTERM)
self._logger.info("Sent SIGTERM to {0}".format(self._pid))
else:
self._logger.info("There is no process to terminate.")
def daemonise(self):
"""Daemonise: do a double fork to prevent zombies; second fork prevents child from
being session leader and thus prevents it from acquire a (controlling) terminal"""
# do first fork, i.e. split a child process and exit if successful
# fork() clones the process and lets both processes continue at this
# position; the parent process receives the child's PID as result,
# while the child receives a 0.
# might raise OSError
pid = os.fork()
if pid > 0: # fork returned a PID: this is the parent process, exit!
sys.exit(0)
# now this process continues as the first child
# let this first child process become a session leader
os.setsid()
# do 2nd fork, i.e. split another child process and exit if successful
# might raise OSError
pid = os.fork()
if pid > 0:
# first child as a session leader should exit, thus leaving
# child no. 2 orphaned without ability to open a controlling
# terminal and thus preventing zombie processes
sys.exit(0)
# detach from environment
os.chdir("/") # switch to the directory root as it's always present
os.umask(0) # reset file creation permissions mask to "u=rwx,g=rwx,o=rwx"
# now this process continues as the second child
# next step: redirect input/output/error file descriptors
# try to redirect them to a logfile (may fail)
sys.stdout.flush()
sys.stderr.flush()
stdin = open(os.devnull,"r")
stdout = open(os.devnull,"a+")
stderr = open(os.devnull,"a+")
os.dup2(stdin.fileno(),sys.stdin.fileno())
os.dup2(stdout.fileno(),sys.stdout.fileno())
os.dup2(stderr.fileno(),sys.stderr.fileno())
def genAppNum(self,function):
"""Generate the internal function number (=APPNUM) for given function.
Args:
function: a string; either "IMAGE", "EMAIL", "OCR" or "FILE".
Returns:
An integer of set (1,2,3,5).
Raises:
ValueError: invalid function string."""
if function == "IMAGE":
return 1 # as seen in the wireshark dump
elif function == "EMAIL":
return 2
elif function == "OCR":
return 3
elif function == "FILE":
return 5
else:
raise ValueError
def snmpSetRequest(self,ip,function,user):
"""Issue an SNMP set request for a Brother variable in order to register with a
printer's scan key.
According to a wireshark dump, SNMP version 1 is used with community "internal".
The request is built and sent in pure Python, so the external net-snmp package
is no longer required.
Args:
ip: a string; the IP address/hostname of the scanner.
function: a string, either "IMAGE", "EMAIL", "OCR" or "FILE".
user: a string; the target name shown on the printer's display.
Raises:
ValueError: function not in set ("IMAGE","EMAIL","OCR","FILE").
OSError: an error occured while sending the UDP datagram."""
value = """TYPE=BR;BUTTON=SCAN;USER="{user}";FUNC={function};HOST={hostname}:{port};APPNUM={appnum};DURATION={duration};BRID=;""".format(
user = user,
function = function,
hostname = self._hostname,
port = self._port,
appnum = self.genAppNum(function),
duration = self._cycle
)
self._reqid = (self._reqid + 1) & 0x7FFFFFFF
packet = buildSNMPSetRequest(
"internal",
self._reqid,
"1.3.6.1.4.1.2435.2.3.9.2.11.1.1.0",
value
)
self._socket_snmp.sendto(packet,(ip,161))
def callScript(self,*args,**kwargs):
"""Wrapper function for subprocess.call().
Adds a two second delay to fix a race condition
(cf. https://forums.gentoo.org/viewtopic-p-7952026.html).
Args:
args: a variable number of arguments passed to call().
kwargs: a variable number of key-value argument pairs passed to call().
Returns:
An integer; exitcode of the called executable.
"""
time.sleep(2)
kwargs["stderr"] = subprocess.STDOUT # redirect stderr to stdout
return subprocess.check_output(*args,**kwargs)
def main(self):
"""Main program loop"""
# store the process identifier and create the PID file
self._pid = os.getpid()
try:
with open(PIDFILE,"w") as f:
f.write(str(self._pid))
pidfile = PIDFILE
except:
# writing failed, most likely: lacking permission to access PIDFILE
# fall back to TMPPIDFILE
with open(TMPPIDFILE,"w") as f:
f.write(str(self._pid))
pidfile = TMPPIDFILE
# prepare asynchronous I/O using epoll
self._epoll = select.epoll()
# prepare process and sequence management
processes = dict()
seqnum = set()
# register with epoll object in level-triggered mode
# (EPOLLET = default; neccessary because the socket might hold
# more data then a read might fetch...
fd_server = self._socket_server.fileno()
self._epoll.register(fd_server,select.EPOLLIN)
# intercept incoming signals via a wakeup file descriptor: a socketpair
# is created and Python writes the signal number to it whenever SIGTERM
# or SIGINT arrives; the read end is monitored by epoll (this replaces
# the linuxfd.signalfd dependency).
self._sig_r,self._sig_w = socket.socketpair()
self._sig_r.setblocking(False)
self._sig_w.setblocking(False)
signal.set_wakeup_fd(self._sig_w.fileno())
# install no-op handlers so the default disposition (terminate) is
# replaced and the loop gets a chance to shut down cleanly
signal.signal(signal.SIGTERM,lambda signum,frame:None)
signal.signal(signal.SIGINT,lambda signum,frame:None)
self._epoll.register(self._sig_r.fileno(),select.EPOLLIN)
# schedule the first SNMP SET request for every configured device;
# expiry/repetition is handled by the epoll timeout below instead of a
# dedicated timer file descriptor (this replaces linuxfd.timerfd).
deadlines = {ip:time.monotonic() + self._firstcycle for ip in self._config.keys()}
# enter main loop
self.isrunning = True
while self.isrunning:
# send SNMP SET requests for every device whose deadline has passed
# and schedule the next request self._cycle seconds later
now = time.monotonic()
for ip in deadlines.keys():
if now >= deadlines[ip]:
for function in self._config[ip].keys():
for user in self._config[ip][function].keys():
try:
self.snmpSetRequest(ip,function,user)
self._logger.debug("SNMP SET request sent ({0}/{1}/{2})".format(ip,function,user))
except OSError as e:
self._logger.warning("SNMP SET request failed ({0}/{1}/{2}): {3}".format(ip,function,user,e))
deadlines[ip] = now + self._cycle
# block until the next event or the next scheduled SNMP request
if deadlines:
timeout = max(0.0,min(deadlines.values()) - time.monotonic())
else:
timeout = -1
# epoll.poll() has to be enclosed in try..except because
# signals might interrupt it -- this case is intercepted and handled
# by catching EINTR errors
try:
fdevents = self._epoll.poll(timeout)
except OSError as e:
if e.errno == errno.EINTR:
continue # system call was interrupted: enter next loop iteration
raise # re-raise uncaught OSError
for fd,fdevent in fdevents:
if fd == fd_server:
#
# server socket became readable: new input
#
data,address = self._socket_server.recvfrom(self._buffersize)
self._logger.debug("incoming UDP packet: data={0}, address={0}".format(data,address))
datastr = data.decode(errors="ignore")
try:
datadict = dict([i.split("=",1) for i in datastr[datastr.index("TYPE=BR;"):].split(";") if "=" in i])
except ValueError:
# index() failed --> no TYPE=BR field --> invalid packet
break
# sanity check:
# - scan button?
# - appnum corresponds to function?
# - correct hostname:port?
# - sequence number not yet seen?
# (at least my scanner sends two identical packets)
try:
hostname,port = datadict["HOST"].rsplit(":",1)
port = int(port)
user = datadict["USER"].strip('"')
function = datadict["FUNC"]
button = datadict["BUTTON"]
appnum = int(datadict["APPNUM"])
seq = datadict["SEQ"]
except (ValueError,KeyError):
# erroneous message/invalid port: ignore
break
if button == "SCAN" and appnum == self.genAppNum(function) and \
hostname == self._hostname and port == self._port and \
seq not in seqnum:
# scan button message; appnum equivalent to function name
# correct hostname/port and sequence number not seen yet
# -> call a script associated with given function/user name
self._logger.info('scan button event "{0}/{1}" received from {2}'.format(function,user,address[0]))
try:
device = self._devices[address[0]]
except KeyError:
break # a deviced called in that is not registered? nevermind
try:
# call script as background process
seqnum.add(seq)
process = multiprocessing.Process(
target=self.callScript,
kwargs={
"args":self._config[address[0]][function][user]
}
)
process.start()
processes[process.sentinel] = process,seq
self._epoll.register(process.sentinel,select.EPOLLIN | EPOLLRDHUP)
self._logger.debug("script call: {} (process {})".format(self._config[address[0]][function][user],process.pid))
except:
# either call() failed or no script is connected to said device/function/user:
# need to think of a way to send an error message to the scanner?
self._logger.exception("Problem calling script {}".format(self._config[address[0]][function][user]))
elif fd in processes:
#
# process management: process terminated (sentinel became readable)
# remove process+seq from list, unregister sentinel
#
proc,seq= processes[fd]
if proc.exitcode == None:
# returncode None: process has not yet terminated,
# but stdout hung up; zombie? kill it!
try:
proc.terminate()
except ProcessLookupError:
pass # process has terminated, ignore
except:
self._logger.exception("Potential problem with script PID={0}".format(proc.pid))
else:
self._logger.debug("Script terminated with code {}".format(proc.exitcode))
self._epoll.unregister(fd)
del processes[fd]
seqnum.remove(seq)
elif fd == self._sig_r.fileno():
#
# pending signal: Python wrote the signal number(s) to the
# wakeup socket; read and inspect them
#
try:
data = self._sig_r.recv(4096)
except BlockingIOError:
data = b""
if signal.SIGTERM in data or signal.SIGINT in data:
# should terminate: end loop (SIGTERM from "stop"/systemd,
# SIGINT from pressing Ctrl+C in an interactive terminal)
self._logger.info("received termination signal: terminating...")
self.isrunning = False
# daemon is terminating...
signal.set_wakeup_fd(-1)
os.remove(pidfile)
syslog.closelog()
if __name__ == '__main__':
# setup argument parser and parse commandline arguments
parser = argparse.ArgumentParser(
#formatter_class=argparse.RawDescriptionHelpFormatter,
description="Start or manage a Brother Scan Key Daemon.",
epilog="""Copyright (C) 2016 Frank Abelbeck <frank.abelbeck@googlemail.com>
This program comes with ABSOLUTELY NO WARRANTY. It is free software,
and you are welcome to redistribute it under certain conditions
(see command "license" for details)."""
)
parser.add_argument("command",choices=("start","daemon","stop","license","config"),help="start, start daemonised or stop this daemon, show more license information or print help on the configuration file format")
parser.add_argument("--config",metavar="CFG",type=argparse.FileType("r"),help="load configuration file CFG")
# default port 54925: it seems Brother scanners address their notifications to this UDP port,
# ignoring the port value passed via SNMP request?
# cf. Brother website: 54925 = scanning, 54926 = PC fax receiving
parser.add_argument("--address",metavar="ADDRESS",help="use hostname ADDRESS (default: try to determine hostname/IPv4 automatically)")
parser.add_argument("--port",metavar="PORT",type=int,default=54925,help="use UDP port PORT (default: %(default)s)")
parser.add_argument("--syslog",action='store_true',help="write messages to syslog")
parser.add_argument("--verbose",action='store_true',help="also write DEBUG messages to stdout")
args = parser.parse_args()
logger = logging.getLogger('brscankeyd')
if args.verbose:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
cliHandler = ConsoleHandler()
logger.addHandler(cliHandler)
if args.command == "license":
# print license information and exit successfully
logger.info(LICENSE)
sys.exit(0)
elif args.command == "config":
# print help on the configuration file format and exit successfully
logger.info(CONFIGHELP)
sys.exit(0)
# create daemon and execute given command
try:
daemon = Daemon(logger)
except FileNotFoundError:
# constructor failed due to PID file access: report and exit
logger.error("PID file could not be removed; perhaps it is a permission problem?")
sys.exit(1)
if args.command == "start":
daemon.start(args.config,args.address,args.port,args.syslog)
elif args.command == "daemon":
daemon.start(args.config,args.address,args.port,args.syslog,daemonise=True)
elif args.command == "stop":
daemon.stop()