forked from Al-Muhandis/ShellRemoteBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellthread.pas
More file actions
283 lines (253 loc) · 7.58 KB
/
Copy pathshellthread.pas
File metadata and controls
283 lines (253 loc) · 7.58 KB
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
unit shellthread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, tgtypes, tgsendertypes, process, eventlog, tgshbot
{$IFDEF MSWINDOWS}, Windows{$ENDIF}
;
type
{ TShellThread }
TShellThread=class(TThread)
private
FLogger: TEventLog;
FBot: TTgShBot;
FProc: TProcess;
FTerminated: Boolean;
FLPTimeout: Integer;
procedure BotReceiveMessage({%H-}ASender: TObject; AMessage: TTelegramMessageObj);
{ Read output from shell terminal by command }
procedure BotReceiveReadCommand({%H-}ASender: TObject; const {%H-}ACommand: String;
{%H-}AMessage: TTelegramMessageObj);
{$IFDEF UNIX}
procedure BotReceiveSIGCommand({%H-}ASender: TObject; const {%H-}ACommand: String;
{%H-}AMessage: TTelegramMessageObj);
{ procedure emulate SIGINT (Ctrl+C) }
procedure BotReceiveSIGINTCommand({%H-}ASender: TObject; const {%H-}ACommand: String;
{%H-}AMessage: TTelegramMessageObj);
procedure BotReceiveSIGKILLCommand({%H-}ASender: TObject; const {%H-}ACommand: String;
{%H-}AMessage: TTelegramMessageObj);
{ procedure emulate SIGQUIT (Ctrl+\) }
procedure BotReceiveSIGQUITCommand({%H-}ASender: TObject; const {%H-}ACommand: String;
{%H-}AMessage: TTelegramMessageObj);
procedure BotReceiveSIGTERMCommand({%H-}ASender: TObject; const {%H-}ACommand: String;
{%H-}AMessage: TTelegramMessageObj);
{$ENDIF}
function CommandStart: Boolean;
function CheckIsAdmin: Boolean;
function GetLogger: TEventLog;
procedure OutputStd(const NoOutput: String = '');
procedure SendToShellTerminal(const InputString: String);
{$IFDEF UNIX}procedure SendSIG(SigNumber: Byte);{$ENDIF}
procedure SetLogger(AValue: TEventLog);
property Logger: TEventLog read GetLogger write SetLogger;
public
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
implementation
uses
configuration{$IFDEF UNIX}, strutils {$ENDIF}
;
{$IFDEF UNIX}
const
{ POSIX signals }
{%H-}SIGABRT = 6;
{%H-}SIGALRM = 14;
{%H-}SIGHUP = 1;
SIGINT = 2;
SIGKILL = 9;
SIGQUIT = 3;
SIGTERM = 15;
{%H-}SIGTRAP = 5;
{$ENDIF}
{ TShellThread }
procedure TShellThread.SetLogger(AValue: TEventLog);
begin
if FLogger=AValue then Exit;
FLogger.Free;
FLogger:=AValue;
end;
function TShellThread.GetLogger: TEventLog;
begin
if not Assigned(FLogger) then
begin
FLogger:=TEventLog.Create(nil);
FLogger.Identification:='Shell thread';
end;
Result:=FLogger;
end;
procedure TShellThread.BotReceiveMessage(ASender: TObject;
AMessage: TTelegramMessageObj);
var
InputString: String;
begin
if not CommandStart then
Exit;
InputString:=AMessage.Text;
if InputString=EmptyStr then
Exit;
InputString+=LineEnding;
SendToShellTerminal(InputString);
end;
procedure TShellThread.BotReceiveReadCommand(ASender: TObject;
const ACommand: String; AMessage: TTelegramMessageObj);
begin
if CommandStart then
OutputStd('No new messages in the terminal');
end;
{$IFDEF UNIX}
procedure TShellThread.BotReceiveSIGCommand(ASender: TObject;
const ACommand: String; AMessage: TTelegramMessageObj);
var
i: LongInt;
begin
if not CommandStart then
Exit;
if TryStrToInt(ExtractDelimited(2, AMessage.Text, [' ']), i) then
if i<=High(Byte) then
SendSIG(i)
else
FBot.sendMessageSafe('SIG number limit by 255!')
else
FBot.sendMessageSafe('Please, specify SIG portable number. For example:'+LineEnding+
'```sh'+LineEnding+'/sig 3```'+LineEnding+'where `3` - is SIGQUIT', pmMarkdown);
end;
procedure TShellThread.BotReceiveSIGINTCommand(ASender: TObject;
const ACommand: String; AMessage: TTelegramMessageObj);
begin
if not CommandStart then
Exit;
SendSIG(SIGINT);
end;
procedure TShellThread.BotReceiveSIGKILLCommand(ASender: TObject;
const ACommand: String; AMessage: TTelegramMessageObj);
begin
if not CommandStart then
Exit;
SendSIG(SIGKILL);
end;
procedure TShellThread.BotReceiveSIGQUITCommand(ASender: TObject;
const ACommand: String; AMessage: TTelegramMessageObj);
begin
if not CommandStart then
Exit;
SendSIG(SIGQUIT);
end;
procedure TShellThread.BotReceiveSIGTERMCommand(ASender: TObject;
const ACommand: String; AMessage: TTelegramMessageObj);
begin
if not CommandStart then
Exit;
SendSIG(SIGTERM);
end;
{$ENDIF}
function TShellThread.CommandStart: Boolean;
begin
FBot.UpdateProcessed:=True; // There is no point in further processing
Result:=CheckIsAdmin and FProc.Running;
end;
function TShellThread.CheckIsAdmin: Boolean;
begin
Result:=not FBot.CurrentIsSimpleUser;
if not Result then
FBot.sendMessage('You cannot access to this bot!')
else
Result:=True;
end;
procedure TShellThread.OutputStd(const NoOutput: String);
var
CharBuffer: array [0..511] of char;
ReadCount: integer;
OutputString: String;
const
SleepForOut = 100; // Pause to wait for output
begin
Sleep(SleepForOut);
OutputString:=EmptyStr;
while FProc.Output.NumBytesAvailable > 0 do
begin
ReadCount := FProc.Output.NumBytesAvailable;
if ReadCount>Length(CharBuffer) then
ReadCount:=Length(CharBuffer);
FProc.Output.Read(CharBuffer{%H-}, ReadCount);
OutputString+=Copy(CharBuffer, 0, ReadCount);
// Write(StdOut, OutputString); // You can uncomment for debug
end;
if (OutputString=EmptyStr) and (NoOutput<>EmptyStr) then
FBot.sendMessageSafe(NoOutput)
else
if not FBot.sendMessageCode(OutputString) then
Logger.Error('['+ClassName+'.OutpuStd] Cant send message to bot!');
// read stderr and write to our stderr ... crashing :((
{ while FProc.Stderr.NumBytesAvailable > 0 do
begin
ReadCount := Min(512, FProc.Stderr.NumBytesAvailable);
FProc.Stderr.Read(CharBuffer, ReadCount);
FBot.sendMessage(Copy(CharBuffer, 0, ReadCount));
// Write(StdErr, Copy(CharBuffer, 0, ReadCount));
end; }
end;
procedure TShellThread.SendToShellTerminal(const InputString: String);
begin
OutputStd;
FProc.Input.Write(InputString[1], Length(InputString));
OutputStd;
end;
{$IFDEF UNIX}
procedure TShellThread.SendSIG(SigNumber: Byte);
var
Sig: String;
begin
Sig:=chr(SigNumber){+LineEnding};
SendToShellTerminal(Sig);
end;
{$ENDIF}
constructor TShellThread.Create;
begin
inherited Create(True);
FreeOnTerminate:=False;
TelegramAPI_URL:=Cnfg.APIEndPoint; // For Russian specific case
FBot:=TTgShBot.Create(Cnfg.BotTooken);
FBot.Logger:=Logger;
if FBot.Token=EmptyStr then
begin
Logger.Error('Please, specify bot token in telegram.ini!');
Exit;
end;
FBot.HTTPProxyHost:=Cnfg.HTTPProxyHost;
FBot.HTTPProxyPort:=Cnfg.HTTPProxyPort;
// FBot.LogDebug:=True;
FBot.OnReceiveMessage:=@BotReceiveMessage;
{ Read output of shell terminal called by user via /read command }
FBot.CommandHandlers['/read']:=@BotReceiveReadCommand;{$IFDEF UNIX}
FBot.CommandHandlers['/sig']:=@BotReceiveSigCommand;
FBot.CommandHandlers['/sigint']:=@BotReceiveSIGINTCommand;
FBot.CommandHandlers['/sigkill']:=@BotReceiveSIGKILLCommand;
FBot.CommandHandlers['/sigquit']:=@BotReceiveSIGQUITCommand;
FBot.CommandHandlers['/sigterm']:=@BotReceiveSIGTERMCommand;
{$ENDIF}{$IFDEF MSWINDOWS}
SetConsoleOutputCP(CP_UTF8);{$ENDIF}
FProc:=TProcess.Create(nil);
FProc.Options := [poUsePipes, poStderrToOutPut, poNoConsole];
FProc.Executable:={$IFDEF MSWINDOWS}'cmd'{$ELSE}'sh'{$ENDIF};
FProc.Execute;
FTerminated:=False;
FLPTimeout:=Cnfg.APITimeout;
end;
destructor TShellThread.Destroy;
begin
FreeAndNil(FProc);
FreeAndNil(FBot);
inherited Destroy;
end;
procedure TShellThread.Execute;
begin
OutputStd;
while not Terminated do
begin
FBot.getUpdatesEx(0, FLPTimeout);
OutputStd;
end;
end;
end.