forked from becarpenter/graspy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrasp.py
4232 lines (3736 loc) · 156 KB
/
grasp.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
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
"""########################################################
########################################################
#
# Generic Autonomic Signaling Protocol (GRASP)
#
# GRASP engine and API - Experimental version
#
# Module name is 'grasp'
#
# This is a prototype/demo implementation of GRASP in
# Python 3.6 or higher, based on draft-ietf-anima-grasp-15.txt
# It is not guaranteed or validated in any way and is
# both incomplete and probably wrong. It makes no claim
# to be production-quality code. Its main purpose is to
# help improve the protocol specification.
#
# Because it's demonstration code written in an
# interpreted language, performance is slow.
#
# SECURITY WARNINGS:
# - assumes ACP up on all interfaces (or none)
# - doesn't even try wrapping TCP in TLS
# - does not watch for interface up/down changes
#
# LIMITATIONS:
# - only coded for IPv6, any IPv4 is accidental
# - survival of address changes and CPU sleep/wakeup is patchy
# - FQDN and URI locators incompletely supported
# - no code for handling rapid mode negotiation
# - relay code is lazy (no rate control)
# - all unicast transactions use TCP (no unicast UDP)
# - workarounds for defects in Python socket module and
# Windows socket peculiarities. Not tested on Android.
#
# Released under the BSD 2-Clause "Simplified" or "FreeBSD"
# License as follows:
#
# Copyright (C) 2015-2019 Brian E. Carpenter.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with
# or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
# AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
# THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
########################################################
########################################################"""
_version = "15-BC-20190206"
##########################################################
# The following change log records significant changes,
# not small bug fixes.
# Version 05 added proto/port to discovery responses
# 1. Update constants for revised CDDL
# 2. Add fields to discovered locator (class asa_locator) and objective
# registry (class _registered_objective)
# 3. Add option code and fields in response messages
# 4. Update generation and parsing of response messages accordingly
# 5. Change from a global TCP listener to a per-objective TCP listener
# 6. Change register_objective to obtain a TCP port and socket and
# launch its own listener
# 7. Make this listener exit if the objective is deregistered (but only
# if new requests come in, otherwise it sleeps harmlessly for ever)
# 20160601 Added discovery cache timeout, and detection of address changes
# 20160605 Added partial recovery after system sleep
# 20160619 Fixed to allow reentrant calls to listen_neg (and listen_syn)
# Version 06 added no protocol changes
# Version 07 added ttl & locator to flood cache entries, and ttl to discovery response
# 20161003 added bubble output option with tkinter
# Version 08 added partial support of M_INVALID
# Version 09 added the F_NEG_DRY flag, modified M_FLOOD format
# 20170122 added Flag24 handling to API
# 20170124 changed error returns to integers (incompatible change to API)
# 20170221 changed session nonce to store packed locator insted of IPv6Address
# 20170224 improved flag bit handling
# 20170429 port 7017 assigned
# 20170518 added interactive choice of test mode (instead of countdown)
# 20170528 fixed several bugs in discovery relaying
# Version 13 improved calculation of discovery timeouts
# 20170604 added initialisation deferral
# Version 15 should conform to RFC-to-be
# 20170721 multicast addresses ff02::13 and 224.0.0.119 assigned
# 20170819 improved handling for long messages
# 20170824 added skip_dialogue() to API
# 20170929 added send_invalid() to API
# 20171003 added inbound message checking option, fixed bug in M_FLOOD format
# 20171013 replaced inbound checking by full parsing, and use parsed
# messages wherever possible
# 20171023 updated _ass_message() to use 'option' class,
# added multiple locators to M_RESPONSE and O_DIVERT,
# added rapid mode objective to M_RESPONSE
# updated register_obj() and synchronize() APIs accordingly
# 20190126 restructure to put IP address/interface discovery
# in the ACP module. There are now no operating system
# dependencies in the grasp.py module (although some
# may be hidden in imported Python modules).
# 20190206 added socket timeouts when sending discovery responses
# or request messages, since there should always be a listener
##########################################################
####################################
# #
# Python version check #
# #
####################################
import sys
if sys.version_info[0] < 3 or \
(sys.version_info[0] == 3 and sys.version_info[1]) < 4:
raise RuntimeError("Must use Python 3.4 or later")
# Each ASA starts with "import grasp"
# List of main classes and functions included in the API:
def init(self):
__all__ = ['objective', 'asa_locator',
'register_asa', 'deregister_asa', 'register_obj',
'deregister_obj', 'discover',
'req_negotiate', 'negotiate_step', 'negotiate_wait',
'end_negotiate', 'listen_negotiate', 'stop_negotiate',
'synchronize', 'listen_synchronize', 'stop_synchronize',
'flood', 'get_flood', 'expire_flood']
####################################
# #
# Imports #
# #
####################################
import time
import errno
import threading
import queue
import socket
import struct
import ipaddress
import ssl
import random
import binascii
import copy
### for bubbles
try:
import tkinter as tk
from tkinter import font
except:
print("Could not import tkinter. No pretty printing.")
time.sleep(10)
###
try:
import cbor
#import cbor2 as cbor
except:
print("Could not import cbor. Please do 'pip3 install cbor' and try again.")
time.sleep(10)
exit()
try:
import acp
except:
print("Could not import acp. Please copy acp.py to the current directory and try again.")
time.sleep(10)
exit()
try:
acp.new2019()
except:
print("Please update acp.py to the 2019 version and try again.")
time.sleep(10)
exit()
#work-around for Python system error
try:
socket.IPPROTO_IPV6
except:
socket.IPPROTO_IPV6 = 41
#########################################
# A very handy function...
#########################################
def tname(x):
"""-> name of type of x"""
return type(x).__name__
####################################
# #
# Data types and global data #
# #
####################################
####################################
# ASA registry #
####################################
class _asa_instance:
"""Internal use only"""
def __init__(self, nonce, name):
self.nonce = nonce #the ASA's nonce
self.name = name #the ASA's name string
# _asa_registry - list of _asa_instance
# _asa_lock - lock for _asa_registry
####################################
# Objectives & registry #
####################################
class objective:
"""
A GRASP objective:
.name String
.neg True if objective supports negotiation
.dry True if objective supportd dry-run negotiation
.synch True if objective supports synchronization
.loop_count Limit on negotiation steps etc.
.value A valid Python object
"""
def __init__(self, name):
self.name = name #Unique name, string
self.neg = False #Set True if objective supports negotiation
self.dry = False #Set True if objective also supports dry-run negotiation
self.synch = False #Set True if objective supports synch
self.loop_count = GRASP_DEF_LOOPCT #Default starting value
self.value = 0 #Place holder; format undefined
def _oclone(obj):
"""Internal use only"""
###################################################
# Clones an objective for local use
# If you don't use this, you may unintenionally
# modify the caller's objective
# Just do obj=_oclone(obj)
###################################################
cobj=objective(obj.name)
cobj.neg=obj.neg
cobj.dry=obj.dry
cobj.synch=obj.synch
cobj.loop_count=obj.loop_count
cobj.value=obj.value
return cobj
class _registered_objective:
"""Internal use only"""
def __init__(self, objective, asa_nonce):
self.objective = objective
self.asa_id = asa_nonce
self.protocol = socket.IPPROTO_TCP #default
self.locators = [] #list of explicit locators, if any
self.port = 0
self.discoverable = False # not discoverable until first listening
self.local = False # link-local iff True
self.rapid = False # support rapid mode iff True
self.ttl = _discCacheDefTimeOut # discovery cache timeout in milliseconds
self.listening = 0 # counts active listeners
self.listen_q = None
# _obj_registry - list of _registered_objective
# _obj_lock - lock for _obj_registry
####################################
# Discovery cache #
####################################
class _discovered_objective:
"""Internal use only"""
def __init__(self, objective, asa_locators):
self.objective = objective
self.asa_locators = asa_locators #list of asa_locator
self.received = None #objective received in M_RESPONSE
class asa_locator:
"""
Locator for a discovered peer ASA, also used for flooded objectives.
Values:
.locator The actual locator
.protocol Transport protocol number
.port Port number
.ifi Interface identifier via which this was discovered
.expire int(time.monotonic()) value when this entry expires (0=never)
Booleans:
.diverted
.is_ipaddress
.is_fqdn
.is_uri
"""
def __init__(self, locator, ifi, diverted):
self.locator = locator
self.ifi = ifi # Remember which interface this came from
self.diverted = diverted # True iff it was in a Divert option
#Defaults
self.protocol = socket.IPPROTO_TCP
self.port = GRASP_LISTEN_PORT
self.expire = 0
#One of the following must be set when the object is created
#Addresses to be stored in Python ipaddress class
self.is_ipaddress = False
self.is_fqdn = False
self.is_uri = False
# _discovery_cache - list of _discovered_objective
# _disc_lock - lock for _discovery_cache
####################################
# Session ID cache #
####################################
class _session_instance:
"""Internal use only"""
def __init__(self, id_value, id_active, id_source):
self.id_value = id_value #Integer
self.id_active = id_active #True if active
self.id_source = id_source #Source locator of ID if needed (packed)
self.id_dq = None #Queue if discovering
self.id_sock = None #Socket if negotiating
self.id_relayed = False #True if has been relayed
class _session_nonce:
"""Internal use only"""
def __init__(self, id_value, id_source):
self.id_value = id_value #Integer
self.id_source = id_source #Source locator of ID if non-local (packed)
# _session_id_cache - list of _session_instance
# _sess_lock - lock for _session_id_cache
# Session_ID cache contains
# - all currently active Session_IDs
# - foreign source address if any
# - status for each one (in use or inactive)
# - as memory permits, all previously seen Session_IDs (status inactive) to avoid reuse
####################################
# Flood cache #
####################################
class tagged_objective:
"""An objective tagged with its source asa_locator"""
def __init__(self, objective, source):
self.objective = objective
self.source = source # an asa_locator (including expiry time)
# _flood_cache - list of tagged_objective
# _flood_lock - lock for _flood_cache
# Flood cache contains flooded objectives with their values and tagged
# with their source address
####################################
# Classes for message parsing #
####################################
class flooded_objective:
"""
An objective embedded in a flood:
.obj the objective
.loco its locator option, or None
"""
def __init__(self, obj, loco):
self.obj = obj #an objective
self.loco = loco #associated locator option
class message:
"""
A GRASP message:
.mtype message type, integer
.id_value session ID, integer
.id_source source address (packed)
.ttl ttl or waiting time (ms)
.options list of embedded option
.obj embedded objective
.flood_list list of flooded_objective
.content arbitrary content
"""
def __init__(self, mtype):
self.mtype = mtype #message type, integer
self.id_value = 0 #session ID, integer
self.id_source = unspec_address.packed #source address
self.ttl = 0 #ttl or waiting time, integer
self.options = [] #list of options
self.obj = None #embedded objective
self.flood_list = None #list of flooded_objective
self.content = None #arbitrary content
class option:
"""
A GRASP option:
.otype option type, integer
.embedded embedded option if any
.locator if locator option: packed address or string
.protocol if locator option: protocol #
.port if locator option: port #
.reason if decline option: reason string
"""
def __init__(self, otype):
self.otype = otype #option type, integer
self.embedded = [] #list of embedded options (if any)
self.locator = None #if locator option: packed address
#or string
self.protocol = 0 #if locator option: protocol #
self.port = 0 #if locator option: port #
self.reason = None #if decline option: reason string
####################################
# Other global variables #
# #
# Reminder: any of these that get #
# assigned inside any function or #
# thread must be declared 'global' #
# inside that function #
####################################
_grasp_initialised = False #true after GRASP core has been initialised
_skip_dialogue = False #true if ASA calls grasp.skip_dialogue
# _tls_required #true if no ACP
# _secure #true if either ACP or TLS is working
# _rapid_supported #true if rapid mode allowed
# _mcq #FIFO for incoming multicasts
# _drq #FIFO for pending discovery responses
# _my_address #this node's preferred global address
# _my_link_local #this node's preferred link local address
# _session_locator #address used to disambiguate session ids (if initiator field used)
# _ll_zone_ids #list of [IPv6 Zone (interface) index,LL address]
# _said_no_route #flag used by watcher to limit printing
# _mcssocks #list of multicast sending sockets
# _relay_needed #True if multiple interfaces require Discovery/Flood relaying
# _mc_restart #True if system wakeup detected - multicast listeners must restart
# _i_sent_it #session ID of most recent discovery multicast, used in a hack
# test_mode #True iff module is running in test mode
# listen_self #True iff listening to own LL multicasts for testing
# test_divert #True to force a divert message from discovery
# mess_check #True to trigger message check diagnostics
# _make_invalid #True to throw a test M_INVALID
# _make_badmess #True to throw a malformed message
# _dobubbles #True to enable bubble printing
####################################
# GRASP protocol constants #
####################################
# Note: there is no reasonable way to define constants in Python.
# These objects could all be overwritten by programming errors.
M_NOOP = 0
M_DISCOVERY = 1
M_RESPONSE = 2
M_REQ_NEG = 3
M_REQ_SYN = 4
M_NEGOTIATE = 5
M_END = 6
M_WAIT = 7
M_SYNCH = 8
M_FLOOD = 9
M_INVALID = 99
O_DIVERT = 100
O_ACCEPT = 101
O_DECLINE = 102
O_IPv6_LOCATOR = 103
O_IPv4_LOCATOR = 104
O_FQDN_LOCATOR = 105
O_URI_LOCATOR = 106
F_DISC = 0 # valid for discovery
F_NEG = 1 # valid for negotiation
F_SYNCH = 2 # valid for synchronization
F_NEG_DRY = 3 # negotiation is dry-run
ALL_GRASP_NEIGHBORS_6 = ipaddress.IPv6Address('ff02::13') # LL multicast
ALL_GRASP_NEIGHBORS_4 = ipaddress.IPv4Address('224.0.0.119') # LL multicast
GRASP_LISTEN_PORT = 7017 # IANA port number
GRASP_DEF_TIMEOUT = 60000 # milliseconds
GRASP_DEF_LOOPCT = 6
GRASP_DEF_MAX_SIZE = 2048 # max message size
unspec_address = ipaddress.IPv6Address('::') # Used in special cases to indicate link local address
####################################
# Support for flag bits #
####################################
def bit(b):
"""Internal use only"""
# return bit b on
return 2**b
B_DISC = bit(F_DISC)
B_NEG = bit(F_NEG)
B_SYNCH = bit(F_SYNCH)
B_DRY = bit(F_NEG_DRY)
def _flagword(obj):
"""Internal use only"""
#create the flags word for an objective
_f = B_DISC #everything's discoverable
if obj.neg:
_f |= B_NEG
if obj.synch:
_f |= B_SYNCH
if obj.dry:
_f |= B_DRY
return _f
def _flags(flagword):
"""Internal use only"""
#return Boolean flags for an objective
return bool(flagword&B_NEG), bool(flagword&B_SYNCH), \
bool(flagword&B_DRY)
##F_DISC_bits = bit(F_DISC)
##F_NEG_bits = F_DISC_bits|bit(F_NEG)
##F_SYNCH_bits = F_DISC_bits|bit(F_SYNCH)
##F_NEG_DRY_bits = F_NEG_bits|bit(F_NEG_DRY)
####################################
# GRASP engine internal constants #
####################################
_asaRegistryLimit = 100
_sessionCacheLimit = _asaRegistryLimit + 1000
_objRegistryLimit = 200
_discCacheLimit = 500
_discCacheDefTimeOut = 10*GRASP_DEF_TIMEOUT # milliseconds
_floodCacheLimit = 100
_discQlimit = 10
_listenQlimit = 5
_multQlimit = 100
_minRelayGap = 500 # milliseconds (unused, intended for relay throttling)
_discTimeoutUnit = 100 # milliseconds (discovery timeout per hop)
####################################
# List offsets for raw message #
# contents (for poor man's parsing)#
# #
# These constants are used only in #
# the various _parse_ functions, #
# _relay() and _ass_message() #
####################################
_Op_Opt = 0 #option code in an option
_Op_Con = 1 #first specific item in an option
_Op_Proto = 2 #protocol number in a locator option
_Op_Port = 3 #port number in a locator option
_Pl_Msg = 0 #message type in a message payload
_Pl_Ses = 1 #session ID in a message payload
_Pl_Ini = 2 #initiator in a message payload
_Pl_Con = 2 #first specific item in a normal message payload
_Pl_TTL = _Pl_Ini+1 #TTL in response or flood payload
_Pl_Rloc = _Pl_TTL+1 #locator option in response payload
_Pl_Robj = _Pl_Rloc+1 #objective in response payload
_Pl_FCon = _Pl_TTL+1 #list of [locator,objective] in flood payload
_Pl_Dobj = _Pl_Ini+1 #objective in discovery payload
_Fo_Fobj = 0 #objective in tagged objective in flood
_Fo_Floc = 1 #locator in tagged objective in flood
_Ob_Nam = 0 #name in an objective
_Ob_Flg = 1 #flags in an objective
_Ob_LCt = 2 #loop count in an objective
_Ob_Val = 3 #value object in an objective
####################################
# Error codes and English-language #
# error texts #
####################################
class _error_codes:
"""names for the error codes"""
def __init__(self):
self.ok = 0
self.declined = 1 #"Declined"
self.noReply = 2 #"No reply"
self.unspec = 3 #"Unspecified error"
self.ASAfull = 4 #"ASA registry full"
self.dupASA = 5 #"Duplicate ASA name"
self.noASA = 6 #"ASA not registered"
self.notYourASA = 7 #"ASA registered but not by you"
self.notBoth = 8 #"Objective cannot support both negotiation and synchronization"
self.notDry = 9 #"Dry-run allowed only with negotiation"
self.notOverlap = 10 #"Overlap not supported by this implementation"
self.objFull = 11 #"Objective registry full"
self.objReg = 12 #"Objective already registered"
self.notYourObj = 13 #"Objective not registered by this ASA"
self.notObj = 14 #"Objective not found"
self.notNeg = 15 #"Objective not negotiable"
self.noSecurity = 16 #"No security"
self.noDiscReply = 17 #"No reply to discovery"
self.sockErrNegRq = 18 #"Socket error sending negotiation request"
self.noSession = 19 #"No session"
self.noSocket = 20 #"No socket"
self.loopExhausted = 21 #"Loop count exhausted"
self.sockErrNegStep = 22 #"Socket error sending negotiation step"
self.noPeer = 23 #"Negotiation peer not listening"
self.CBORfail = 24 #"CBOR decode failure"
self.invalidNeg = 25 #"Invalid Negotiate message"
self.invalidEnd = 26 #"Invalid end message"
self.noNegReply = 27 #"No reply to negotiation step"
self.noValidStep = 28 #"No valid reply to negotiation step"
self.sockErrWait = 29 #"Socket error sending wait message"
self.sockErrEnd = 30 #"Socket error sending end message"
self.IDclash = 31 #"Incoming request Session ID clash"
self.notSynch = 32 #"Not a synchronization objective"
self.notFloodDisc = 33 #"Not flooded and no reply to discovery"
self.sockErrSynRq = 34 #"Socket error sending synch request"
self.noListener = 35 #"Synchronization peer not listening"
self.noSynchReply = 36 #"No reply to synchronization request"
self.noValidSynch = 37 #"No valid reply to synchronization request"
self.invalidLoc = 38 #"Invalid locator"
errors = _error_codes()
etext = ["OK",
"Declined",
"No reply",
"Unspecified error",
"ASA registry full",
"Duplicate ASA name",
"ASA not registered",
"ASA registered but not by you",
"Objective cannot support both negotiation and synchronization",
"Dry-run allowed only with negotiation",
"Overlap not supported by this implementation",
"Objective registry full",
"Objective already registered",
"Objective not registered by this ASA",
"Objective not found",
"Objective not negotiable",
"No security",
"No reply to discovery",
"Socket error sending negotiation request",
"No session",
"No socket",
"Loop count exhausted",
"Socket error sending negotiation step",
"Negotiation peer not listening",
"CBOR decode failure",
"Invalid Negotiate message",
"Invalid end message",
"No reply to negotiation step",
"No valid reply to negotiation step",
"Socket error sending wait message",
"Socket error sending end message",
"Incoming request Session ID clash",
"Not a synchronization objective",
"Not flooded and no reply to discovery",
"Socket error sending synch request",
"Synchronization peer not listening",
"No reply to synchronization request",
"No valid reply to synchronization request",
"Invalid locator"
]
####################################
# #
# Registration functions #
# #
####################################
####################################
#
# Tell GRASP to skip initial dialogue
#
####################################
def skip_dialogue(testing=False, selfing=False, diagnosing=False):
"""
####################################################################
# skip_dialogue(testing=False, selfing=False, diagnosing=False)
#
# Tells GRASP to skip initial dialogue
#
# Default is not test mode and not listening to own multicasts
# and not printing message syntax diagnostics
# Must be called before register_asa()
#
# No return value
####################################################################
"""
global _skip_dialogue, test_mode, listen_self, mess_check, _grasp_initialised
if _grasp_initialised:
return
_skip_dialogue = True
test_mode = testing
listen_self = selfing
mess_check = diagnosing
def register_asa(asa_name):
"""
####################################################################
# register_asa(asa_name)
#
# Tells the GRASP engine that a new ASA is starting up.
# Also triggers GRASP initialisation if needed.
#
# return zero, asa_nonce if successful
# return errorcode, None if failure
#
# Note - the ASA must store the asa_nonce (an opaque Python object)
# and use it in every subsequent GRASP call.
####################################################################
"""
if not _grasp_initialised:
_initialise_grasp()
_asa_lock.acquire()
if len(_asa_registry) >= _asaRegistryLimit:
# no free space, fail
_asa_lock.release()
return errors.ASAfull, None
elif ([clash for clash in _asa_registry if clash.name == asa_name]):
# duplicate, fail
_asa_lock.release()
return errors.dupASA, None
else:
#append new one
asa_nonce = _new_session(None)
new_asa = _asa_instance(asa_nonce, asa_name)
_asa_registry.append(new_asa)
_asa_lock.release()
return errors.ok, asa_nonce
def deregister_asa(asa_nonce, asa_name):
"""
####################################################################
# deregister_asa(asa_nonce, asa_name)
#
# Tells the GRASP engine that an ASA is going away.
# Deregisters its objectives too.
# We need this to happen automatically when an ASA crashes.
#
# return zero if successful
# return errorcode if failure
####################################################################
"""
# Stop all operations for this ASA (if registered with same PID)
# and remove all relevant data.
# (Need this to happen automatically if ASA exits)
i = _retrieve_asa(asa_name)
if i == -1:
return errors.noASA
elif (_asa_registry[i].nonce != asa_nonce):
_asa_lock.release()
return errors.notYourASA
else:
# Stops all operations for this ASA
# by removing all registered objectives
# and the ASA itself from their registries.
# We have to keep the ASA lock for the whole time!
_obj_lock.acquire()
# The following loop looks unPythonesque, because
# it shortens the list that it's looping over, so
# it has to be done the old-fashioned way.
j=0
while j < len(_obj_registry):
x = _obj_registry[j]
if x.asa_id == asa_nonce:
#found a match - delete it, which shortens the list
del _obj_registry[j]
else:
j += 1
_obj_lock.release()
del _asa_registry[i]
#mark the nonce as inactive
_update_session(_session_instance(asa_nonce,False,None))
_asa_lock.release()
return errors.ok
def register_obj(asa_nonce, obj, ttl=None, discoverable=False, \
overlap=False, local=False, rapid=False, locators=[]):
"""
####################################################################
# register_obj(asa_nonce, objective,ttl=None, discoverable=False,
# overlap=False, local=False, locators=[])
#
# Store an objective that this ASA supports and may modify.
#
# The objective becomes available for discovery only after
# a call to listen_negotiate() or listen_synchronize()
# unless the optional parameter discoverable is True.
#
# ttl is discovery time to live in milliseconds; the default
# is the GRASP default timeout.
#
# if discoverable==True, the objective is *immediately* discoverable
# even if the ASA is not listening.
#
# if overlap==True, more than one ASA may register this objective.
# (NOT supported in this implementation.)
#
# if local==True, discovery must return a link-local address
#
# if rapid==True, supplied value should be used in rapid mode
# (only works for synchronization)
#
# locators is a list of explicit asa_locators, trumping normal
# discovery
#
# The ASA may negotiate the objective or send synch or flood data.
# (Not needed if the ASA only wants to receive synch or flood data.)
# May be repeated for multiple objectives.
#
# return zero if successful
# return errorcode if failure
####################################################################
"""
if _no_nonce(asa_nonce):
return errors.noASA
if (obj.neg and obj.synch) or (obj.dry and obj.synch):
return errors.notBoth
if (not obj.neg) and obj.dry:
return errors.notDry
if overlap:
return errors.notOverlap
#Clone the objective to avoid unintended side effects:
#the copy in the registry will be distinct from the instance
#supplied by the ASA
obj=_oclone(obj)
#Search the registry to detect any duplicate
_obj_lock.acquire()
if len(_obj_registry) >= _objRegistryLimit:
# no free space, fail
_obj_lock.release()
return errors.objFull
elif ([clash for clash in _obj_registry if clash.objective.name == obj.name]):
# duplicate, fail
_obj_lock.release()
return errors.objReg
else:
#start a listener thread if needed
if obj.neg or obj.synch or obj.dry:
listen_sock=socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_sock.bind(('',0))
listen_port = listen_sock.getsockname()[1]
_tcp_listen(listen_sock).start()
else:
listen_port = 0
#append new one
new_obj = _registered_objective(obj, asa_nonce)
new_obj.port = listen_port
new_obj.discoverable = discoverable # whether it can be discovered immediately
new_obj.local = local # whether it must be assigned a link-local address
new_obj.rapid = rapid # whether it should support rapid mode
new_obj.locators = locators
if tname(ttl) == "int" and ttl>0:
new_obj.ttl = ttl
_obj_registry.append(new_obj)
_obj_lock.release()
return errors.ok
def deregister_obj(asa_nonce, obj):
"""
####################################################################
# deregister_obj(asa_nonce, objective)
#
# Stops all operations on this objective (if registered)
# by removing it from the registry.
#
# return zero if successful
# return errorcode if failure
####################################################################
"""
if _no_nonce(asa_nonce):
return errors.noASA
_obj_lock.acquire()
# Can't use a comprehension because we need the actual
# list entry in order to delete it.
for i in range(len(_obj_registry)):
x =_obj_registry[i]
if x.objective.name == obj.name:
#found it
if x.asa_id != asa_nonce:
_obj_lock.release()
return errors.notYourObj
#now delete it
del _obj_registry[i]
_obj_lock.release()
return errors.ok
_obj_lock.release()
return errors.notObj
####################################
# #
# Support function: #
# Receive complete raw message #
# from TCP socket. #
# #
####################################
def _recvraw(sock):
"""Internal use only"""
rawmsg, send_addr = sock.recvfrom(GRASP_DEF_MAX_SIZE)
if len(rawmsg) > 1200: # close to minimum IPv6 MTU
#need to check briefly for a second chunk
ttprint("Raw chunk length",len(rawmsg),"; waiting for more")
_to = sock.gettimeout()
sock.settimeout(0.2)
try:
raw2, _ = sock.recvfrom(GRASP_DEF_MAX_SIZE)
if len(raw2):
rawmsg += raw2
except:
pass #timeout, assume there's nothing more
sock.settimeout(_to)
return rawmsg, send_addr
####################################
# #
# Discovery functions #
# #
####################################
def discover(asa_nonce, obj, timeout, flush=False, relay_ifi=False, relay_snonce=None):
"""
##############################################################