webXMPP

Check-in [d87eec90b5]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Code to run on a phone to pull in notifications and display, make noise, light LED's, stuff like that.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | master | trunk
Files: files | file ages | folders
SHA3-256:d87eec90b5eb90ee43a2184711f1a9757079d54233166f943c621ce203f21651
User & Date: vandyswa@gmail.com 2017-06-22 22:41:33
Context
2017-06-23
15:42
Split out packet part from general notification dispatch check-in: d06467d45f user: vandyswa@gmail.com tags: master, trunk
2017-06-22
22:41
Code to run on a phone to pull in notifications and display, make noise, light LED's, stuff like that. check-in: d87eec90b5 user: vandyswa@gmail.com tags: master, trunk
2017-06-16
16:55
Some other ideas check-in: 53fbcf2287 user: vandyswa@gmail.com tags: master, trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added notified.py.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#
# notified.py
#	Client for UDP notifications
# vim: expandtab
#
# Ugh, Ubuntu Phone seems to have pretty much gone to Python 3, so
#  here we are.
#
# This client is written to run on a mobile, battery powered
#  device.  Being battery powered means it wants to transmit
#  rarely, and receive infrequently.  Against this, it must
#  accept that its network can go down or change address, and
#  such changes might occur without any other system event
#  to indicate the change.
#
# The initial implementation is for Ubuntu Touch.  It plays
#  a sound and pushes a notification when receiving new
#  events.  It also turns on a blinking LED where it can,
#  and clears it only when the device is next unlocked.
#
# The protocol uses a JSON-encoded string carried over UDP.
# The message structure is documented below, but at a high
#  level the protocol advances in three stages.  First,
#  the client sends a request to the notification server.
#  Among other items, it indicates the last event serial
#  seen.
# The server immediately responds to the client's port and
#  address.  If its response indicates new events, then
#  the exchange is over.  The client will presumably post
#  notifications and eventually start a new protocol exchange.
# If the server returns an indication that the client has
#  already seen the latest event, it will specify a
#  timeout.  If a new event occurs before that timeout, the
#  server will send the event.  Otherwise, at the timeout
#  interval, the server will send a message specifying
#  (still) no new messages.
# In both cases of the previous paragraph, the exchange is
#  considered finished.  A new exchange from the beginning
#  must be undertaken to receive subsequent notifications.
#
# The relative transience of an exchange, and the lack of
#  any ongoing network connection is intentional.  The client
#  might change its own address, or it might be behind a NAT
#  device which changes its address.  The most that can be
#  disrupted by such a change is a single span of exchanges
#  within the bounds of one timeout period.
# Thus, each exchange starts with the client creating a
#  fresh socket so that no long-term network state is carried.
#
# The initial version of this protocol implements authentication
#  of its operations, but not privacy (i.e., crypto).  Because
#  all the messages are JSON, it's easy to imagine further fields
#  which would configure crypto.  This is TBD.
# The initial version's authentication uses SHA-256 along with
#  a nonce to protect packets from spoofing, modification, or
#  replay.
#
# Each packet thus has a nonce (generated by the system's crypto-
#  quality random number generator) and a SHA-256 derived
#  signature reflecting the shared secret.
#
# The client's initial message indicates the current event
#  serial seen (initially 0).  It specifies how many
#  event details it wants at most, along with whether its wants
#  subject and even body.  The server always indicates
#  the latest event serial, and considers the events delivered
#  regardless of how many bodies the client wanted to receie.
# Imagine the request is
#  {nextev: 100, detail: 2, nevent: 1}
# and that the server next event # is 103 (i.e., 100, 101 and
#  102 have arrived).  The server will respond:
#  {nextev: 103, events: [["xmpp", "Joe"]]}
# which tells the client to ask next for 103, and it can
#  display that the first event (100) had a subject line
#  of "event100-subject" from an XMPP message.
#
# Event details are reported with the specified detail.
#  Leve1 1 is just the event source type (XMPP, SMS, ...).
#  Level 2 is the sender.  Level 3 is the subject line,
#  level 4 is a message body.  In the above example the
#  client requested the first two items, thus seeing
#  that it's an XMPP message from Joe.  At detail 0, you
#  would only see that there were new events, but no other
#  detail.
#
import socket, sys, json, time, os
import dbus, notify2, hashlib
from Crypto.Cipher import AES

