/
listener.py
2054 lines (1900 loc) · 77.3 KB
/
listener.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
"""
Listener Thread
"""
import base64
import importlib
import json
import os
import pkgutil
import sys
import socket
import logging
import time
import select
import shutil
import traceback
import uuid
import fnmatch
import re
import datetime
from foreign.six.moves.urllib.parse import urlparse, parse_qs # pylint: disable=import-error
from subprocess import Popen
from errno import EADDRINUSE, ECONNRESET, EPIPE, EBADF
try:
import ssl
import foreign.h2 as h2
from foreign.h2.config import H2Configuration
from foreign.h2.connection import H2Connection
from foreign.hyper.common.headers import HTTPHeaderMap
has_ssl = True
except Exception:
has_ssl = False
try:
import foreign.jwt as jwt
from foreign.jwt.algorithms import RSAAlgorithm
has_jwt = True
except Exception:
has_jwt = False
import foreign.six as six
import daemon.shared as shared
import core.exceptions as ex
from foreign.six.moves import queue
from env import Env
from utilities.storage import Storage
from core.comm import Headers
from utilities.chunker import chunker
from utilities.naming import split_path, fmt_path, factory, split_fullname
from utilities.files import makedirs
from utilities.drivers import driver_import
from utilities.lazy import set_lazy, lazy, unset_lazy
from utilities.converters import print_duration
from utilities.string import bencode, bdecode
from utilities.uri import Uri
from utilities.render.listener import fmt_listener
if six.PY2:
class _ConnectionResetError(Exception):
pass
class _ConnectionAbortedError(Exception):
pass
ConnectionResetError = _ConnectionResetError
ConnectionAbortedError = _ConnectionAbortedError
RE_LOG_LINE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]:[0-6][0-9]:[0-6][0-9],[0-9]{3} .* \| ")
JANITORS_INTERVAL = 0.5
ICON = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAABigAAAYoBM5cwWAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAJKSURBVDiNbZJLSNRRFMZ/5/5HbUidRSVSuGhMzUKiB9SihYaJQlRSm3ZBuxY9JDRb1NSi7KGGELRtIfTcJBjlItsohT0hjcpQSsM0CMfXzP9xWszM35mpA/dy7+Wc7/vOd67wn9gcuZ8bisa3xG271LXthTdNL/rZ0B0VQbNzA+mX2ra+kL04d86NxY86QpEI8catv0+SIyOMNnr6aa4ba/aylL2cTdVI6tBwrbfUXvKeOXY87Ng2jm3H91dNnWrd++U89kIx7jw48+DMf0bcOtk0MA5gABq6egs91+pRCKc01lXOnG2tn4yAKUYkmWpATDlqevRjdb4PYMWDrSiVqIKCosMX932vAYoQQ8bCgGoVajcDmIau3jxP9bj6/igoFqiTuCeLkDQQQOSEDm3PMQEnfxeqhYlSH6Si6WF4EJjIZE+1AqiGCAZ3GoT1yYcEuSqqMDBacOXMo5JORDJBRJa9V0qMqkiGfHwt1vORlW3ND9ZdB/mZNDANJNmgUXcsnTmx+WCBvuH8G6/GC276BpLmA95XMxvVQdC5NOYkkC8ocG9odRCRzEkI0yzF3pn+SM2SKrfJiCRQYp9uqf9l/p2E3pIdr20DkCvBS6o64tMvtzLTfmTiQlGh05w1iSFyQ23+R3rcsjsqrlPr4X3Q5f6nOw7/iOwpX+wEsyLNwLcIB6TsSQzASon+1n83unbboTtiaczz3FVXD451VG+cawfyEAHPGcdzruPOHpOKp39SdcvzyAqdOh3GsyoBsLxJ1hS+F4l42Xl/Abn0Ctwc5dldAAAAAElFTkSuQmCC")
ROUTED_ACTIONS = {
"node": {
"logs": "node_logs",
"backlogs": "node_backlogs",
},
"object": {
"logs": "object_logs",
"backlogs": "object_backlogs",
},
}
class Close(Exception):
pass
class DontClose(Exception):
pass
class Listener(shared.OsvcThread):
name = "listener"
stage = "init"
events_grace_period = True
sock_tmo = 1.0
sockmap = {}
last_janitors = 0
crl_expire = 0
crl_mode = None
sockux = None
sockuxh2 = None
sock = None
tls_sock = None
tls_context = None
tls_port = -1
tls_addr = ""
port = -1
addr = ""
handlers = {}
@lazy
def certfs(self):
mod = driver_import("resource", "fs")
res = mod.Fs(rid="fs#certs", mount_point=Env.paths.certs, device="tmpfs", fs_type="tmpfs", mount_options="rw,nosuid,nodev,noexec,relatime,size=1m")
set_lazy(res, "log", self.log)
return res
@lazy
def ca(self):
secpaths = shared.NODE.oget("cluster", "ca")
if not secpaths:
secpaths = ["system/sec/ca-" + self.cluster_name]
secs = []
for secpath in secpaths:
secname, namespace, kind = split_path(secpath)
sec = factory("sec")(secname, namespace=namespace, volatile=True, node=shared.NODE)
if not sec.exists():
self.log.warning("ca %s does not exist: ignore", secpath)
continue
if "certificate_chain" not in sec.data_keys():
self.log.warning("ca %s has no certificate key: ignore", secpath)
continue
secs.append(sec)
return secs
@lazy
def cert(self):
secpath = shared.NODE.oget("cluster", "cert")
if secpath is None:
secpath = "system/sec/cert-" + self.cluster_name
secname, namespace, kind = split_path(secpath)
return factory("sec")(secname, namespace=namespace, volatile=True, node=shared.NODE)
def prepare_certs(self):
makedirs(Env.paths.certs)
if Env.sysname == "Linux" and self.ca and self.cert and self.cert.exists():
self.certfs.start()
os.chmod(Env.paths.certs, 0o0755)
# concat ca certificates
ca_certs = os.path.join(Env.paths.certs, "ca_certificates")
try:
open(ca_certs, 'w').close()
except OSError:
pass
for ca in self.ca:
data = ca.decode_key("certificate_chain")
if data is None:
self.log.warning("secret key %s.%s is not set" % (ca.path, "certificate_chain"))
continue
self.log.info("add %s certificate chain to %s", ca.path, ca_certs)
with open(ca_certs, "a") as fo:
fo.write(bdecode(data))
# listener cert chain
data = self.cert.decode_key("certificate_chain")
if data is None:
raise ex.InitError("secret key %s.%s is not set" % (self.cert.path, "certificate_chain"))
cert_chain = os.path.join(Env.paths.certs, "certificate_chain")
self.log.info("write %s", cert_chain)
# listener private key
with open(cert_chain, "w") as fo:
fo.write(bdecode(data))
data = self.cert.decode_key("private_key")
if data is None:
raise ex.InitError("secret key %s.%s is not set" % (self.cert.path, "private_key"))
# listener private key
private_key = os.path.join(Env.paths.certs, "private_key")
self.log.info("write %s", private_key)
with open(private_key, "w+") as fo:
pass
os.chmod(private_key, 0o0600)
with open(private_key, "w") as fo:
fo.write(bdecode(data))
# revocations
crl_path = self.fetch_crl()
return ca_certs, cert_chain, private_key, crl_path
def fetch_crl(self):
crl = shared.NODE.oget("listener", "crl")
if not crl:
return
if crl == Env.paths.crl:
self.crl_mode = "internal"
try:
os.unlink(crl)
except OSError:
pass
buff = ""
for ca in self.ca:
ca.unset_lazy("cd")
if "crl" not in ca.data_keys():
continue
try:
buff += bdecode(ca.decode_key("crl"))
except Exception as exc:
self.log.error("decode %s crl error: %s", ca.path, exc)
if buff:
try:
with open(crl, "w") as fo:
fo.write(buff)
return crl
except Exception as exc:
self.log.error("install %s error: %s", crl, exc)
return
self.crl_mode = "external"
if os.path.exists(crl):
return crl
crl_path = os.path.join(Env.paths.certs, "certificate_revocation_list")
secure = shared.NODE.oget("node", "secure_fetch")
try:
with Uri(crl, secure=secure).fetch() as fpath:
shutil.copy(fpath, crl_path)
# TODO: extract expire from crl
self.crl_expire = time.time() + 60*60*24
return crl_path
except Exception as exc:
self.log.warning("crl fetch failed: %s", exc)
return
def get_http2_ssl_context(self):
"""
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
"""
ca_certs, cert_chain, private_key, crl = self.prepare_certs()
# Get the basic context from the standard library.
ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
#ctx.verify_mode = ssl.CERT_REQUIRED
ctx.verify_mode = ssl.CERT_OPTIONAL
ctx.load_cert_chain(cert_chain, keyfile=private_key)
ctx.load_verify_locations(ca_certs)
if crl:
self.log.info("tls crl %s", crl)
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
ctx.load_verify_locations(crl)
self.log.info("tls stats: %s", ctx.cert_store_stats())
# RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
# or higher. Disable TLS 1.1 and lower.
ctx.options |= (
ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
)
# RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
# compression.
ctx.options |= ssl.OP_NO_COMPRESSION
# RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
# support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
# blacklist defined in this section allows only the AES GCM and ChaCha20
# cipher suites with ephemeral key negotiation.
ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
# We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
# be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
ctx.set_alpn_protocols(["h2", "http/1.1"])
try:
ctx.set_npn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
return ctx
def run(self):
shared.NODE.listener = self
self.set_tid()
self.last_relay_janitor = 0
self.log = logging.LoggerAdapter(logging.getLogger(Env.nodename+".osvcd.listener"), {"node": Env.nodename, "component": self.name})
self.events_clients = []
self.stats = Storage({
"sessions": Storage({
"accepted": 0,
"auth_validated": 0,
"tx": 0,
"rx": 0,
"alive": Storage({}),
"clients": Storage({})
}),
})
self.register_handlers()
self.setup_socks()
self.stage = "ready"
while True:
try:
self.do()
self.update_status()
except socket.error as exc:
self.log.warning(exc)
self.setup_socks()
except Exception as exc:
self.log.exception(exc)
if self.stopped():
for sock in self.sockmap.values():
sock.close()
self.join_threads()
if Env.sysname == "Linux":
self.certfs.stop()
self.exit()
def status(self, **kwargs):
data = shared.OsvcThread.status(self, **kwargs)
data["stats"] = self.stats
data["config"] = {
"port": self.port,
"addr": self.addr,
}
return data
def reconfigure(self):
shared.NODE.listener = self
unset_lazy(self, "ca")
unset_lazy(self, "cert")
unset_lazy(self, "certfs")
self.setup_socks()
def register_handlers(self):
self.register_core_handlers()
self.register_driver_handlers()
def register_driver_handlers(self):
from utilities.drivers import iter_drivers
from core.objects.svcdict import KEYS, SECTIONS
for mod in iter_drivers(SECTIONS):
if not hasattr(mod, "DRIVER_HANDLERS"):
continue
for handler_class in mod.DRIVER_HANDLERS:
handler = handler_class()
for method, path in handler.routes:
path = "drivers/resource/%s/%s/%s" % (mod.DRIVER_GROUP, mod.DRIVER_BASENAME, path)
self.handlers[(method, path)] = handler
if method:
self.log.info("register handler %s /%s", method, path)
def register_core_handlers(self):
def onerror(name):
import traceback
traceback.print_exc()
handlers_path = [os.path.join(Env.paths.pathsvc, Env.package, "daemon", "handlers")]
for modinfo in pkgutil.walk_packages(handlers_path, 'daemon.handlers.', onerror=onerror):
if hasattr(modinfo, "ispkg"):
name = modinfo.name
ispkg = modinfo.ispkg
else:
name = modinfo[1]
ispkg = modinfo[2]
if ispkg:
continue
if name.split(".")[-1] not in ("get", "post"):
continue
try:
mod = importlib.import_module(name)
handler = mod.Handler()
if handler.path in self.handlers:
continue
for method, path in handler.routes:
self.handlers[(method, path)] = handler
if method:
self.log.info("register handler %s /%s", method, path)
except Exception as exc:
self.alert("error", "error registering handler %s: %s" % (name, exc))
continue
def do(self):
self.reload_config()
ts = time.time()
if ts > self.last_janitors + JANITORS_INTERVAL:
self.janitor_crl()
self.janitor_procs()
self.janitor_threads()
self.janitor_events()
self.janitor_relay()
self.last_janitors = ts
fds = select.select([fno for fno in self.sockmap], [], [], self.sock_tmo)
if self.sock_tmo and fds == ([], [], []):
return
for fd in fds[0]:
sock = self.sockmap[fd]
try:
conn = None
conn, addr = sock.accept()
self.stats.sessions.accepted += 1
if fd == self.sockux.fileno():
tls = False
addr = ["local"]
scheme = "raw"
encrypted = False
elif fd == self.sockuxh2.fileno():
tls = False
addr = ["local"]
scheme = "h2"
encrypted = False
elif fd == self.sock.fileno():
scheme = "raw"
tls = False
encrypted = True
elif fd == self.tls_sock.fileno():
scheme = "h2"
tls = True
encrypted = False
else:
print("bug")
continue
if addr[0] not in self.stats.sessions.clients:
self.stats.sessions.clients[addr[0]] = Storage({
"accepted": 0,
"auth_validated": 0,
"tx": 0,
"rx": 0,
})
self.stats.sessions.clients[addr[0]].accepted += 1
#self.log.info("accept %s", str(addr))
except socket.timeout:
continue
except OSError as exc:
if conn and exc.errno == EBADF:
conn.close()
continue
except ConnectionAbortedError:
if conn:
conn.close()
continue
except Exception as exc:
self.log.exception(exc)
if conn:
conn.close()
continue
try:
thr = ClientHandler(self, conn, addr, encrypted, scheme, tls, self.tls_context)
thr.start()
self.threads.append(thr)
except RuntimeError as exc:
self.log.warning(exc)
conn.close()
def janitor_crl(self):
if not self.tls_sock:
return
if not self.crl_mode:
return
try:
mtime = os.path.getmtime(Env.paths.crl)
except Exception:
mtime = 0
change = False
has_crl = False
if self.crl_mode == "internal":
for ca in self.ca:
ca.unset_lazy("cd")
if "crl" in ca.data_keys():
has_crl = True
try:
refmtime = os.path.getmtime(ca.paths.cf)
except Exception:
continue
if mtime >= refmtime:
continue
change = True
self.log.info("refresh crl: installed version is %s older than %s", print_duration(refmtime-mtime), ca.path)
if not has_crl and os.path.exists(Env.paths.crl):
try:
self.log.info("remove %s", Env.paths.crl)
os.unlink(Env.paths.crl)
change = True
except Exception as exc:
self.log.warning("remove %s: %s", Env.paths.crl, exc)
elif self.crl_mode == "external":
if mtime and mtime <= self.crl_expire:
self.log.info("refresh crl: installed version is expired since %s", print_duration(self.crl_expire-mtime))
change = True
if change:
self.setup_socktls(force=True)
def janitor_relay(self):
"""
Purge expired relay.
"""
now = time.time()
if now - self.last_relay_janitor < shared.RELAY_JANITOR_INTERVAL:
return
self.last_relay_janitor = now
with shared.RELAY_LOCK:
for key in [k for k in shared.RELAY_DATA]:
age = now - shared.RELAY_DATA[key]["updated"]
if age > shared.RELAY_SLOT_MAX_AGE:
self.log.info("drop relay slot %s aged %s", key, print_duration(age))
del shared.RELAY_DATA[key]
def janitor_events(self):
"""
Send queued events to all subscribed clients.
Don't dequeue messages during the first 2 seconds of the listener lifetime,
so clients have a chance to reconnect after a daemon restart and loose an
event.
"""
if self.events_grace_period:
if time.time() > self.created + 2:
self.events_grace_period = False
else:
return
done = []
while True:
try:
event = shared.EVENT_Q.get(False, 0)
except queue.Empty:
break
to_remove = []
for idx, thr in enumerate(self.events_clients):
if thr not in self.threads:
to_remove.append(idx)
continue
# make a copy, filter_event may change data, avoid being replaced while queued
fevent = self.filter_event(json.loads(json.dumps(event)), thr)
if fevent is None:
continue
if thr.h2conn:
if not thr.events_stream_ids:
to_remove.append(idx)
continue
thr.event_queue.put(fevent)
for idx in to_remove:
try:
del self.events_clients[idx]
except IndexError:
pass
def filter_event(self, event, thr):
if event is None:
return
if thr.selector in (None, "**") and (thr.usr is False or "root" in thr.usr_grants):
# root and no selector => fast path
return event
namespaces = thr.get_namespaces()
kind = event.get("kind")
if kind == "full":
return event
elif kind == "patch":
return self.filter_patch_event(event, thr, namespaces)
elif kind == "event":
return self.filter_event_event(event, thr, namespaces)
def filter_event_event(self, event, thr, namespaces):
def valid(change):
try:
path = event["data"]["path"]
except KeyError:
return True
if thr.selector and not self.match_object_selector(thr.selector, namespaces=namespaces, path=path):
return False
return False
if valid(event):
return event
return None
def filter_patch_event(self, event, thr, namespaces):
def filter_change(change):
try:
key, value = change
except:
key = change[0]
value = None
try:
key_len = len(key)
except:
return change
if key_len == 0:
if value is None:
return change
value = self.filter_daemon_status(value, namespaces=namespaces, selector=thr.selector)
return [key, value]
elif key[0] == "monitor":
if key_len == 1:
if value is None:
return change
value = self.filter_daemon_status({"monitor": value}, namespaces=namespaces, selector=thr.selector)["monitor"]
return [key, value]
if key[1] == "services":
if key_len == 2:
if value is None:
return change
value = dict((k, v) for k, v in value.items() if self.match_object_selector(thr.selector, namespaces=namespaces, path=k))
return [key, value]
if self.match_object_selector(thr.selector, namespaces=namespaces, path=key[2]):
return change
else:
return
if key[1] == "nodes":
if key_len == 2:
if value is None:
return change
value = self.filter_daemon_status({"monitor": {"nodes": value}}, namespaces=namespaces, selector=thr.selector)["monitor"]["nodes"]
return [key, value]
if key_len == 3:
if value is None:
return change
value = self.filter_daemon_status({"monitor": {"nodes": {key[2]: value}}}, namespaces=namespaces, selector=thr.selector)["monitor"]["nodes"][key[2]]
return [key, value]
if key[3] == "services":
if key_len == 4:
if value is None:
return change
value = self.filter_daemon_status({"monitor": {"nodes": {key[2]: {"services": value}}}}, namespaces=namespaces, selector=thr.selector)["monitor"]["nodes"][key[2]]["services"]
return [key, value]
if key[4] == "status":
if key_len == 5:
if value is None:
return change
value = dict((k, v) for k, v in value.items() if self.match_object_selector(thr.selector, namespaces=namespaces, path=k))
return [key, value]
if self.match_object_selector(thr.selector, namespaces=namespaces, path=key[5]):
return change
else:
return
if key[4] == "config":
if key_len == 5:
if value is None:
return change
value = dict((k, v) for k, v in value.items() if self.match_object_selector(thr.selector, namespaces=namespaces, path=k))
return [key, value]
if self.match_object_selector(thr.selector, namespaces=namespaces, path=key[5]):
return change
else:
return
return change
changes = []
for change in event.get("data", []):
filtered_change = filter_change(change)
if filtered_change:
changes.append(filtered_change)
# print("ACCEPT", thr.usr.name if thr.usr else "", filtered_change)
#else:
# print("DROP ", thr.usr.name if thr.usr else "", change)
event["data"] = changes
return event
def bind_inet(self, sock, addr, port):
"""
Retry bind until the error is no longer "in use"
"""
while True:
if self.stopped():
break
try:
sock.bind((addr, port))
break
except socket.error as exc:
if exc.errno == EADDRINUSE:
time.sleep(0.5)
continue
raise
def setup_socktls(self, force=False):
self.vip
if not has_ssl:
self.log.info("skip tls listener init: ssl module import error")
return
port = shared.NODE.oget("listener", "tls_port")
addr = shared.NODE.oget("listener", "tls_addr")
if self.tls_port < 0 or not self.tls_addr:
self.tls_port = port
self.tls_addr = addr
elif force or port != self.tls_port or addr != self.tls_addr:
try:
self.tls_sock.close()
except socket.error:
pass
try:
del self.sockmap[self.tls_sock.fileno()]
except KeyError:
pass
self.tls_port = port
self.tls_addr = addr
else:
self.log.info("tls listener %s config unchanged", fmt_listener(self.tls_addr, self.tls_port))
return
try:
addrinfo = socket.getaddrinfo(self.tls_addr, None)[0]
self.tls_context = self.get_http2_ssl_context()
self.tls_addr = addrinfo[4][0]
if ":" in self.tls_addr:
af = socket.AF_INET6
else:
af = socket.AF_INET
self.tls_sock = socket.socket(af, socket.SOCK_STREAM)
self.tls_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.bind_inet(self.tls_sock, self.tls_addr, self.tls_port)
self.tls_sock.listen(128)
self.tls_sock.settimeout(self.sock_tmo)
except socket.error as exc:
self.alert("error", "bind tls listener %s error: %s", fmt_listener(self.tls_addr, self.tls_port), exc)
return
except ex.InitError as exc:
self.log.info("skip tls listener init: %s", exc)
return
except Exception as exc:
self.log.info("failed tls listener init: %s", exc)
return
self.log.info("listening on %s using http/2 tls with client auth", fmt_listener(self.tls_addr, self.tls_port))
self.sockmap[self.tls_sock.fileno()] = self.tls_sock
def setup_sock(self):
port = shared.NODE.oget("listener", "port")
addr = shared.NODE.oget("listener", "addr")
if self.port < 0 or not self.addr:
self.port = port
self.addr = addr
elif port != self.port or addr != self.addr:
try:
self.sock.close()
except socket.error:
pass
try:
del self.sockmap[self.sock.fileno()]
except KeyError:
pass
self.port = port
self.addr = addr
else:
self.log.info("aes listener %s config unchanged", fmt_listener(self.addr, self.port))
return
try:
addrinfo = socket.getaddrinfo(self.addr, None)[0]
self.addr = addrinfo[4][0]
if ":" in self.addr:
af = socket.AF_INET6
else:
af = socket.AF_INET
self.sock = socket.socket(af, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.bind_inet(self.sock, self.addr, self.port)
self.sock.listen(128)
self.sock.settimeout(self.sock_tmo)
except socket.error as exc:
self.alert("error", "bind aes listener %s error: %s", fmt_listener(self.addr, self.port), exc)
return
self.log.info("listening on %s using aes encryption", fmt_listener(self.addr, self.port))
self.sockmap[self.sock.fileno()] = self.sock
def setup_sockux_h2(self):
if os.name == "nt":
return
if self.sockuxh2:
self.log.info("raw listener %s config unchanged", Env.paths.lsnruxsock)
return
if not os.path.exists(Env.paths.lsnruxsockd):
os.makedirs(Env.paths.lsnruxsockd)
try:
if os.path.isdir(Env.paths.lsnruxh2sock):
shutil.rmtree(Env.paths.lsnruxh2sock)
else:
os.unlink(Env.paths.lsnruxh2sock)
except Exception:
pass
try:
self.sockuxh2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sockuxh2.bind(Env.paths.lsnruxh2sock)
self.sockuxh2.listen(1)
self.sockuxh2.settimeout(self.sock_tmo)
except socket.error as exc:
self.alert("error", "bind http/2 listener %s error: %s", Env.paths.lsnruxh2sock, exc)
return
self.log.info("listening on %s using http/2", Env.paths.lsnruxh2sock)
self.sockmap[self.sockuxh2.fileno()] = self.sockuxh2
def setup_sockux(self):
if os.name == "nt":
return
if self.sockux:
self.log.info("raw listener %s config unchanged", Env.paths.lsnruxsock)
return
if not os.path.exists(Env.paths.lsnruxsockd):
os.makedirs(Env.paths.lsnruxsockd)
try:
if os.path.isdir(Env.paths.lsnruxsock):
shutil.rmtree(Env.paths.lsnruxsock)
else:
os.unlink(Env.paths.lsnruxsock)
except Exception:
pass
try:
self.sockux = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sockux.bind(Env.paths.lsnruxsock)
self.sockux.listen(1)
self.sockux.settimeout(self.sock_tmo)
except socket.error as exc:
self.alert("error", "bind raw listener %s error: %s", Env.paths.lsnruxsock, exc)
return
self.log.info("listening on %s", Env.paths.lsnruxsock)
self.sockmap[self.sockux.fileno()] = self.sockux
def setup_socks(self):
self.setup_socktls()
self.setup_sock()
self.setup_sockux()
self.setup_sockux_h2()
class ClientHandler(shared.OsvcThread):
sock_tmo = 5.0
name = "listener client"
def __init__(self, parent, conn, addr, encrypted, scheme, tls, tls_context):
shared.OsvcThread.__init__(self)
self.parent = parent
self.event_queue = None
self.conn = conn
self.addr = addr
self.encrypted = encrypted
self.scheme = scheme
self.tls = tls
self.tls_context = tls_context
self.log = logging.LoggerAdapter(logging.getLogger(Env.nodename+".osvcd.listener"), {"node": Env.nodename, "component": "%s/%s" % (self.parent.name, addr[0])})
self.streams = {}
self.h2conn = None
self.events_stream_ids = []
self.usr_cf_sum = None
self.same_auth = lambda h: False
if scheme == "raw":
self.usr = False
self.usr_auth = "secret"
self.usr_grants = {"root": None}
else:
self.usr = None
self.usr_auth = None
self.usr_grants = {}
self.events_counter = 0
def __str__(self):
try:
progress = self.parent.stats.sessions.alive[self.sid].progress
except Exception:
progress = "unknown"
return "client handler thread (client addr: %s, usr: %s, auth: %s, scheme: %s, progress: %s)" % (
self.addr[0],
self.usr.name if self.usr else self.usr,
self.usr_auth,
self.scheme,
progress,
)
def run(self):
try:
close = True
self.sid = str(uuid.uuid4())
self.parent.stats.sessions.alive[self.sid] = Storage({
"created": time.time(),
"addr": self.addr[0],
"encrypted": self.encrypted,
"progress": "init",
})
if self.scheme == "h2":
self.handle_h2_client()
else:
self.handle_raw_client()
except Close:
pass
except DontClose:
close = False
except (OSError, socket.error) as exc:
if exc.errno in (0, ECONNRESET):
pass
except RuntimeError as exc:
self.log.error("%s", exc)
except Exception as exc:
try:
ignore = exc.errno == 0
except AttributeError:
ignore = False
if not ignore:
self.log.error("unexpected: %s", exc)
traceback.print_exc()
finally:
if close:
del self.parent.stats.sessions.alive[self.sid]
if self.h2conn:
self.h2conn.close_connection()
self.conn.close()
def negotiate_tls(self):
"""
Given an established TCP connection and a HTTP/2-appropriate TLS context,
this function:
1. wraps TLS around the TCP connection.
2. confirms that HTTP/2 was negotiated and, if it was not, throws an error.
"""
if not self.tls:
self.tls_conn = self.conn
return
try:
self.tls_conn = self.tls_context.wrap_socket(self.conn, server_side=True)
except OSError as exc:
if exc.errno in (0, ECONNRESET):
# 0: client => server after daemon restart
# ECONNRESET: server => client after daemon restart
raise
raise RuntimeError("tls wrap error: %s"%exc)
# Always prefer the result from ALPN to that from NPN.
# You can only check what protocol was negotiated once the handshake is
# complete.
negotiated_protocol = self.tls_conn.selected_alpn_protocol()
if negotiated_protocol is None:
negotiated_protocol = self.tls_conn.selected_npn_protocol()
if negotiated_protocol != "h2":
raise RuntimeError("couldn't negotiate h2: %s" % negotiated_protocol)
def current_usr_cf_sum(self):
return self.node_data.get(["services", "config", self.usr.path, "csum"], default="unknown")
def authenticate_client(self, headers):
if self.usr is False:
return
if self.usr and self.usr_cf_sum == self.current_usr_cf_sum():
# unchanged server side
if self.same_auth(headers):
# unchanged request auth
return
if self.addr[0] == "local":
# only root can talk to the ux sockets
self.usr = False
self.usr_auth = "uxsock"
self.last_auth = None
self.same_auth = lambda h: True
return
secret = headers.get(Headers.secret)
if secret:
self.usr = self.authenticate_client_secret(secret)
self.usr_auth = "secret"
self.last_auth = secret
self.same_auth = lambda h: h.get(Headers.secret) == self.last_auth
return
authorization = headers.get("authorization")
if authorization:
if authorization.startswith("Bearer "):
self.usr = self.authenticate_client_jwt(authorization)
self.usr_auth = "jwt"
self.usr_grants = self.user_grants()
self.last_auth = authorization
self.same_auth = lambda h: h.get("authorization") == self.last_auth
return
elif authorization.startswith("Basic "):
self.usr = self.authenticate_client_basic(authorization)
self.usr_auth = "basic"
self.usr_grants = self.user_grants()
self.usr_cf_sum = self.current_usr_cf_sum()
self.last_auth = authorization
self.same_auth = lambda h: h.get("authorization") == self.last_auth
return
try:
self.usr = self.authenticate_client_x509()
self.usr_auth = "x509"
self.usr_grants = self.user_grants()
self.usr_cf_sum = self.current_usr_cf_sum()
#self.log.info("loaded grants for %s, conf %s", self.usr.path, self.usr_cf_sum)
self.last_auth = None
self.same_auth = lambda h: h.get(Headers.secret) is None and h.get("authorization") is None
return
except Exception as exc:
#self.log.warning("%s", exc)
pass
self.usr = None
self.usr_grants = {}
self.last_auth = None
self.usr_cf_sum = None
self.same_auth = lambda h: False
raise ex.Error("refused %s auth" % str(self.addr))