-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathace.py
executable file
·2734 lines (2383 loc) · 84.1 KB
/
ace.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
#!/usr/bin/env python3
#region copyright
# This file is Copyright (C) 2022 ITAS Solutions LP, All Rights Reserved
# Contact ITAS Solutions LP at [email protected] for licensing inquiries
#endregion copyright
#region imports
# stdlib imports:
from __future__ import annotations
from dataclasses import asdict, fields
import datetime # don't replace this with "from datetime import ..." b/c eval(flask.cfg)
import html
import json
import logging
import mimetypes
from multiprocessing import RLock as MPLockFactory
from multiprocessing.synchronize import RLock as MPLock
import os
from pathlib import Path, PurePosixPath
import random
import re
import shutil
import socket
import sys
import tempfile
from threading import RLock, Thread
from time import sleep
from typing import(
Any, Callable, cast, Dict, Iterator, Optional as Opt,
Type, TypeVar, TYPE_CHECKING, Union,
)
from urllib.parse import urlencode, urlparse
import uuid
# 3rd-party imports:
import accept_types # pip install accept-types
from flask import( # pip install flask
Flask, jsonify, request, Response,
send_from_directory, session, url_for,
)
from flask_login import( # type: ignore # pip install flask-login
LoginManager, UserMixin, AnonymousUserMixin,
login_required, current_user, confirm_login, login_user, logout_user,
)
from flask_session import Session # type: ignore # pip install flask-session
from tornado.wsgi import WSGIContainer # pip install tornado
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from werkzeug.serving import make_ssl_devcert
if TYPE_CHECKING:
def redirect( url: str ) -> Response: ...
else:
from flask import redirect # flask.wrappers.Response vs werkzeug.wrappers.Response
# OS specific:
if sys.platform != 'win32':
import grp
import pam # pip install python-pam
import pwd
if __name__ == '__main__':
incpy_path = Path( __file__ ).absolute().parent / 'incpy'
sys.path.append( str( incpy_path ))
# local imports:
import ace_engine
from ace_fields import Field, ValidationError
import ace_logging
import ace_settings
import auditing
from chown import chown
from coalesce import coalesce
from dhms import dhms
import repo
from tts import TTS_VOICES, tts_voices
#endregion imports
#region globals
DEBUG9 = 9
DID_MAX_LENGTH = 30
ANI_MAX_LENGTH = 20
CPN_MAX_LENGTH = 30
ACCT_NUM_MAX_LENGTH = 4
ACCT_NAME_MAX_LENGTH = 30
SESSION_USERDATA = 'userdata'
etc_path = Path( '/etc/itas/ace/' )
default_data_path = Path( '/usr/share/itas/ace/' )
logger = logging.getLogger( __name__ )
if sys.platform != 'win32':
auth = pam.pam()
else:
logger.critical(
'NON-POSIX IMPLEMENTATION ONLY SUPPORTS A SINGLE HARD-CODED USER FOR NOW'
)
g_settings_mplock = MPLockFactory()
g_car_mplock = MPLockFactory()
#endregion globals
#region utilities
def new_audit() -> auditing.Audit:
assert request.remote_addr is not None
return auditing.Audit(
user = current_user.name,
remote_addr = request.remote_addr,
)
def logging_formatTime( self: Any, record: Any, datefmt: Opt[str] = None ) -> str:
dt = datetime.datetime.fromtimestamp( record.created )
datefmt = datefmt or '%b%d %H:%M:%S.%F'
if '%F' in datefmt:
datefmt = datefmt.replace( '%F', dt.strftime('%f')[:-3] )
return dt.strftime( datefmt )
setattr( logging.Formatter, 'formatTime', logging_formatTime )
AnyNumeric = TypeVar( 'AnyNumeric', int, float )
def clamp( val: AnyNumeric, minval: AnyNumeric, maxval: AnyNumeric ) -> AnyNumeric:
return sorted( [ val, minval, maxval ] )[1]
def to_optional_int( s: Opt[str] ) -> Opt[int]:
if s is None:
return None
return int( s )
def is_safe_url( url: str ) -> bool:
log = logger.getChild( 'is_safe_url' )
unsafe = bool( urlparse( url ).netloc )
log.debug( 'url=%r -> unsafe=%r', url, unsafe )
return not unsafe
def is_root() -> bool:
assert sys.platform != 'win32' # this function doesn't make sense outside of posix for now
uid: int = os.getuid() # type: ignore
return uid == 0
if sys.platform != 'win32':
def drop_root( uid_name: str = 'nobody', gid_name: str = 'nogroup' ) -> None:
if not is_root():
return # we're already not root, nothing to do
# Get the uid/gid from the name
running_uid = pwd.getpwnam( uid_name ).pw_uid
running_gid = grp.getgrnam( gid_name ).gr_gid
# Remove group privileges
os.setgroups( [] )
# Try setting the new uid/gid
os.setgid( running_gid )
os.setuid( running_uid )
# Ensure a very conservative umask
_ = os.umask( 0o077 ) # returns old_umask
else:
def drop_root( uid_name: str = 'nobody', gid_name: str = 'nogroup' ) -> None:
pass
def os_execute( cmd: str ) -> None:
log = logger.getChild( 'os_execute' )
log.debug( cmd )
os.system( cmd )
def walk_json_dicts( json_data: Any, callback: Callable[[Any],Opt[Any]] ) -> Opt[Any]:
if isinstance( json_data, dict ):
r = callback( json_data )
if r is not None:
return r
for k, v in json_data.items():
r = walk_json_dicts( v, callback )
if r is not None:
return r
elif isinstance( json_data, list ):
for v in json_data:
r = walk_json_dicts( v, callback )
if r is not None:
return r
return None
#endregion utilities
#region html helpers
def qry_int( name: str, default: int, *,
min: Opt[int] = None,
max: Opt[int] = None,
) -> int:
try:
q = int( request.args.get( name, '' ))
except ValueError:
q = default
if min is not None and q < min:
return min
if max is not None and q > max:
return max
return q
def html_text( text: str ) -> str:
return html.escape( text, quote = False )
def html_att( text: str ) -> str:
return html.escape( text, quote = True )
def html_page( *lines: str, stylesheets: Opt[list[str]] = None, status_code: Opt[int] = None ) -> Response:
settings = ace_settings.load()
header = [
'<!doctype html>',
'<html>',
'<head>',
'<link rel="stylesheet" href="/ace.css">',
]
for stylesheet in stylesheets or ():
header.append( f'<link rel="stylesheet" href="{stylesheet}">' )
header.append( '</head><body>' )
if current_user.is_authenticated:
header.extend( [
'<ul class="nav">',
f' <li><a href="{url_for("http_index")}">ACE</a></li>',
f' <li><a href="{url_for("http_dids")}">DIDs</a></li>',
f' <li><a href="{url_for("http_anis")}">ANIs</a></li>',
f' <li><a href="{url_for("http_flags")}">Flags</a></li>',
f' <li><a href="{url_for("http_routes")}">Routes</a></li>',
f' <li><a href="{url_for("http_voicemails")}">Voicemail</a></li>',
f' <li><a href="{url_for("http_settings")}">Settings</a></li>',
f' <li><a href="{url_for("http_cars")}">CAR</a></li>',
f' <li><a href="{url_for("http_audits")}">Audit</a></li>',
f' <li><a href="{url_for("http_logout")}">Log Out</a></li>',
'</ul>',
] )
header.append( '<div id="content">' )
footer = [ f'<br/><br/>{settings.motd}</div></body></html>' ]
return Response(
'\n'.join( header + list( lines ) + footer ),
status_code or 200,
)
def accept_type(
accepted_types: list[str] = [ 'text/html', 'application/json' ],
) -> str:
#log = logger.getChild( 'accept_type' )
accept_header: str = request.headers.get( 'Accept' ) or 'text/html'
return_type: str = accept_types.get_best_match( accept_header, accepted_types ) or 'text/html'
assert isinstance( return_type, str ), f'invalid return_type={return_type!r}'
#log.debug( 'accept_header=%r, accepted_types=%r, return_type=%r', accept_header, accepted_types, return_type )
return return_type
class HttpFailure( Exception ):
def __init__( self, error: str, status_code: int = 400 ) -> None:
self.error = error
self.status_code = status_code
def __repr__( self ) -> str:
cls = type( self )
return f'{cls.__module__}.{cls.__name__}(error={self.error!r}, status_code={self.status_code!r})'
def rest_success( rows: Opt[list[dict[str,Any]]] = None ) -> Response:
return cast( Response, jsonify( success = True, rows = rows or [] ))
def rest_failure( error: str, status_code: Opt[int] = None ) -> Response:
r = cast( Response, jsonify( success = False, error = error ))
r.status_code = status_code or 400
return r
def _http_failure( return_type: str, error: str, status_code: int = 400 ) -> Response:
if return_type == 'application/json':
return rest_failure( error, status_code )
else:
return html_page( html_text( error ), status_code = status_code )
def inputs() -> dict[str,Any]:
if request.content_type == 'application/json':
return cast( Dict[str,Any], request.json )
else:
return request.form
#endregion html helpers
#region authentication
# NOTE: you can override this function in flask.cfg if you want to implement alternative auth method
if sys.platform != 'win32':
def authenticate( usernm: str, secret: str ) -> bool:
return bool( auth.authenticate( usernm, secret ))
else:
def authenticate( usernm: str, secret: str ) -> bool:
log = logger.getChild( 'authenticate' )
log.critical(
'NON-POSIX IMPLEMENTATION ONLY SUPPORTS A SINGLE HARD-CODED USER FOR NOW'
)
return usernm == 'setup' and secret == 'deleteme'
#endregion authentication
#region custom DID fields
class IntField( Field ):
def __init__( self, field: str, label: str, *,
tooltip: str = '',
required: bool = False,
min_length: Opt[int] = None,
max_length: Opt[int] = None,
min_value: Opt[int] = None,
max_value: Opt[int] = None,
placeholder: Opt[str] = None,
) -> None:
super().__init__( field, label,
tooltip = tooltip,
required = required,
min_length = min_length,
max_length = max_length,
placeholder = placeholder,
)
self.min_value = min_value
self.max_value = max_value
def validate( self, rawvalue: Opt[str] ) -> Union[None,int,str]:
rawvalue_ = super().validate( rawvalue )
if rawvalue_ is None:
return None
try:
value = int( rawvalue_ )
except ValueError as e1:
raise ValidationError( f'invalid {self.label}: {e1.args[0]!r}' ) from None
if self.min_value is not None and value < self.min_value:
raise ValidationError( f'{self.label} is too small, min value is {self.min_value!r}' )
if self.max_value is not None and value > self.max_value:
raise ValidationError( f'{self.label} is too large, max value is {self.max_value!r}' )
return value
class StrField( Field ):
pass
#endregion custom DID fields
#region flask config
etc_path.mkdir( mode = 0o770, parents = True, exist_ok = True )
cfg_path = etc_path / 'flask.cfg'
if not cfg_path.is_file():
cfg_raw = '\n'.join( [
f'ENV = {"production"!r}',
f'DEBUG = {False!r}',
f'TESTING = {False!r}',
f'SECRET_KEY = {os.urandom(24)!r}',
f'SESSION_TYPE = {"filesystem"!r}',
f'SESSION_FILE_DIR = {"/var/cache/itas/ace/sessions"!r}',
f'PERMANENT_SESSION_LIFETIME = {datetime.timedelta(minutes=5)!r}',
f'ITAS_LISTEN_PORT = {443!r}',
f'ITAS_CERTIFICATE_PEM = {str(etc_path/"certificate.pem")!r}',
f'ITAS_AUTOBAN_BAD_EXPIRE_MINUTES = {0.5!r}',
f'ITAS_AUTOBAN_BAD_COUNT_LOCKOUT = {10!r}',
f'ITAS_AUTOBAN_DURATION_MINUTES = {10!r}',
f'ITAS_AUDIT_DIR = {"/var/log/itas/ace/audit/"!r}',
f'ITAS_AUDIT_FILE = {"%Y-%m-%d.log"!r}',
f'ITAS_AUDIT_TIME = {"%Y-%m-%d %H:%M:%S.%f %Z%z"!r}',
f'ITAS_OWNER_USER = {"www-data"!r}',
f'ITAS_OWNER_GROUP = {"www-data"!r}',
f'ITAS_FREESWITCH_JSON_CDR_PATH = {"/var/log/freeswitch/json_cdr"!r}',
f'ITAS_REPOSITORY_TYPE = {"fs"!r}',
f'ITAS_REPOSITORY_NOFS_TYPE = {"sqlite"!r}',
f'ITAS_REPOSITORY_FS_PATH = {"/usr/share/itas/ace/"!r}',
f'ITAS_REPOSITORY_SQLITE_PATH = {"/usr/share/itas/ace/ace.sqlite"!r}',
f'ITAS_REPOSITORY_PGSQL_HOST = {"127.0.0.1"!r}',
f'ITAS_REPOSITORY_PGSQL_DATABASE = {"ace"!r}',
f'ITAS_REPOSITORY_PGSQL_USERNAME = {"ace"!r}',
f'ITAS_REPOSITORY_PGSQL_PASSWORD = {""!r}',
f'ITAS_REPOSITORY_PGSQL_PORT = {5432!r}',
f"ITAS_REPOSITORY_PGSQL_SSLMODE: Opt[Literal['disable','allow','prefer','require','verify-ca','verify-full']] = None",
f'ITAS_REPOSITORY_PGSQL_SSLROOTCERT = None',
f'ITAS_FLAGS_PATH = {str(default_data_path)!r}',
f'ITAS_DID_FIELDS = {[]!r}',
f'ITAS_DID_VARIABLES_EXAMPLES = {[]!r}',
'ITAS_ANI_OVERRIDES_EXAMPLES = {!r}'.format([
'# <<< anything after a # is a "comment" and is ignored',
'8005551212 6999 # always send calls with this ANI and DID 8005551212 to route 6999',
'8005551213 6999 1999-12-31 # send calls with this ANI and DID 8005551213 to route 6999 until Dec 31, 1999 12:00:00 AM',
'8005551214 6999 1999-12-31 08:00:00 # send calls with this ANI and DID 8005551214 to route 6999 until Dec 31, 1999 8:00 AM (local time)',
]),
f'ITAS_VOICEMAIL_BOXES_PATH = {"/usr/share/itas/ace/boxes/"!r}',
f'ITAS_VOICEMAIL_MSGS_PATH = {"/usr/share/itas/ace/msgs/"!r}',
f'ITAS_SETTINGS_PATH = {"/etc/itas/ace/settings.json"!r}',
f'ITAS_UI_LOGFILE = {"/var/log/itas/ace/logs/ui.log"!r}',
f'ITAS_ENGINE_LOGFILE = {"/var/log/itas/ace/logs/engine.log"!r}',
'ITAS_LOGLEVELS = {!r}'.format( {} ),
] )
with cfg_path.open( 'w' ) as f:
print( cfg_raw, file = f )
else:
with cfg_path.open( 'r' ) as f:
cfg_raw = f.read()
# begin flask.cfg variables:
app = Flask( __name__ )
ENV: str = ''
DEBUG: bool = False
TESTING: bool = False
SECRET_KEY: bytes = b''
SESSION_TYPE: str = ''
SESSION_FILE_DIR: str = ''
PERMANENT_SESSION_LIFETIME: datetime.timedelta = datetime.timedelta( minutes = 5 )
ITAS_LISTEN_PORT: int = 443
ITAS_CERTIFICATE_PEM: str = ''
ITAS_AUTOBAN_BAD_EXPIRE_MINUTES: float = 0.5
ITAS_AUTOBAN_BAD_COUNT_LOCKOUT: int = 10
ITAS_AUTOBAN_DURATION_MINUTES: float = 10
ITAS_AUDIT_DIR: str = ''
ITAS_AUDIT_FILE: str = ''
ITAS_AUDIT_TIME: str = ''
ITAS_OWNER_USER: str = ''
ITAS_OWNER_GROUP: str = ''
ITAS_FREESWITCH_JSON_CDR_PATH: str = ''
ITAS_REPOSITORY_TYPE: str = ''
ITAS_REPOSITORY_NOFS_TYPE: str = ''
ITAS_REPOSITORY_FS_PATH: str = ''
ITAS_REPOSITORY_SQLITE_PATH: str = ''
ITAS_REPOSITORY_PGSQL_HOST: str = ''
ITAS_REPOSITORY_PGSQL_DATABASE: str = ''
ITAS_REPOSITORY_PGSQL_USERNAME: str = ''
ITAS_REPOSITORY_PGSQL_PASSWORD: str = ''
ITAS_REPOSITORY_PGSQL_PORT: int = 5432
ITAS_REPOSITORY_PGSQL_SSLMODE: Opt[repo.PGSQL_SSLMODE] = None
ITAS_REPOSITORY_PGSQL_SSLROOTCERT: Opt[str] = None
ITAS_FLAGS_PATH: str = ''
ITAS_DID_FIELDS: list[Field] = []
ITAS_DID_VARIABLES_EXAMPLES: list[str] = []
ITAS_ANI_OVERRIDES_EXAMPLES: list[str] = []
ITAS_VOICEMAIL_BOXES_PATH: str
ITAS_VOICEMAIL_MSGS_PATH: str
ITAS_SETTINGS_PATH: str
ITAS_UI_LOGFILE: str = ''
ITAS_ENGINE_LOGFILE: str = ''
ITAS_LOGLEVELS: dict[str,str] = {}
exec( cfg_raw + '\n' ) # this exec overrides the variables from flask.cfg
assert ITAS_AUDIT_DIR, f'flask.cfg missing ITAS_AUDIT_DIR'
assert ITAS_UI_LOGFILE, f'flask.cfg missing ITAS_UI_LOGFILE'
assert ITAS_ENGINE_LOGFILE, f'flask.cfg missing ITAS_ENGINE_LOGFILE'
# end of flask.cfg variables
app.config.from_object( __name__ )
app.config['APP_NAME'] = 'Automated Call Experience (ACE)'
#endregion flask config
#region autoban
class AutoBan:
def __init__( self ) -> None:
self._lock = RLock()
self._fails: dict[str,list[datetime.datetime]] = {}
self._bans: dict[str,datetime.datetime] = {}
def try_auth( self, usernm: str, secret: str ) -> bool:
log = logger.getChild( 'AutoBan.try_auth' )
auth = authenticate( usernm, secret )
with self._lock:
ip = request.remote_addr
now = datetime.datetime.now()
if ip is None:
log.debug( 'user %r has ip=%r', usernm, ip )
return False
# check if user is already locked out:
try:
until = self._bans[ip]
except KeyError:
pass
else:
if until <= now:
del self._bans[ip]
else:
log.debug( 'user %r is locked out until %r', usernm, str( until ))
return False
# check for auth success:
if auth:
self._fails.pop( ip, None ) # successful login - reset failure count
return True
# update fail count and check if user needs to be locked out:
ar = self._fails.get( ip, [] )
while ar and ar[0] <= now:
ar = ar[1:] # remove expired bad pw attempts
ar.append( now + datetime.timedelta( minutes = ITAS_AUTOBAN_BAD_EXPIRE_MINUTES ))
if len( ar ) >= ITAS_AUTOBAN_BAD_COUNT_LOCKOUT:
until = now + datetime.timedelta( minutes = ITAS_AUTOBAN_DURATION_MINUTES )
self._bans[ip] = until
self._fails.pop( ip, None )
log.debug( 'user %r banned until %r', usernm, str( until ))
else:
self._fails[ip] = ar
log.debug( 'user %r fail count=%r', usernm, len( ar ))
return False
autoban = AutoBan()
#endregion autoban
#region paths and auditing
auditing.init(
path = Path( ITAS_AUDIT_DIR ),
file = ITAS_AUDIT_FILE,
time_format = ITAS_AUDIT_TIME,
)
if __name__ == '__main__' and SESSION_TYPE == 'filesystem':
session_path = Path( SESSION_FILE_DIR )
session_path.mkdir( mode = 0o770, parents = True, exist_ok = True )
if sys.platform != 'win32':
chown( str( session_path ), ITAS_OWNER_USER, ITAS_OWNER_GROUP )
os.chmod( SESSION_FILE_DIR, 0o770 )
r_valid_audit_filename = re.compile( r'^[a-zA-Z0-9_\.-]+$', re.I )
def valid_audit_filename( filename: str ) -> bool:
return bool( r_valid_audit_filename.match( filename ))
AnyPath = TypeVar( 'AnyPath', Path, PurePosixPath )
def mkdir_with_permissions( path: AnyPath ) -> AnyPath:
path2 = str( path )
Path( path ).mkdir( mode = 0o775, parents = True, exist_ok = True )
chown( path2, ITAS_OWNER_USER, ITAS_OWNER_GROUP )
os.chmod( path2, 0o775 )
return path
flags_path = mkdir_with_permissions( Path( ITAS_FLAGS_PATH ))
def flag_file_path( flag: str ) -> Path:
return flags_path / f'{flag}.flag'
voicemail_meta_path = mkdir_with_permissions( PurePosixPath( ITAS_VOICEMAIL_BOXES_PATH ))
def voicemail_greeting_path( box: int, greeting: int ) -> PurePosixPath:
return voicemail_meta_path / f'{box}' / f'greeting{greeting}.wav'
voicemail_msgs_path = mkdir_with_permissions( PurePosixPath( ITAS_VOICEMAIL_MSGS_PATH ))
def voicemail_box_msgs_path( box: int ) -> PurePosixPath:
return voicemail_msgs_path / str( box )
#endregion paths and auditing
#region repo config
repo_config = repo.Config(
fs_path = Path( ITAS_REPOSITORY_FS_PATH ),
sqlite_path = Path( ITAS_REPOSITORY_SQLITE_PATH ),
pgsql_host = ITAS_REPOSITORY_PGSQL_HOST,
pgsql_db = ITAS_REPOSITORY_PGSQL_DATABASE,
pgsql_uid = ITAS_REPOSITORY_PGSQL_USERNAME,
pgsql_pwd = ITAS_REPOSITORY_PGSQL_PASSWORD,
pgsql_port = ITAS_REPOSITORY_PGSQL_PORT,
pgsql_sslmode = ITAS_REPOSITORY_PGSQL_SSLMODE,
pgsql_sslrootcert = Path( ITAS_REPOSITORY_PGSQL_SSLROOTCERT ) if ITAS_REPOSITORY_PGSQL_SSLROOTCERT else None,
)
REPO_FACTORY: Type[repo.Repository]
# Setup repositories based on config
try:
REPO_FACTORY = repo.from_type( ITAS_REPOSITORY_TYPE )
except KeyError:
raise Exception( f'invalid ITAS_REPOSITORY_TYPE={ITAS_REPOSITORY_TYPE!r}' ) from None
REPO_FACTORY_NOFS: Type[repo.Repository] = REPO_FACTORY
if REPO_FACTORY == repo.RepoFs:
try:
REPO_FACTORY_NOFS = repo.from_type( ITAS_REPOSITORY_NOFS_TYPE )
except KeyError:
raise Exception( f'invalid ITAS_REPOSITORY_NOFS_TYPE={ITAS_REPOSITORY_NOFS_TYPE!r}' ) from None
REPO_DIDS = REPO_FACTORY( repo_config, 'dids', '.did', [
repo.SqlInteger( 'did', null = False, size = 10, auto = False, primary = True ),
repo.SqlText( 'tollfree', null = True ),
repo.SqlText( 'category', null = True ),
repo.SqlInteger( 'acct', size = 4, null = True ),
repo.SqlText( 'name', null = True ),
repo.SqlText( 'acct_flag', null = True ),
repo.SqlVarChar( 'route', size = 20, null = False ),
repo.SqlText( 'did_flag', null = True ),
repo.SqlText( 'variables', null = True ),
repo.SqlText( 'notes', null = True ),
*[
repo.SqlText( field.field, null = True )
for field in ITAS_DID_FIELDS
]
], ITAS_OWNER_USER, ITAS_OWNER_GROUP, keyname = 'did' )
REPO_ANIS = REPO_FACTORY( repo_config, 'anis', '.ani', [
repo.SqlInteger( 'ani', null = False, size = 10, auto = False, primary = True ),
repo.SqlVarChar( 'route', size = 20, null = True ),
repo.SqlText( 'overrides', null = True ),
repo.SqlText( 'notes', null = True ),
], ITAS_OWNER_USER, ITAS_OWNER_GROUP, keyname = 'ani' )
REPO_ROUTES = REPO_FACTORY( repo_config, 'routes', '.route', [
repo.SqlInteger( 'route', null = False, size = 10, auto = False, primary = True ),
repo.SqlText( 'name', null = True ),
repo.SqlText( 'type', null = True ),
repo.SqlJson( 'nodes', null = False ),
], ITAS_OWNER_USER, ITAS_OWNER_GROUP, keyname = 'route' )
REPO_BOXES = REPO_FACTORY( repo_config, 'boxes', '.box', [
repo.SqlInteger( 'box', null = False, size = 10, auto = False, primary = True ),
repo.SqlText( 'name', null = True, unique = False ),
repo.SqlText( 'type', null = True ),
repo.SqlVarChar( 'pin', size = 20, null = False ),
repo.SqlInteger( 'max_greeting_seconds', size = 4, null = False ),
repo.SqlInteger( 'max_message_seconds', size = 4, null = False ),
repo.SqlBool( 'allow_guest_urgent', null = False ),
repo.SqlVarChar( 'format', size = 20, null = False ),
repo.SqlJson( 'branches', null = True ),
repo.SqlJson( 'greetingBranch', null = True ),
repo.SqlJson( 'delivery', null = True ),
], ITAS_OWNER_USER, ITAS_OWNER_GROUP, keyname = 'box' )
REPO_JSON_CDR = REPO_FACTORY_NOFS( repo_config, 'cdr', '.cdr', [
repo.SqlInteger( 'id', null = False, size = 16, auto = True, primary = True ),
repo.SqlVarChar( 'call_uuid', size = 36, null = False ),
repo.SqlDateTime( 'start_stamp', null = False ),
repo.SqlDateTime( 'answered_stamp', null = True ),
repo.SqlDateTime( 'end_stamp', null = False ),
repo.SqlJson( 'json', null = False ),
], ITAS_OWNER_USER, ITAS_OWNER_GROUP, auditing = False )
# CAR = Caller Activity Report
REPO_CAR = REPO_FACTORY_NOFS( repo_config, 'car', '.car', [
# NOTE: keep this in sync with ace_car.CAR
repo.SqlVarChar( 'id', size = 36, null = False, primary = True ), # call's uuid
repo.SqlVarChar( 'did', size = DID_MAX_LENGTH, null = False ),
repo.SqlVarChar( 'ani', size = ANI_MAX_LENGTH, null = False ),
repo.SqlVarChar( 'cpn', size = CPN_MAX_LENGTH, null = False ),
repo.SqlVarChar( 'acct_num', size = ACCT_NUM_MAX_LENGTH, null = True ),
repo.SqlVarChar( 'acct_name', size = ACCT_NAME_MAX_LENGTH, null = True ),
repo.SqlFloat( 'start', null = False ),
repo.SqlFloat( 'end', null = True ),
repo.SqlJson( 'activity', null = False ),
], ITAS_OWNER_USER, ITAS_OWNER_GROUP, auditing = False )
#endregion repo config
#region session management
Session( app )
class User( UserMixin ): # type: ignore
def __init__( self, name: str ) -> None:
self.name = name
self.id = str( uuid.uuid4() )
self.active = True
def __repr__( self ) -> str:
cls = type( self )
return f'{cls.__module__}.{cls.__qualname__}(name={self.name!r}, id={self.id!r})' # TODO FIXME: id is not a parameter to __init__
def __str__( self ) -> str:
return repr( self )
class Anonymous( AnonymousUserMixin ): # type: ignore
name = 'Anonymous'
login_manager = LoginManager()
login_manager.login_view = 'http_login'
login_manager.login_message = 'Please log in to access this page.'
login_manager.refresh_view = 'http_reauth'
@login_manager.user_loader # type: ignore
def load_user( user_id: str ) -> UserMixin:
#log = logger.getChild( 'load_user' )
user = session.get( SESSION_USERDATA, None )
#log.debug( 'user_id %r -> %r', user_id, user )
return user
login_manager.init_app( app )
def try_login( usernm: str, secret: str, remember: bool = False ) -> bool:
log = logger.getChild( 'try_login' )
log.debug( 'trying usernm=%r', usernm )
if usernm and secret and autoban.try_auth( usernm, secret ):
log.debug( 'usernm %r auth success', usernm )
user = User( usernm )
session[SESSION_USERDATA] = user
if login_user( user, remember = remember ):
log.debug( 'usernm %r logged in', usernm )
session.permanent = True
return True
return False
def try_logout() -> None:
try:
del session[SESSION_USERDATA]
except KeyError:
pass
logout_user()
#endregion session management
#region http - login
@app.route( '/login', methods = [ 'GET', 'POST' ] )
def http_login() -> Response:
log = logger.getChild( 'http_login' )
return_type = accept_type()
usernm: str = ''
errmsg = ''
if request.method == 'POST':
inp = inputs()
usernm = inp.get( 'usernm', '' )
secret = inp.get( 'secret', '' )
remember_ = inp.get( 'remember', 'no' )
if remember_ not in ( 'yes', 'no' ):
return _http_failure(
return_type,
'"remember" must be "yes" or "no"',
400,
)
remember =( remember_ == 'yes' )
if try_login( usernm, secret, remember ):
if return_type == 'application/json':
return rest_success( [] )
next_url = request.args.get( 'next' )
if next_url and is_safe_url( next_url ):
return redirect( next_url )
return redirect( url_for( 'http_index' ))
else:
log.warning( 'username %r auth failure', usernm )
errmsg = 'Invalid credentials'
if return_type == 'application/json':
logout_user()
return rest_failure( errmsg )
logout_user()
return html_page(
'<center>',
f'<p>{app.config["APP_NAME"]} Portal Login</p>',
'<p>',
' <form method="POST">',
' User Name:<br/>',
f' <input type="text" name="usernm" value="{html_att(usernm)}" autofocus/><br/>',
' <br/>',
' Secret:<br/>',
' <input type="password" name="secret"/><br/>',
' <br/>',
' <input type="submit" value="Login"/>',
' </form>',
'</p>',
f'<font color=red>{errmsg}</font>',
'</center>',
)
@app.route( '/reauth', methods = [ 'GET', 'POST' ] )
@login_required # type: ignore
def http_reauth() -> Response:
log = logger.getChild( 'http_reauth' )
if request.method == 'POST':
confirm_login()
return redirect( url_for( 'http_index' ))
log.warning( 'ToDO FiXME: need to generate reauth html content' )
return html_page(
'ToDO FiXME: reauth html content goes here',
)
@app.route( '/logout' )
def http_logout() -> Response:
log = logger.getChild( 'http_logout' )
log.debug( 'logging out current user' )
return_type = accept_type()
try_logout()
if return_type == 'application/json':
return rest_success( [] )
return redirect( url_for( 'http_index' ))
#endregion http - login
#region http - misc
@app.route( '/<path:filepath>' )
def http_send_from_directory( filepath: str ) -> Response:
mimetype = mimetypes.guess_type( filepath )[0]
if not mimetype:
mimetype = 'text/plain'
return send_from_directory(
'www',
filepath,
mimetype = mimetype,
max_age = 30 * 60,
)
@app.route( '/' )
@login_required # type: ignore
def http_index() -> Response:
#log = logger.getChild( 'http_index' )
#return_type = accept_type()
settings = ace_settings.load()
return html_page(
'TODO FIXME',
)
r_callie = re.compile( r'[/\\]callie[/\\]([^/\\]+)[/\\]8000[/\\](.*)$' )
def _iter_sounds( sounds: Path ) -> Iterator[str]:
for path2 in sounds.iterdir():
if path2.stem == 'music':
continue
for folder, _, files in os.walk( str( path2 )):
path3 = Path( folder )
if path3.stem not in ( '16000', '32000', '48000' ):
for file in files:
path = str( Path( folder ) / file )
# callie sounds can be specifically simplified for freeswitch:
m = r_callie.search( path )
if m:
yield f'{m.group(1)}/{m.group(2)}' # <<< FS can handle forward slashes on windows
else:
yield path
@app.route( '/sounds/' )
@login_required # type: ignore
def http_sounds() -> Response:
return_type = accept_type()
sounds: list[dict[str,str]] = []
settings = ace_settings.load()
for path in map( Path, settings.freeswitch_sounds ):
sounds.extend( [
{ 'sound': sound }
for sound in _iter_sounds( path )
] )
sounds.sort( key = lambda d: d['sound'] )
rsp = rest_success( sounds )
rsp.cache_control.public = True
rsp.cache_control.max_age = 30
return rsp
#endregion http - misc
#region http - DID
def valid_destination( dest: str ) -> bool:
if dest.startswith( 'V' ):
dest = dest[1:]
return dest.isnumeric()
@app.route( '/dids/', methods = [ 'GET' ] )
@login_required # type: ignore
def http_dids() -> Response:
log = logger.getChild( 'http_dids' )
return_type = accept_type()
q_limit = qry_int( 'limit', 20, min = 1, max = 1000 )
q_offset = qry_int( 'offset', 0, min = 0 )
filters: dict[str,str] = {}
for key in 'did tollfree acct name route notes'.split():
val = request.args.get( key, '' ).strip()
if val:
filters[key] = val
q_did = filters.get( 'did', '' )
q_tf = filters.get( 'tollfree', '' )
q_acct = filters.get( 'acct', '' )
q_name = filters.get( 'name', '' )
q_route = filters.get( 'route', '' )
q_notes = filters.get( 'notes', '' )
datadefs: dict[str,Any] = {
'acct': '',
'name': '',
}
with repo.Connector() as ctr:
dids: list[dict[str,Any]] = []
for did, did_data in REPO_DIDS.list( ctr,
filters = filters,
limit = q_limit,
offset = q_offset,
):
did_data['did'] = int( did )
dids.append({ **datadefs, **did_data })
if return_type == 'application/json':
return rest_success( dids )
row_html = (
'<tr>'
'<td><a href="/dids/{did}">{did}</a></td>'
'<td><a href="/dids/{did}">{acct}</a></td>'
'<td><a href="/dids/{did}">{name}</a></td>'
'</tr>'
)
body = '\n'.join([
row_html.format( **d ) for d in dids
])
did_tip = 'Performs substring search of all DIDs'
tf_tip = 'Performs substring search of all TF #s'
acct_tip = 'Performs substring search of all Account #s'
name_tip = 'Performs substring search of all Account Names'
route_tip = 'Performs substring search of all Routes'
notes_tip = 'Performs substring search of all Notes'
prevpage = urlencode({ 'did': q_did, 'tollfree': q_tf, 'acct': q_acct, 'name': q_name, 'route': q_route, 'notes': q_notes, 'limit': q_limit, 'offset': max( 0, q_offset - q_limit )})
nextpage = urlencode({ 'did': q_did, 'tollfree': q_tf, 'acct': q_acct, 'name': q_name, 'route': q_route, 'notes': q_notes, 'limit': q_limit, 'offset': q_offset + q_limit })
return html_page(
'<table width="100%"><tr>',
'<td align="center">',
'<a href="/dids/0">(Create new DID)</a>',
'</td>',
'<td align="center">'
'<form method="GET">'
f'<span tooltip="{html_att(did_tip)}"><input type="text" name="did" placeholder="DID" value="{html_att(q_did)}" maxlength="10" size="10" /></span>',
f'<span tooltip="{html_att(tf_tip)}"><input type="text" name="tollfree" placeholder="TF#" value="{html_att(q_tf)}" maxlength="10" size="10" /></span>',
f'<span tooltip="{html_att(acct_tip)}"><input type="text" name="acct" placeholder="Acct#" value="{html_att(q_acct)}" maxlength="4" size="4" /></span>',
f'<span tooltip="{html_att(name_tip)}"><input type="text" name="name" placeholder="Name" value="{html_att(q_name)}" size="10" /></span>',
f'<span tooltip="{html_att(route_tip)}"><input type="text" name="route" placeholder="Route" value="{html_att(q_route)}" size="4" /></span>',
f'<span tooltip="{html_att(notes_tip)}"><input type="text" name="notes" placeholder="Notes" value="{html_att(q_notes)}" size="10" /></span>',
'<input type="submit" value="Search"/>',
'<button id="clear" type="button" onclick="window.location=\'?\'">Clear</button>'
'</form>',
'</td>',
f'<td align="right"><a href="?{prevpage}"><<</a> <a href="?{nextpage}">>></a></td>',
'</tr></table>',
'<table class="fancy dids_list">',
' <tr><th>DID</th><th>Acct#</th><th>Acct Name</th></tr>',
body,
'</table>',
)
def try_post_did( ctr: repo.Connector, did: int, data: dict[str,str] ) -> int:
log = logger.getChild( 'try_post_did' )
try:
did2 = did or int( data.get( 'did' ) or '' )
except Exception as e1:
raise ValidationError( f'invalid DID: {e1!r}' ) from None
if len( str( did2 )) != 10:
raise ValidationError( 'invalid DID: must be 10 digits exactly' )
data2: dict[str,Union[int,str]] = { 'did': did2 }
try:
tollfree = data.get( 'tollfree', '' )
except Exception as e0:
raise ValidationError( f'invalid Toll Free #: {e0!r}' ) from None
if tollfree:
data2['tollfree'] = tollfree
try:
category = data.get( 'category', '' )
except Exception as e4:
raise ValidationError( f'invalid Category: {e4!r}' ) from None
if category:
data2['category'] = category
try:
did_flag = data.get( 'did_flag', '' )
except Exception as e6:
raise ValidationError( f'invalid DID Flag: {e6!r}' ) from None
if did_flag:
data2['did_flag'] = did_flag
try:
acct_ = data.get( 'acct', '' )
acct: Opt[int] = int( acct_ ) if acct_ else None
except Exception as e2:
raise ValidationError( f'invalid Account #: {e2!r}' ) from None
if acct is not None and not ( 1 <= acct <= 9999 ):
raise ValidationError( 'Account # must be between 1-9999' )
if acct is not None:
data2['acct'] = acct
try:
name = data.get( 'name', '' )
except Exception as e3:
raise ValidationError( f'invalid Client Name: {e3!r}' ) from None
if name:
data2['name'] = name
try:
acct_flag = data.get( 'acct_flag', '' )
except Exception as e6:
raise ValidationError( f'invalid Acct Flag: {e6!r}' ) from None