-
Notifications
You must be signed in to change notification settings - Fork 0
/
rc.py
2314 lines (1812 loc) · 80.1 KB
/
rc.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
import os
import sys
import time
import json
import socket
import base64
import struct
import logging
import platform
import subprocess
import threading
from enum import Enum
from types import SimpleNamespace
# ==============================================================================
# DEFINITIONS
# ==============================================================================
#
# definition of unit
#
_1KB_ = 1024
_1MB_ = _1KB_*1024
#
# definition for pyrc
#
_WAIT_TIMEOUT_ = 60
_HEADER_SIZE_ = 16
_CHUNK_SIZE_ = _1KB_*512
_BUFFER_SIZE_ = _1MB_*2
#
# Signature of headers
#
_SIGNATURE_ECHO___ = b'$SiGEcH$'
_SIGNATURE_UPLOAD_ = b'$SiGUpL$'
_SIGNATURE_DOWNLO_ = b'$SiGDoW$'
_SIGNATURE_EXECUT_ = b'$SiGExE$'
_SIGNATURE_LIST___ = b'$SiGLiS$'
_SIGNATURE_TEXT___ = b'$SiGTex$'
class CONFIG():
def _try(self, o):
try:
return o.__dict__
except Exception:
return str(o).replace('\n', '')
def toTEXT(self):
return json.dumps(self, default=lambda o: self._try(o)).strip()
def toJSON(self):
return json.loads(self.toTEXT())
def toCLASS(self, text=None):
if not text:
text = self.toTEXT()
return json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
#
# Exception definitions
#
class rcresult(CONFIG):
def __init__(self, errcode: int = 0, errmsg: str = ''):
self.errcode = errcode
self.text = errmsg
self.data = b''
# General error
error_unknown = rcresult(1, 'Unknown error')
error_file_already_exist = rcresult(2, 'File already exist')
error_file_not_found = rcresult(3, 'File not found')
error_path_not_exist = rcresult(4, 'Path is not exist')
error_not_a_file = rcresult(5, 'The specific path is not a file')
error_not_a_folder = rcresult(6, 'The specific path is not a folder')
error_file_not_identical = rcresult(7, 'File length is not identical')
error_exception = rcresult(9, 'An exception rised')
# Streaming
error_wait_timeout_streaming = rcresult(50, 'Wait streaming timeout')
error_wait_timeout_done = rcresult(51, 'Wait done timeout')
# Process
error_exception_proc_wait_timeout = rcresult(60, 'Wait timeout a process')
#
# Enumeration definitions
#
class action_name(Enum):
unknown = 0
upload = 1
download = 2
list = 3
execute = 4
message = 5
echo = 99
class action_kind(Enum):
unknown = 0
ask = 1
data = 2
done = 3
class execute_subcmd(Enum):
unknown = 0
start = 1
query = 2
kill = 3
class proc_status(Enum):
unknown = 0
unstart = 1
running = 2
killing = 3
killed = 4
terminated = 5
exception = 6
# ==============================================================================
# CLASSES
# ==============================================================================
#
# Inner Commands
#
class inncmd_sysinfo(CONFIG):
def __init__(self, osname: str = 'unknown', homedir: str = ''):
self.osname = osname
self.homedir = homedir
class inncmd_mkdir(CONFIG):
def __init__(self, path: str, result: bool = False):
self.path = path
self.result = result
#
# Basic classes
#
class execmdarg(CONFIG):
def __init__(self,
program: bytes,
argument: bytes = '',
workdir: bytes = '.',
isbase64: bool = False):
self.program = program
self.argument = argument
self.workdir = workdir
self.isbase64 = isbase64
class execresult(CONFIG):
def __init__(self):
self.errcode = 0
self.stdout = []
self.stderr = []
self.data = b''
class async_process():
def __init__(self, tag):
self.program = ''
self.argument = ''
self.workdir = '.'
self.status = proc_status.unknown
self.execrs = execresult()
self.tag: int = tag
self.thread = threading.Thread(target=self._thread_start)
self.thread.daemon = True
def _thread_start(self):
self.status = proc_status.running
try:
fullcmd = self.program
if '' != self.argument:
fullcmd += ' ' + self.argument
self.proc = subprocess.Popen(fullcmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=self.workdir)
try:
_WAIT_TIMEOUT_10_MINS_ = 60 * 5
self.execrs.errcode = self.proc.wait(_WAIT_TIMEOUT_10_MINS_)
logfmt = 'fullcmd={} errcode={}'
logging.error(logfmt.format(fullcmd, self.execrs.errcode))
stdout_lines = [line.decode('utf-8', errors="ignore").rstrip() for line in self.proc.stdout.readlines()]
self.execrs.stdout.extend(stdout_lines)
stderr_lines = [line.decode('utf-8', errors="ignore").rstrip() for line in self.proc.stderr.readlines()]
self.execrs.stderr.extend(stderr_lines)
self.status = proc_status.terminated
except Exception as Err:
self.execrs.errcode = 100000
self.status = proc_status.exception
self.execrs.stderr.append(Err)
except subprocess.TimeoutExpired as Err:
logging.exception(Err)
self.status = proc_status.exception
self.execrs.errcode = error_exception_proc_wait_timeout.errcode
self.execrs.stderr.append(error_exception_proc_wait_timeout.text)
self.execrs.stderr.append(str(Err))
except Exception as Err:
logging.exception(Err)
self.status = proc_status.exception
self.execrs.errcode = error_exception.errcode
self.execrs.stderr.append(error_exception.text)
self.execrs.stderr.append(str(Err))
finally:
pass
def run(self, program: str,
argument: str = '',
workdir: str = '.'):
self.program = program
self.argument = argument
self.workdir = workdir
if self.status != proc_status.unknown:
return
if self.thread:
self.thread.start()
self.status = proc_status.running
def kill(self):
if self.proc:
self.proc.terminate()
self.status = proc_status.killed
self.thread = None
def get_status(self):
return self.status
def get_tag(self):
return self.tag
class header_echo():
def __init__(self, kind: action_kind = action_kind.unknown, data: bytes = b''):
self.data = b''
self._STRUCT_FORMAT_ = '8s' + 'iiiii' + 'iii' + 'i'
self.signature: bytes = _SIGNATURE_ECHO___
self.header_size: int = 0
self.total_size: int = 0
self.payload_size: int = 0
self.action_name: int = action_name.echo.value
self.action_kind: int = kind.value
self.chunk_size: int = len(data)
self.chunk_count: int = 0
self.chunk_index: int = 0
self.errcode: int = 0
self.payload: bytes = data
def pack(self):
self.header_size = struct.calcsize(self._STRUCT_FORMAT_)
self.payload_size = self.chunk_size
self.total_size = self.header_size + self.payload_size
rawdata = struct.pack(self._STRUCT_FORMAT_,
self.signature,
self.header_size,
self.total_size,
self.payload_size,
self.action_name,
self.action_kind,
self.chunk_size,
self.chunk_count,
self.chunk_index,
self.errcode)
rawdata += self.payload
return rawdata
def unpack(self, data: bytes):
if len(data) <= _HEADER_SIZE_:
return None
hdr_size: int = int.from_bytes(data[8:11], 'little')
hdr_only: bytes = data[:hdr_size]
hdr = header_echo()
# Header files
unpack = struct.unpack(self._STRUCT_FORMAT_, hdr_only)
hdr.signature = unpack[0]
hdr.header_size = unpack[1]
hdr.total_size = unpack[2]
hdr.payload_size = unpack[3]
hdr.action_name = unpack[4]
hdr.action_kind = unpack[5]
hdr.chunk_size = unpack[6]
hdr.chunk_count = unpack[7]
hdr.chunk_index = unpack[8]
hdr.errcode = unpack[9]
# Payload
hdr.payload = data[hdr_size:]
# Unpack data from payload
hdr.data = hdr.payload
return hdr
class header_upload():
def __init__(self, kind: action_kind = action_kind.unknown,
filename: str = '',
filesize: int = 0,
dstdirpath: str = '.',
data: bytes = b''):
if filename is None:
filename = ''
if dstdirpath is None:
dstdirpath = '.'
self._STRUCT_FORMAT_ = '8s' + 'iiiiii' + 'iii' + 'i' + 'ii'
# Unpack payload fields
self.filename = b''
self.dstdirpath = b''
self.data = b''
self.signature: bytes = _SIGNATURE_UPLOAD_
self.header_size: int = 0
self.total_size: int = 0
self.payload_size: int = 0
self.file_size: int = filesize
self.action_name: int = action_name.upload.value
self.action_kind: int = kind.value
self.chunk_size: int = len(data)
self.chunk_count: int = 0
self.chunk_index: int = 0
self.errcode: int = 0
self.length_filename: int = len(filename)
self.length_dirpath: int = len(dstdirpath)
self.payload: bytes = (filename.encode('utf-8') +
dstdirpath.encode('utf-8') +
data)
def pack(self):
self.header_size = struct.calcsize(self._STRUCT_FORMAT_)
self.payload_size = (self.length_filename +
self.length_dirpath +
self.chunk_size)
self.total_size = self.header_size + self.payload_size
rawdata = struct.pack(self._STRUCT_FORMAT_,
self.signature,
self.header_size,
self.total_size,
self.payload_size,
self.file_size,
self.action_name,
self.action_kind,
self.chunk_size,
self.chunk_count,
self.chunk_index,
self.errcode,
self.length_filename,
self.length_dirpath)
rawdata += self.payload
return rawdata
def unpack(self, data: bytes):
if len(data) <= _HEADER_SIZE_:
return None
hdr_size: int = int.from_bytes(data[8:11], 'little')
hdr_only: bytes = data[:hdr_size]
hdr = header_upload()
# Header files
unpack = struct.unpack(self._STRUCT_FORMAT_, hdr_only)
hdr.signature = unpack[0]
hdr.header_size = unpack[1]
hdr.total_size = unpack[2]
hdr.payload_size = unpack[3]
hdr.file_size = unpack[4]
hdr.action_name = unpack[5]
hdr.action_kind = unpack[6]
hdr.chunk_size = unpack[7]
hdr.chunk_count = unpack[8]
hdr.chunk_index = unpack[9]
self.errcode = unpack[10]
hdr.length_filename = unpack[11]
hdr.length_dirpath = unpack[12]
# Payload
hdr.payload = data[hdr_size:]
# Unpack data from payload
pos1 = 0
pos2 = hdr.length_filename
if pos2 - pos1 > 0:
hdr.filename = str(hdr.payload[:pos2], 'utf-8')
pos1 = hdr.length_filename
pos2 = hdr.length_filename + hdr.length_dirpath
if pos2 - pos1 > 0:
hdr.dstdirpath = str(hdr.payload[pos1:pos2], 'utf-8')
pos1 = hdr.length_filename + hdr.length_dirpath
hdr.data = hdr.payload[pos1:]
return hdr
class header_download():
def __init__(self, kind: action_kind = action_kind.unknown,
filepath: str = '',
filesize: int = 0,
data: bytes = b''):
self._STRUCT_FORMAT_ = '8s' + 'iiiiii' + 'iii' + 'i' + 'i'
# Unpack payload fields
self.filepath = b''
self.data = b''
self.signature: bytes = _SIGNATURE_DOWNLO_
self.header_size: int = 0
self.total_size: int = 0
self.payload_size: int = 0
self.file_size: int = filesize
self.action_name: int = action_name.download.value
self.action_kind: int = kind.value
self.chunk_size: int = len(data)
self.chunk_count: int = 0
self.chunk_index: int = 0
self.errcode: int = 0
self.length_filepath: int = len(filepath)
self.payload: bytes = b''
if filepath:
self.payload += filepath.encode('utf-8')
if data:
self.payload += data
def pack(self):
self.header_size = struct.calcsize(self._STRUCT_FORMAT_)
self.payload_size = (self.length_filepath +
self.chunk_size)
self.total_size = self.header_size + self.payload_size
rawdata = struct.pack(self._STRUCT_FORMAT_,
self.signature,
self.header_size,
self.total_size,
self.payload_size,
self.file_size,
self.action_name,
self.action_kind,
self.chunk_size,
self.chunk_count,
self.chunk_index,
self.errcode,
self.length_filepath)
rawdata += self.payload
return rawdata
def unpack(self, data: bytes):
if len(data) <= _HEADER_SIZE_:
return None
hdr_size: int = int.from_bytes(data[8:11], 'little')
hdr_only: bytes = data[:hdr_size]
hdr = header_download()
# Header files
unpack = struct.unpack(self._STRUCT_FORMAT_, hdr_only)
hdr.signature = unpack[0]
hdr.header_size = unpack[1]
hdr.total_size = unpack[2]
hdr.payload_size = unpack[3]
hdr.file_size = unpack[4]
hdr.action_name = unpack[5]
hdr.action_kind = unpack[6]
hdr.chunk_size = unpack[7]
hdr.chunk_count = unpack[8]
hdr.chunk_index = unpack[9]
self.errcode = unpack[10]
hdr.length_filepath = unpack[11]
# Payload
hdr.payload = data[hdr_size:]
# Unpack data from payload
pos1 = 0
pos2 = hdr.length_filepath
if pos2 - pos1 > 0:
hdr.filepath = str(hdr.payload[:pos2], 'utf-8')
pos1 = hdr.length_filepath
hdr.data = hdr.payload[pos1:]
return hdr
class header_list():
def __init__(self,
kind: action_kind = action_kind.unknown,
dstdirpath: str = '',
data: bytes = b''):
if data is None:
data = b''
self._STRUCT_FORMAT_ = '8s' + 'iiiii' + 'iii' + 'i' + 'i'
# Unpack payload fields
self.dstdirpath = b''
self.data = b''
self.signature: bytes = _SIGNATURE_LIST___
self.header_size: int = 0
self.total_size: int = 0
self.payload_size: int = 0
self.action_name: int = action_name.list.value
self.action_kind: int = kind.value
self.chunk_size: int = len(data)
self.chunk_count: int = 0
self.chunk_index: int = 0
self.errcode: int = 0
self.length_dirpath: int = len(dstdirpath)
self.payload: bytes = (dstdirpath.encode('utf-8') +
data)
def pack(self):
self.header_size = struct.calcsize(self._STRUCT_FORMAT_)
self.payload_size = (self.length_dirpath +
self.chunk_size)
self.total_size = self.header_size + self.payload_size
rawdata = struct.pack(self._STRUCT_FORMAT_,
self.signature,
self.header_size,
self.total_size,
self.payload_size,
self.action_name,
self.action_kind,
self.chunk_size,
self.chunk_count,
self.chunk_index,
self.errcode,
self.length_dirpath)
rawdata += self.payload
return rawdata
def unpack(self, data: bytes):
if len(data) <= _HEADER_SIZE_:
return None
hdr_size: int = int.from_bytes(data[8:11], 'little')
hdr_only: bytes = data[:hdr_size]
hdr = header_list()
# Header files
unpack = struct.unpack(self._STRUCT_FORMAT_, hdr_only)
hdr.signature = unpack[0]
hdr.header_size = unpack[1]
hdr.total_size = unpack[2]
hdr.payload_size = unpack[3]
hdr.action_name = unpack[4]
hdr.action_kind = unpack[5]
hdr.chunk_size = unpack[6]
hdr.chunk_count = unpack[7]
hdr.chunk_index = unpack[8]
hdr.errcode = unpack[9]
hdr.length_dirpath = unpack[10]
# Payload
hdr.payload = data[hdr_size:]
# Unpack data from payload
pos1 = 0
pos2 = hdr.length_dirpath
if pos2 - pos1 > 0:
hdr.dstdirpath = str(hdr.payload[pos1:pos2], 'utf-8')
pos1 = hdr.length_dirpath
hdr.data = hdr.payload[pos1:]
return hdr
class header_execute():
def __init__(self,
kind: action_kind = action_kind.unknown,
subcmd: execute_subcmd = execute_subcmd.unknown,
program: bytes = b'',
argument: bytes = b'',
workdir: bytes = b'.',
isbase64: bool = False,
chunk_data: bytes = b''):
self._STRUCT_FORMAT_ = '8s' + 'iiiii' + 'iii' + 'iii' + 'i' + 'Biii'
#
# payload_data
#
self.cmdresult = execresult()
self.exec = execmdarg(program, argument, workdir, isbase64)
#
# chunk_data
#
self.chunk_data = chunk_data # execresult
#
# Header content
#
self.signature: bytes = _SIGNATURE_EXECUT_
self.header_size: int = 0
self.total_size: int = 0
self.payload_size: int = 0
self.action_name: int = action_name.execute.value
self.action_kind: int = kind.value
self.subcmd_value: int = 0
self.status_value: int = proc_status.unknown.value
self.tag_value = 0
if subcmd:
self.subcmd_value = subcmd.value
self.chunk_size: int = len(chunk_data)
self.chunk_count: int = 0
self.chunk_index: int = 0
if self.chunk_size > 0:
self.chunk_count = 1
self.errcode: int = 0
self.length_isbase64: int = 1
self.length_program: int = len(program)
self.length_argument: int = len(argument)
self.length_workdir: int = len(workdir)
def pack(self):
self.header_size = struct.calcsize(self._STRUCT_FORMAT_)
self.payload_size = (self.length_isbase64 +
self.length_program +
self.length_argument +
self.length_workdir +
self.chunk_size)
self.total_size = self.header_size + self.payload_size
packed_data = struct.pack(self._STRUCT_FORMAT_,
self.signature,
self.header_size,
self.total_size,
self.payload_size,
self.action_name,
self.action_kind,
self.subcmd_value,
self.status_value,
self.tag_value,
self.chunk_size,
self.chunk_count,
self.chunk_index,
self.errcode,
self.length_isbase64,
self.length_program,
self.length_argument,
self.length_workdir)
isbase = b''
if self.exec.isbase64:
isbase = b'1'
else:
isbase = b'0'
data = (isbase +
self.exec.program +
self.exec.argument +
self.exec.workdir +
self.chunk_data)
packed_data = packed_data + data
assert len(packed_data) == self.total_size, 'data lengths are not identical !!!'
return packed_data
def unpack(self, chunk_data_raw: bytes):
packed_data_len = len(chunk_data_raw)
if packed_data_len <= _HEADER_SIZE_:
logfmt = '[header_execute] buffer is insufficient !!! (data_len={})'
logging.info(logfmt.format(packed_data_len))
return None
hdr_size: int = int.from_bytes(chunk_data_raw[8:11], 'little')
total_size: int = int.from_bytes(chunk_data_raw[12:15], 'little')
logging.info('[header_execute] hdr_size={}'.format(hdr_size))
logging.info('[header_execute] total_size={}'.format(total_size))
if packed_data_len < total_size:
logfmt = '[header_execute] buffer is insufficient !!! ' + \
'(data_len={} less than total_size={})'
logging.info(logfmt.format(packed_data_len, total_size))
return None
header_content: bytes = chunk_data_raw[:hdr_size]
hdr = header_execute()
# Header files
unpack = struct.unpack(self._STRUCT_FORMAT_, header_content)
hdr.signature = unpack[0]
hdr.header_size = unpack[1]
hdr.total_size = unpack[2]
hdr.payload_size = unpack[3]
hdr.action_name = unpack[4]
hdr.action_kind = unpack[5]
hdr.subcmd_value = unpack[6]
hdr.status_value = unpack[7]
hdr.tag_value = unpack[8]
hdr.chunk_size = unpack[9]
hdr.chunk_count = unpack[10]
hdr.chunk_index = unpack[11]
hdr.errcode = unpack[12]
hdr.length_isbase64 = unpack[13]
hdr.length_program = unpack[14]
hdr.length_argument = unpack[15]
hdr.length_workdir = unpack[16]
#
# Payload (payload_data + chunk_data)
#
payload_content = chunk_data_raw[hdr.header_size: hdr.total_size]
# Unpack data from payload
pos1 = 0
pos2 = (pos1 + 1)
isbase64 = payload_content[pos1:pos2]
hdr.exec.isbase64 = bool(int(isbase64))
pos1 = pos2
pos2 = pos2 + hdr.length_program
program = payload_content[pos1:pos2]
# hdr.program = str(program, encoding='utf-8')
hdr.exec.program = program
pos1 = pos2
pos2 = pos2 + hdr.length_argument
argument = payload_content[pos1:pos2]
# hdr.argument = str(argument, encoding='utf-8')
hdr.exec.argument = argument
pos1 = pos2
pos2 = pos2 + hdr.length_workdir
workdir = payload_content[pos1:pos2]
# hdr.workdir = str(workdir, 'utf-8')
hdr.exec.workdir = workdir
# chunk_data
pos1 = pos2
pos2 = pos2 + hdr.chunk_size
if pos2 - pos1 > 0:
chunk_data_raw = payload_content[pos1:pos2]
chunk_data_ori: execresult = CONFIG().toCLASS(chunk_data_raw)
hdr.chunk_data = chunk_data_ori
return hdr
class header_message():
def __init__(self, kind: action_kind = action_kind.unknown, title: str = 'default', data: bytes = b''):
self._STRUCT_FORMAT_ = '8s' + 'iiiii' + 'iii' + 'i' + 'i'
#
# payload_data
#
self.title: str = title
#
# payload_chunk
#
self.payload_chunk = data
#
# Header content
#
self.signature: bytes = _SIGNATURE_TEXT___
self.header_size: int = 0
self.total_size: int = 0
self.payload_size: int = 0
self.action_name: int = action_name.message.value
self.action_kind: int = kind.value
self.chunk_size: int = len(data)
self.chunk_count: int = 0
self.chunk_index: int = 0
self.errcode: int = 0
self.length_title: int = len(title)
if len(data) > 0:
self.chunk_count = 1
def pack(self):
self.header_size = struct.calcsize(self._STRUCT_FORMAT_)
self.payload_size = self.length_title + self.chunk_size
self.total_size = self.header_size + self.payload_size
rawdata = struct.pack(self._STRUCT_FORMAT_,
self.signature,
self.header_size,
self.total_size,
self.payload_size,
self.action_name,
self.action_kind,
self.chunk_size,
self.chunk_count,
self.chunk_index,
self.errcode,
self.length_title)
payload = (self.title.encode('ascii') + self.payload_chunk)
rawdata += payload
return rawdata
def unpack(self, data: bytes):
if len(data) <= _HEADER_SIZE_:
return None
hdr_size: int = int.from_bytes(data[8:11], 'little')
hdr_only: bytes = data[:hdr_size]
hdr = header_message()
# Header files
unpack = struct.unpack(self._STRUCT_FORMAT_, hdr_only)
hdr.signature = unpack[0]
hdr.header_size = unpack[1]
hdr.total_size = unpack[2]
hdr.payload_size = unpack[3]
hdr.action_name = unpack[4]
hdr.action_kind = unpack[5]
hdr.chunk_size = unpack[6]
hdr.chunk_count = unpack[7]
hdr.chunk_index = unpack[8]
hdr.errcode = unpack[9]
hdr.length_title = unpack[10]
#
# Payload
#
pos1 = self.header_size
pos2 = pos1 + self.total_size
payload = data[pos1:pos2]
# payload_data
pos1 = 0
pos2 = self.length_title
hdr.title = str(payload[pos1:pos2], encoding='ascii')
# payload_chunk
pos1 = pos2
pos2 = pos1 + self.chunk_size
hdr.payload_chunk = payload[pos1:pos2]
return hdr
class header():
def __init__(self):
pass
def find_header(self, data: bytes):
data_len = len(data)
if data_len < _HEADER_SIZE_:
logging.info('buffer is insufficient !!! (data_len={})'.format(data_len))
return None, 0
index = 0
matched_index = -1
targets = [_SIGNATURE_UPLOAD_, # 0
_SIGNATURE_DOWNLO_, # 1
_SIGNATURE_EXECUT_, # 2
_SIGNATURE_LIST___, # 3
_SIGNATURE_ECHO___, # 4
_SIGNATURE_TEXT___] # 5
signature_pos = -1
for item in targets:
signature_pos = data.find(item)
if signature_pos >= 0:
matched_index = index
logging.info('signature matched (matched_index={}).'.format(matched_index))
break
index += 1
hdr_pos1 = signature_pos + 8
hdr_pos2 = hdr_pos1 + 4
header_size: int = int.from_bytes(data[hdr_pos1:hdr_pos2], 'little')
if data_len < header_size:
logging.info('buffer is insufficient !!! (data_len is less than header_size)')
return None, 0
found_hdr = None
hdr_pos1 = signature_pos + 12
hdr_pos2 = hdr_pos1 + 4
total_size: int = int.from_bytes(data[hdr_pos1:hdr_pos2], 'little')
if data_len < total_size:
logging.info('buffer is insufficient !!! (data_len is less than total_size)')
return None, 0