# Are LEDs available for notification indication?
LED = "/sys/class/leds/red"
leds = False

# Initial condition, no events ever seen
serial = 0

# Packet sequence number, bumped for each new exchange
pakseq = 0

# How long to wait for initial/immediate response
# (This is the starting timeout, which backs off with each
#  retry.)
WAITRESP = 1

# How long to hold off network activity after seeing a
#  network failure
WAITNET = 60

# Max sized message
# (You can turn this up, but you really need to start thinking
#  about REST and TCP.)
MAXMSG = 1024

# Defend against replays
used_nonces = set()

# Hook for logging
def log(s):
    sys.stderr.write(s)
    sys.stderr.write('\n')

# Quick/easy way to turn dict into an ob with those k/v as attrs
class DictOb(object):
    def __init__(self, d):
        for k,v in d.iteritems():
            setattr(self, str(k), v)

# XOR a byte range into one half its size
def fold(buf):
    assert (len(buf) & 1) == 0
    l = len(buf)/2
    return bytes((c1 ^ c2)
        for c1,c2 in zip(buf[:l], buf[l:]))

# Display bytes in hex
def tohex(buf):
    return ''.join(("%02x" % (c,)) for c in buf)
def fromhex(buf):
    res = bytearray()
    while buf:
        res.append(buf[:2].decode("hex"))
        buf = buf[2:]
    return res

# SHA256 adapted signature
def calchash(buf):
    global cfg

    sh = hashlib.sha256()
    sh.update(buf)
    sh.update(nonce)
    sh.update(cfg.password)
    return fold(fold(sh.digest()))

# Configuration, a DictOb
cfg = None
# Cache of SHA256 of cfg.password
hashedpw = None

# DBus monitoring.  We need to know if the device is on/active, since
#  we only want to blink the LED if it's off (and only until it
#  goes back on)
"""
targ="interface='org.freedesktop.DBus.Properties'," \
    "member='PropertiesChanged'"
   string "com.canonical.UnityGreeter"
   array [
      dict entry(
         string "IsActive"
         variant             boolean true
      )
   ]
   array [
   ]
"""

# LED device manipulation
def set_led(base, val):
    f = open(LED + "/" + base, "w")
    f.write(val)
    f.close()
def get_led(base):
    f = open(LED + "/" + base, "r")
    res = f.read()
    f.close()
    return res

# Set LED mode, if we can
def setup_leds():
    global leds

    try:
        set_led("on_off_ms", "500 2500")
        brt = get_led("max_brightness")
        set_led("brightness", brt)
        set_led("rgb_start", "0")
        leds = True
    except:
        pass

# Encode and sign this message
#
# We're using 64 bits of nonce, and 64 bits of folded SHA256
def wrap_msg(d, crypt=False):
    global cfg, hashedpw

    # String rep of actual operation
    inner = json.dumps(d)

    # 64 bits of nonce
    nonce = os.urandom(8)

    # And collapse 256 bits of sha256 to 64 bits too
    # (We hash the content, nonce, and shared secret.)
    sig = calchash(inner, nonce)

    # Wrap inner into outer
    outer = {"user": cfg.user,
        "sig": tohex(sig),
        "nonce": tohex(nonce)}

    # Encrypt?
    if crypt:
        # Pad to 64 byte boundary
        li = len(inner)
        if li % AES.block_size:
            inner += (" " * (AES.block_size - (li % 64)))
        a = AES.new(hashedpw, AES.MODE_CFB, nonce)

        inner = a.encrypt(inner)
        outer["crypt"] = "AES"

    # Signed and possibly encrypted inner content
    outer["inner"] = inner

    # As a JSON string
    return json.dumps(outer)

