-
Notifications
You must be signed in to change notification settings - Fork 9
/
dwcommand.py
1516 lines (1356 loc) · 51.7 KB
/
dwcommand.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 threading
import traceback
import subprocess
from dwsocket import *
from dwtelnet import DWTelnet
import os
import sys
import re
import urlparse
import tempfile
from dwserial import DWSerial
class ParseNode:
def __init__(self, name, nodes=None):
self.name = name
self.nodes = {}
if nodes:
self.nodes = nodes
def add(self, key, val):
self.nodes[key] = val
def lookup(self, key):
if not key:
return None
# exact match
r = self.nodes.get(key, None)
if r:
return r
key = key.lower()
r = self.nodes.get(key, None)
if r:
return r
# search partial
allNodes = self.nodes.keys()
for i in range(len(key) + 1):
s = key[:i]
nodes = [n for n in allNodes if n.startswith(s)]
# print i,"(%s"%s,nodes
if len(nodes) == 1:
key = nodes[0]
return self.nodes.get(key, None)
return None
def repr(self):
return str(nodes)
def help(self):
p = []
if self.name:
p.append(self.name)
p.append("commands:")
p.extend(self.nodes.keys())
return "%s" % (' '.join(p))
class ATParseNode(ParseNode):
def __init__(self, name, nodes=None):
ParseNode.__init__(self, name, nodes)
def lookup(self, key):
k = key[0]
r = ParseNode.lookup(self, k)
if not r:
k = key[0:1]
r = ParseNode.lookup(self, k.upper())
return r
def help(self):
# if self.name:
# p.append(self.name)
p = ["commands:"]
p.extend(["AT%s" % k for k in self.nodes])
return "%s" % (' '.join(p))
class ParseAction:
def __init__(self, fn):
self.fn = fn
def call(self, *args):
return self.fn(*args)
def repr(self):
return fn
class DWParser:
def setupParser(self):
diskParser = ParseNode("disk")
diskParser.add("insert", ParseAction(self.doInsert))
diskParser.add("reset", ParseAction(self.doReset))
diskParser.add("eject", ParseAction(self.doEject))
diskParser.add("show", ParseAction(self.doShow))
diskParser.add("offset", ParseAction(self.doDiskOffset))
diskParser.add("create", ParseAction(self.doDiskCreate))
diskParser.add("info", ParseAction(self.doDiskInfo))
diskParser.add("dosplus", ParseAction(self.doDiskDosPlus))
serverParser = ParseNode("server")
serverParser.add("instance", ParseAction(self.doInstanceShow))
serverParser.add("dir", ParseAction(self.doDir))
serverParser.add("list", ParseAction(self.doList))
serverParser.add("dump", ParseAction(self.dumpstacks))
serverParser.add("debug", ParseAction(self.doDebug))
serverParser.add("timeout", ParseAction(self.doTimeout))
serverParser.add("version", ParseAction(self.doVersion))
serverParser.add("hdbdos", ParseAction(self.doHdbDos))
serverParser.add("dosplus", ParseAction(self.doServerDosPlus))
connParser = ParseNode("conn")
connParser.add("debug", ParseAction(self.doConnDebug))
serverParser.add("conn", connParser)
serverParser.add("pwd", ParseAction(self.doPwd))
serverParser.add("getdir", ParseAction(self.doDwGetDir))
serverParser.add("setdir", ParseAction(self.doDwSetDir))
portParser = ParseNode("port")
portParser.add("show", ParseAction(self.doPortShow))
portParser.add("close", ParseAction(self.doPortClose))
portParser.add("debug", ParseAction(self.doPortDebug))
portParser.add("term", ParseAction(self.doPortTerm))
portParser.add("rows", ParseAction(self.doPortRows))
portParser.add("cols", ParseAction(self.doPortCols))
# portParser.add("size", ParseAction(self.doPortSize)) XXX: Not working
instanceParser = ParseNode("instance")
instanceParser.add("show", ParseAction(self.doInstanceShow))
instanceParser.add("add", ParseAction(self.doInstanceShow))
instanceParser.add("select", ParseAction(self.doInstanceSelect))
printParser = ParseNode("printer")
printParser.add("flush", ParseAction(self.doPrintFlush))
printParser.add("format", ParseAction(self.doPrintFormat))
printParser.add("file", ParseAction(self.doPrintFile))
printParser.add("dir", ParseAction(self.doPrintDir))
printParser.add("prefix", ParseAction(self.doPrintPrefix))
printParser.add("cmd", ParseAction(self.doPrintCmd))
printParser.add("status", ParseAction(self.doPrintStatus))
configParser = ParseNode("config")
configParser.add("show", ParseAction(self.doConfigShow))
configParser.add("save", ParseAction(self.doConfigSave))
dwParser = ParseNode("dw")
dwParser.add("disk", diskParser)
dwParser.add("server", serverParser)
dwParser.add("port", portParser)
dwParser.add("instance", instanceParser)
dwParser.add("printer", printParser)
dwParser.add("config", configParser)
tcpParser = ParseNode("tcp")
tcpParser.add("connect", ParseAction(self.doConnect))
tcpParser.add("listen", ParseAction(self.doListen))
tcpParser.add("join", ParseAction(self.doJoin))
tcpParser.add("kill", ParseAction(self.doKill))
atParser = ATParseNode("AT")
atParser.add(
"",
ParseAction(
lambda x: {
'msg': 'OK',
'self.cmdClass': 'AT'}))
atParser.add(
"Z",
ParseAction(
lambda x: {
'msg': 'OK',
'self.cmdClass': 'AT'}))
atParser.add("D", ParseAction(self.doDial))
atParser.add(
"I",
ParseAction(
lambda x: {
'msg': 'pyDriveWire %s\r\nOK' % self.server.version,
'self.cmdClass': 'AT'}))
atParser.add(
"O",
ParseAction(
lambda x: {
'msg': 'OK',
'self.cmdClass': 'AT'}))
atParser.add(
"H",
ParseAction(
lambda x: {
'msg': 'OK',
'self.cmdClass': 'AT'}))
atParser.add(
"E",
ParseAction(
lambda x: {
'msg': 'OK',
'self.cmdClass': 'AT',
'self.echo': True}))
uiSFileParser = ParseNode("file")
uiSFileParser.add("defaultdir", ParseAction(self.doUSFdefaultdir))
uiSFileParser.add("dir", ParseAction(self.doUSFdir))
uiSFileParser.add("info", ParseAction(self.doUSFinfo))
uiSFileParser.add("roots", ParseAction(self.doUSFroots))
uiSFileParser.add("xdir", ParseAction(self.doUSFxdir))
uiServerParser = ParseNode("server")
uiServerParser.add("file", uiSFileParser)
uiParser = ParseNode("ui")
uiParser.add("server", uiServerParser)
mcAliasParser = ParseNode("alias")
mcAliasParser.add("show", ParseAction(self.doMcAliasShow))
mcAliasParser.add("add", ParseAction(self.doMcAliasAdd))
mcAliasParser.add("remove", ParseAction(self.doMcAliasRemove))
mcParser = ParseNode("mc")
mcParser.add("alias", mcAliasParser)
mcParser.add("setdir", ParseAction(self.doMcSetDir))
mcParser.add("getdir", ParseAction(self.doMcGetDir))
mcParser.add("listdir", ParseAction(self.doMcListDir))
mcParser.add("show", ParseAction(self.doShow))
mcParser.add("eject", ParseAction(self.doEject))
dloadAliasParser = ParseNode("alias")
dloadAliasParser.add("show", ParseAction(self.doDloadAliasShow))
dloadAliasParser.add("add", ParseAction(self.doDloadAliasAdd))
dloadAliasParser.add("remove", ParseAction(self.doDloadAliasRemove))
dloadParser = ParseNode("dload")
dloadParser.add("alias", dloadAliasParser)
dloadParser.add("status", ParseAction(self.doDloadStatus))
dloadParser.add("enable", ParseAction(self.doDloadEnable))
dloadParser.add("disable", ParseAction(self.doDloadDisable))
dloadParser.add("setdir", ParseAction(self.doDloadSetDir))
dloadParser.add("getdir", ParseAction(self.doDloadGetDir))
dloadParser.add("listdir", ParseAction(self.doDloadListDir))
dloadParser.add("translate", ParseAction(self.doDloadTranslate))
nobjAliasParser = ParseNode("alias")
nobjAliasParser.add("show", ParseAction(self.doNamedObjAliasShow))
nobjAliasParser.add("add", ParseAction(self.doNamedObjAliasAdd))
nobjAliasParser.add("remove", ParseAction(self.doNamedObjAliasRemove))
nobjParser = ParseNode("namedobj")
nobjParser.add("alias", nobjAliasParser)
nobjParser.add("setdir", ParseAction(self.doNamedObjSetDir))
nobjParser.add("getdir", ParseAction(self.doNamedObjGetDir))
nobjParser.add("listdir", ParseAction(self.doNamedObjListDir))
nobjParser.add("show", ParseAction(self.doShow))
nobjParser.add("eject", ParseAction(self.doEject))
psAliasParser = ParseNode("alias")
psAliasParser.add("show", ParseAction(self.doPlaySoundAliasShow))
psAliasParser.add("add", ParseAction(self.doPlaySoundAliasAdd))
psAliasParser.add("remove", ParseAction(self.doPlaySoundAliasRemove))
playSoundParser = ParseNode("playsound")
playSoundParser.add("alias", psAliasParser)
playSoundParser.add("setdir", ParseAction(self.doPlaySoundSetDir))
playSoundParser.add("getdir", ParseAction(self.doPlaySoundGetDir))
playSoundParser.add("listdir", ParseAction(self.doPlaySoundListDir))
playSoundParser.add("play", ParseAction(self.doPlaySoundPlay))
playSoundParser.add("stop", ParseAction(self.doPlaySoundStop))
self.parseTree = ParseNode("")
self.parseTree.add("dw", dwParser)
self.parseTree.add("tcp", tcpParser)
self.parseTree.add("AT", atParser)
self.parseTree.add("ui", uiParser)
self.parseTree.add("mc", mcParser)
self.parseTree.add("dload", dloadParser)
self.parseTree.add("namedobj", nobjParser)
self.parseTree.add("playsound", playSoundParser)
self.parseTree.add("telnet", ParseAction(self.doTelnet))
self.parseTree.add("ssh", ParseAction(self.doSsh))
self.parseTree.add("help", ParseAction(self.ptWalker))
self.parseTree.add("pwd", ParseAction(self.doPwd))
self.parseTree.add("?", ParseAction(self.ptWalker))
def __init__(self, server):
self.server = server
self.setupParser()
def doInsert(self, data):
opts = data.split(' ')
usageMsg = "dw disk insert <drive> <path> [<opts>]"
if len(opts) < 2:
raise Exception('Usage: '+usageMsg)
drive = opts[0]
try:
_ = int(drive)
except:
raise Exception("Invalid drive: %s\r\nUsage: %s" % (drive, usageMsg))
pathStart = len(drive) + 1
pathEnd = len(data)
stream = False
mode = 'rb+'
raw = False
proto = 'dw'
dosplus = None
for s in opts[2:]:
if s.lower() == '--stream':
stream = True
pathEnd -= 9 # len(' --stream')
elif s.lower() == '--ro':
mode = 'r'
pathEnd -= 5 # len(' --ro')
elif s.lower() == '--raw':
raw = True
pathEnd -= 6 # len(' --raw')
elif s.lower() == '--dw':
proto = 'dw'
pathEnd -= 5 # len(' --dw')
#elif s.lower() == '--mc':
# proto = 'mc'
# pathEnd -= 5 # len(' --mc')
elif s.lower() == '--dload':
proto = 'dload'
raw = True
pathEnd -= 8 # len(' --dload')
elif s.lower() == '--namedobj':
proto = 'namedobj'
raw = True
pathEnd -= 11 # len(' --namedobj')
elif s.lower() == '--dosplus':
dosplus = True
pathEnd -= 10 # len(' --dosplus')
path = data[pathStart:pathEnd]
try:
self.server.open(int(drive), path, mode=mode, stream=stream, raw=raw, proto=proto, dosplus=dosplus)
except Exception as e:
return str(e)
return "open(%d, %s)" % (int(drive), path)
def doDiskCreate(self, data):
usageMsg = "dw disk create <drive> <path> [<opts>]"
opts = data.split(' ')
if len(opts) < 2:
raise Exception(usageMsg)
drive = opts[0]
try:
_ = int(drive)
except:
raise Exception("Invalid drive: %s\r\nUsage: %s" % (drive, usageMsg))
pathStart = len(drive) + 1
pathEnd = len(data)
stream = False
mode = 'ab+'
path = data[pathStart:pathEnd]
self.server.open(int(drive), path, mode=mode, stream=stream, create=True, proto='dw')
return "create(%d, %s)" % (int(drive), path)
def doDiskInfo(self, data):
opts = data.split(' ')
usageMsg = "dw disk info <drive>"
if len(opts) < 1:
raise Exception(usageMsg)
try:
drive = int(opts[0])
except:
raise Exception("Invalid drive: %s\r\nUsage: %s" % (opts[0], usageMsg))
fi = self.server.files[drive]
if fi is None:
return "Drive %d: Not inserted" % drive
out = [
'Drive: %d' % drive,
'Path: %s' % fi.file.name,
'Size: %d' % fi.img_size,
'Sectors: %d' % fi.img_sectors,
'MaxLsn: %d' % fi.maxLsn,
'Format: %s' % fi.fmt,
'Offset: %s' % fi.offset,
'Byte Offset: %s' % fi.byte_offset,
'Proto: %s' % fi.proto,
'flags: mode=%s, remote=%s stream=%s raw=%s dosplus=%s' % (fi.mode, fi.remote, fi.stream, fi.raw, fi.dosplus)
]
return '\r\n'.join(out)
def doReset(self, data):
try:
drive = int(data.split(' ')[0])
except:
raise Exception("dw disk reset <drive>")
dl = len(self.server.files)
if drive >= dl:
raise Exception('Drive higher than maximum %d' % dl)
if self.server.files[drive] is None:
return "Drive %d not mounted" % drive
self.server.reset(drive)
return "reset(%d, %s)" % (int(drive), self.server.files[drive].name)
def doEject(self, data):
try:
drive = int(data.split(' ')[0])
except:
raise Exception("Usage: dw disk eject <drive>")
dl = len(self.server.files)
if drive >= dl:
raise Exception('Drive higher than maximum %d' % dl)
if self.server.files[drive] is None:
return "Drive %d not mounted" % drive
self.server.close(drive)
return "close(%d)" % (drive)
def doHdbDos(self, data):
data = data.lstrip().rstrip()
if data:
if data.startswith(('1', 'on', 't', 'T', 'y', 'Y')):
self.server.hdbdos = True
elif data.startswith(('0', 'off', 'f', 'F', 'n', 'N')):
self.server.hdbdos = False
else:
raise Exception("dw server hdbdos [0|1|on|off|t|T|f|F|y|Y|n|N]")
return "hdbdos=%s" % (self.server.hdbdos)
def doDiskOffset(self, data):
dp = data.split(' ')
usageMsg = 'dw disk offset <drive> <offset>'
if len(dp) <2:
raise Exception('Usage: %s' % usageMsg)
try:
drive = int(dp[0])
except:
raise Exception("Invalid drive: %s\r\nUsage: %s" % (dp[0], usageMsg))
dl = len(self.server.files)
if drive >= dl:
raise Exception('Drive higher than maximum %d' % dl)
if self.server.files[drive] is None:
return "Drive %d not mounted" % drive
offset = self.server.files[drive].offset
if len(dp) >= 2:
try:
offset = eval(dp[1])
self.server.files[drive].offset = offset
except BaseException:
return "Invalid offset: %s" % (hex(offset))
return "drive(%d) offset(%s)" % (drive, hex(offset))
def doDosPlus(self, data, server=False):
if server:
usageStr = "Usage: dw server dosplus [0|1|on|off|t|T|f|F|y|Y|n|N]"
opt = 0
nopts = 1
else:
usageStr = "Usage: dw disk dosplus <drive> [0|1|on|off|t|T|f|F|y|Y|n|N]"
opt = 1
nopts = 2
dp = data.split(' ')
if not server and (len(dp) < 1 or len(dp) > 2):
raise exception('Usage: '+usageStr)
if server:
n = self.server.dosplus
else:
try:
drive = int(dp[0])
except:
raise Exception("Invalid drive: %s\r\nUsage: %s" % (dp[0], usageStr))
n = self.server.files[drive].dosplus
if len(dp) == nopts:
if dp[opt].startswith(('1', 'on', 't', 'T', 'y', 'Y')):
n = True
elif dp[opt].startswith(('0', 'off', 'f', 'F', 'n', 'N')):
n = False
elif not server:
raise Exception(usageStr)
if server:
self.server.dosplus = n
return "server dosplus(%s)" % (n)
else:
self.server.files[drive].dosplus = n
return "drive(%d) dosplus(%s)" % (drive, n)
def doDiskDosPlus(self, data):
return self.doDosPlus(data, server=False)
def doServerDosPlus(self, data):
return self.doDosPlus(data, server=True)
def doInstanceSelect(self, data):
try:
instance = int(data.split(' ')[0])
except:
raise Exception("dw instance select <instance>")
if instance >= len(self.server.instances):
return 'Invalid instance %d' % instance
self.server = self.server.instances[instance]
return "Selected Instance %s: %s" % (
self.server.instance, self.server.conn.name())
def doInstanceShow(self, data):
out = ['', '']
out.append("Inst. Type")
out.append("----- --------------------------------------")
i = 0
for inst in self.server.instances:
c = ' '
if i == self.server.instance:
c = '*'
if 'instName' in inst.args:
name = '[%s]' % inst.args.instName
else:
name = '(main)'
out.append("%d%c %s %s" % (i, c, name, inst.conn.name()))
i += 1
out.append('')
return '\n\r'.join(out)
def doPortClose(self, data):
data = data.lstrip().rstrip()
if not data:
raise Exception("Usage: dw port close <portNum>")
try:
channel = chr(int(data))
except:
raise Exception("Invalid port %s" % channel)
if channel not in self.server.channels:
return "Invalid port %s" % channel
ch = self.server.channels[channel]
ch.close()
del self.server.channels[channel]
return "Port=n%s closing" % data
def doPortShow(self, data):
out = ['', '']
out.append("Port Status")
out.append("----- --------------------------------------")
i = 0
for i, ch in self.server.channels.items():
co = ch.conn
connstr = "State: %s Class: %s" % (ch.getState(), ch.cmdClass)
# connstr = " Online" if ch.online else "Offline"
# if co:
# direction = " In" if ch.inbound else "Out"
# connstr = "%s %s %s:%s" % (connstr, direction, co.host, co.port)
out.append("N%d %s" % (int(ord(i)), connstr))
out.append('')
args = self.server.args
out.append('Term: %s Rows: %s Cols: %s' % (
args.portTerm,
args.portRows,
args.portCols))
return '\n\r'.join(out)
def doPortDebug(self, data):
data = data.lstrip().rstrip()
usageStr = "Usage: dw port debug <port> [0|1|on|off|t|T|f|F|y|Y|n|N]"
if not data:
raise Exception(usageStr)
dv = data.split(' ')
if len(dv)<1 or len(dv)>2:
raise Exception(usageStr)
try:
cn = dv[0]
channel = chr(int(cn))
except:
raise Exception('Invalid port: %s' %cn)
if not channel in self.server.channels:
return "Invalid port: %s" % cn
state = None
if len(dv) > 1:
state = dv[1]
ch = self.server.channels[channel]
if state.startswith(('1', 'on', 't', 'T', 'y', 'Y')):
ch.debug = True
if state.startswith(('0', 'off', 'f', 'F', 'n', 'N')):
ch.debug = False
return "Port=N%s debug=%s" % (cn, ch.debug)
def doPortTerm(self, data):
data = data.lstrip().rstrip()
args = self.server.args
if data:
args.portTerm = data
return "Terminal Type: %s" % args.portTerm
def doPortRows(self, data):
data = data.lstrip().rstrip()
if data:
try:
int(data)
except:
raise Exception('Usage: dw port rows <rows>')
args = self.server.args
if data:
args.portRows = int(data)
return "Terminal Rows: %s" % args.portRows
def doPortCols(self, data):
data = data.lstrip().rstrip()
if data:
try:
int(data)
except:
raise Exception('Usage: dw port cols <cols>')
args = self.server.args
if data:
args.portCols = int(data)
return "Terminal Cols: %s" % args.portCols
# XXX: Not working
def _doAnsiCPR(self):
if not self.conn:
return (1,1)
print('doAnsiCpr')
okChars = '\e0123456789;R['
print('send CPR')
self.conn.write('\e[6n')
s = ''
ok = True
while ok:
c = self.conn.read(1)
print('read %s' % c)
if c not in okChars:
ok = False
else:
s += c
if c =='R':
break
ok = True
print('ok=%s' % ok)
if not ok:
return (16,32)
(row,col) = s.split(';')
row = row[2:]
col = col[:-1]
return(row, col)
# XXX: Not working
def _doPortDiscoverSize(self):
if not self.conn:
return(16,32)
(oldRow, oldCol) = self._doAnsiCPR()
self.conn.write('\e[133;133H')
(maxRow, maxCol) = self._doAnsiCPR()
self.conn.write('\e%d;%dH' % (oldRow, oldCol))
return (maxRow, maxCol)
# XXX: Not working
def doPortSize(self, data):
data = data.lstrip().rstrip()
args = self.server.args
if data:
p = data.split(' ')
if p[0] == 'auto':
args.portSize = p[0]
elif len(p) == 2:
args.portSize = None
args.portRows = int(p[0])
args.portCols = int(p[1])
elif len(p) > 2:
raise Exception('Usage: dw port size auto | <rows> <cols>')
if args.portSize == 'auto':
(args.portRows, args.portCols) = self._doPortDiscoverSize()
msg = 'auto: rows=%d cols=%d' % (args.portRows, args.portCols)
elif args.portRows and args.portCols:
msg = 'rows=%d cols=%d' % (args.portRows, args.portCols)
return "Terminal Size: %s" % msg
def doShow(self, data):
out = ['', '']
out.append("Drive File")
out.append("----- --------------------------------------")
i = 0
# for f in self.server.files[:4]:
for f in self.server.files:
if i >= 4 and f is None:
i += 1
continue
name = f.name if f else f
if f and f.remote:
name += '(%s)' % f.file.name
out.append("%-3d %s" % (i, name))
i += 1
out.append('')
return '\n\r'.join(out)
def doConnDebug(self, data):
data = data.lstrip().rstrip()
if data.startswith(('1', 'on', 't', 'T', 'y', 'Y')):
self.server.conn.debug = True
elif data.startswith(('0', 'off', 'f', 'F', 'n', 'N')):
self.server.conn.debug = False
elif data:
raise Exception("Usage: dw server conn debug [0|1|on|off|t|T|f|F|y|Y|n|N]")
return "connDebug=%s" % (self.server.conn.debug)
def doTimeout(self, data):
opts = data.lstrip().rstrip().split(' ')
if opts:
try:
timeout = float(opts[0])
except:
raise Exception("Invalid timeout: %s" % data)
self.server.timeout = timeout
return "timeout=%s" % (self.server.timeout)
def doVersion(self, data):
return "pyDriveWire Server %s" % self.server.version
def doDebug(self, data):
out = []
if data.startswith(('on', 't', 'T', 'y', 'Y')):
self.server.debug = True
elif data.startswith(('off', 'f', 'F', 'n', 'N')):
self.server.debug = False
elif data and data[0].isdigit():
d = int(data[0])
self.server.debug = d
if d == 2:
out += [self.doConnDebug('1')]
elif d < 2:
out += [self.doConnDebug('0')]
else:
raise Exception("dw server debug [T|f|F|F|Y|y|N|n|0|1|2|on|off]")
elif data:
raise Exception("dw server debug [T|f|F|F|Y|y|N|n|0|1|2|on|off]")
out += ["debug=%s" % (self.server.debug)]
return '\r\n'.join(out)
# def doDir(self, data, nxti):
def doDir(self, data, msg=None):
out = ['']
if msg is not None:
out += msg
# print "doDir data=(%s)" % data
if not data:
data = os.getcwd()
out.extend(os.listdir(os.path.expanduser(data)))
out.append('')
return '\n\r'.join(out)
def doList(self, path, msg=None):
out = []
if msg is not None:
out += msg
# cmd = ['cat']
# path = data.split(' ')[0]
path = path.lsplit().rsplit()
if not path:
raise Exception("Usage: dw server list <path>")
# cmd.append(path)
# data2 = subprocess.Popen(
# " ".join(cmd),
# stdout=subprocess.PIPE,
# stderr=subprocess.STDOUT,
# shell=True)
# out.extend(data2.stdout.read().strip().split('\n'))
out.extend(open(os.path.expanduser(path)).read().split('\n'))
# out.append('')
return '\n\r'.join(out)
def doSsh(self, data):
return self.doConnect(data, ssh=True, interactive=True)
def doTelnet(self, data):
return self.doConnect(data, telnet=True, interactive=True)
def doDial(self, data):
return self.doConnect(data, telnet=False, ssh=False, interactive=True)
def doConnect(self, data, telnet=False, ssh=False, interactive=False):
pr = urlparse.urlparse(data)
args = self.server.args
if pr.scheme == 'ssh':
ssh = True
if ssh:
if (not args.experimental) or (args.experimental and 'ssh' not in args.experimental):
raise Exception("Ssh is not enabled, use: -x ssh")
if pr.scheme == 'telnet':
d2 = pr.netloc
telnet = True
# elif pr.scheme == '':
elif pr.scheme == 'ssh':
ssh = True
if not all([pr.username, pr.password, pr.hostname]):
raise Exception('Invalid URI: ssh://<username>:<password>@<hostname>[:<port>]')
if pr.port:
try:
int(pr.port)
except BaseException:
raise Exception('Invalid URI: ssh://<username>:<password>@<hostname>[:<port>]')
hp = "%s:%s" % (pr.hostname, pr.port)
else:
hp = pr.hostname
d2 = "%s %s %s" % (hp, pr.username, pr.password)
else:
d2 = data
host = port = username = password = None
if ssh:
p = d2.split(' ')
if len(p) != 3:
raise Exception("Usage: ssh <hostname>[:<port>] <username> <password>")
(hp, username, password) = p
hpp = hp.split(':')
host = hpp[0]
if len(hpp) == 1:
port = '22'
else:
port = hpp[1]
print("host (%s)" % host)
print("port (%s)" % port)
print("username (%s)" % username)
l = len(password)
print("password (%s)[%d]" % ('*' * l, l))
else:
r = d2.split(':')
if len(r) == 1:
r = d2.split(' ')
if len(r) == 1:
r.append('23')
(host, port) = r
print "host (%s)" % host
print "port (%s)" % port
try:
int(port)
except BaseException:
port = None
if not host or not port:
if pr.scheme == 'telnet':
raise Exception("Usage: telnet://<hostname>[:<port>]")
elif telnet:
raise Exception("Usage: telnet <hostname> [<port>]")
elif interactive:
raise Exception("Usage: ATD<hostname>[:<port>]")
else:
raise Exception("Usage: tcp connect <hostname> [<port>]")
try:
if telnet:
sock = DWTelnet(host=host, port=port, debug=self.server.debug)
elif ssh:
from dwssh import DWSsh
args = self.server.args
sock = DWSsh(
host,
username,
password,
port=port,
args=self.server.args,
debug=self.server.debug)
else:
sock = DWSocket(host=host, port=port, debug=self.server.debug)
if telnet or interactive:
res = {
'msg': '\r\nCONNECTED',
'obj': sock,
'self.cmdClass': 'AT',
'self.online': True}
else:
res = {
'msg': None,
'obj': sock,
'self.cmdClass': 'TCP'}
sock.connect()
except Exception as ex:
if telnet or interactive:
res = {'msg': '\r\nFAIL %s' % str(ex), 'self.cmdClass': 'AT'}
else:
res = "FAIL %s" % str(ex)
return res
def doListen(self, data):
r = data.split(' ')
port = r[0]
return DWSocketListener(port=port)
def doKill(self, data):
# r = data.split(':')
conn = self.server.connections.get(data, None)
if not conn:
raise Exception("Invalid connection: %s" % data)
res = "OK killing connection %s\r\n" % data
print res
conn.binding = None
conn.close()
del self.server.connections[r]
return res
def doJoin(self, data):
# r = data.split(':')
conn = self.server.connections.get(data, None)
print "Binding %s to %s" % (conn, data)
if not conn:
raise Exception("Invalid connection: %s" % data)
conn.binding = data
return conn
def dumpstacks(self, data):
import threading
import sys
import traceback
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" %
(id2name.get(threadId, ""), threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append(
'File: "%s", line %d, in %s' %
(filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
return "\r\n".join(code)
def doUSFdir(self, data):
r = []
if os.path.isdir(data):
dd = [os.path.join(data, d) for d in listdir(data)]
else:
dd = [data]
for path in dd:
rr = [os.path.sep]
rr += [path]
rr += [data]
s = os.stat(path)
rr += ["%d" % s.st_size]
rr += ["%d" % s.st_mtime]
rr += ["true" if os.path.isdir(path) else "false"] # readable
rr += ["false"] # writable
re = '|'.join(rr)
r.append(re)
return '\n'.join(r)
def doUSFdefaultdir(self, data):
raise Exception("Command not implemented")
def doUSFinfo(self, data):
raise Exception("Command not implemented")
def doUSFroots(self, data):
r = []
if os.name == 'posix':
r += ["/"]
else:
from win32com.client import Dispatch
fso = Dispatch('scripting.filesystemobject')
for i in fso.Drives:
r += [i]
return "\n".join(r)
def doUSFxdir(self, data):
import stuct
r = []
if os.path.isdir(data):
dd = [os.path.join(data, d) for d in listdir(data)]
else:
dd = [data]
for path in dd:
s = os.stat(data)
mt = time.localtime(s.st_mtime)
e = struct.pack(
">IBBBBBBBB",
s.st_size & 0xffffffff,
mt[0], # tm_year
mt[1], # tm_mon
mt[2], # tm_mday
mt[3], # tm_hour
mt[4], # tm_min
os.path.isdir(path),
os.access(path, W_OK),
len(data)
)
e += data
r += [e]
return '\n'.join(r)
def doSetDir(self, data, proto):
data = os.path.expanduser(data.lstrip().rstrip())
protoCmd = proto if proto != 'dw' else 'dw server'
if len(data) == 0:
raise Exception("Usage: %s setdir <path>" % protoCmd)
if not os.path.exists(data):
raise Exception("%s setdir: %s: No such path" % (protoCmd, data))
self.server.dirs[proto] = data
return "%s SetDir: %s" % (proto, data)
def doGetDir(self, data, proto):
data = ''
try:
data = self.server.dirs[proto]
except Exception as e:
return str(e)
return "%s GetDir: %s" % (proto, data)
def doListDir(self, data, proto):
d = self.server.dirs[proto]
msg = [
'==== %s Dir: %s ===' % (proto, d),
]
return self.doDir(d, msg=msg)
def doMcSetDir(self, data):
return self.doSetDir(data, 'mc')