# Receive a message, with timeout
# The message is verified for correct sig
def recv_msg(sock, timeout):
    global used_nonces, hashedpw

    targtm = time.time() + timeout
    while True:
        # No more time
        tmo = targtm - time.time()
        if tmo <= 0:
            log(" out of time")
            return None

        # Receive, with timeout
        sock.settimeout(tmo)
        try:
            buf,who = sock.recvfrom(MAXMSG)
        except:
            # Timeout
            log(" timeout")
            return None
        log("pak %s from %s\n" % (buf, who))

        # Valid?
        try:
            # Decode
            outer = json.loads(buf)
            inner = outer["inner"]
            nonce = outer["nonce"]

            # Protect nonce value
            if nonce in used_nonces:
                log(" dup nonce")
                continue

            # Verify sig
            sig = calchash(inner, outer["nonce"])
            if sig != outer["sig"]:
                log(" bad sig")
                continue

            # Crypto?
            if "crypt" in outer:
                if outer["crypt"] != "AES":
                    log(" unknown crypto")
                    continue
                a = AES.new(hashedpw, AES.MODE_CFB, fromhex(nonce))
                inner = a.decrypt(inner)

            # Convert inner
            inner = json.loads(inner)

        except:
            log(" malformed")
            continue

        # Don't use this nonce again
        used_nonces.add(nonce)

        # Here's something signed by our peer
        log(" good pak")
        return inner

# Build message, signed, all that stuff
# Return JSON encoding of it.
def msg(op, subop, vals=None):
    # Start with any params they specified
    if vals is not None:
        req = dict(vals)
    else:
        req = {}

    # Plug in some standard fields
    req["op"] = op
    req["subop"] = subop
    req["pakseq"] = pakseq
    pakseq += 1

    # Sign and maybe encrypt
    buf = wrap_msg(req)

    return buf

# Ping-Pong message exchange.  We said something to them,
#  and we expect to hear something back.
# JSON in each direction.
def pingpong(buf):

    # A new socket each time.  This is an easy way to make
    #  sure we bind to the latest IP address, for instance.
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # Adaptive timeout
    tmo = WAITRESP
    while True:
        log("sending %r" % (req,))
        try:
            sock.sendto(buf, (ipa, port))
        except:
            log(" send failed")
            # With a network outage, hang back for a bit
            time.sleep(WAITNET)
            return Non

        # Get back a response, or None for timeout
        resp = recv_msg(sock, tmo)
        if resp is not None:
            sock.close()
            return resp

        # Didn't reach our server
        log(" timeout")
        tmo *= 2
        if tmo > WAITNET:
            # Backed off to failure
            sock.close()
            return None

# Ping...Pong message behavior.
# This is long polling with UDP.  We send a request, and we expect to
#  hear back from them when they have something, or a null closing
#  message at the timeout.
def ping_pong(buf, timeout):

    # A new socket each time.  This is an easy way to make
    #  sure we bind to the latest IP address, for instance.
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # Request
    log("sending %r" % (req,))
    try:
        sock.sendto(buf, (ipa, port))
    except:
        log(" send failed")
        # With a network outage, hang back for a bit
        time.sleep(WAITNET)
        return Non

    # Get back a response, or None for timeout
    resp = recv_msg(sock, timeout)
    sock.close()

    # None (timeout) or a response
    return resp

# Endless execution, notification client
def run(ipa, port):
    global leds, cfg, hashedpw

    # Get our configuration
    f = open(os.getenv("HOME") + "/.config/notify.json", "r")
    d = json.loads(f.read())
    f.close()
    cfg = DictOb(d)

    # Precalc the hash of our password, needed when used as a key
    #  for AES (which requires a fixed size binary block).
    sh = hashlib.sha256()
    sh.update(cfg.password.encode("utf8"))
    hashedpw = sh.digest()

    # Server parameters
    ipa = cfg.server
    port = cfg.port

    # Prep LEDs for use if possible
    setup_leds()

    # Params; we in particular need to know the server's
    #  intended timeout.
    while True:
        params = pingpong(msg("params", "get"))
        if params is not None:
            break
        time.sleep(WAITNET)

    # This is how long they'll hold a notify/get pending before
    #  sending back a null result.
    # If we request one and don't hear back in this amount of
    #  time, we have a lost packet or something.
    tmo = params["timeout"]

    # Server loop
    while True:
        # Always yield for a second, so no matter
        #  what we never CPU spin hard.
        time.sleep(1)

        # Next round of notifications
        # Request events starting at this serial number
        buf = msg("notify", "get", {
            "serial": serial,
            "detail": cfg.detail,
            "nmsg": cfg.nmsg})
        resp = pingpong(buf, tmo*1.1)

        # Failure
        if resp is None:
            time.sleep(WAITNET)
            continue

        # Nothing happened
        if resp["serial"] == serial:
            continue

        # New messages
        notify(resp)

if __name__ == "__main__":
    run()