-
Notifications
You must be signed in to change notification settings - Fork 22
/
GkStatus.cxx
2422 lines (2231 loc) · 73.2 KB
/
GkStatus.cxx
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
//////////////////////////////////////////////////////////////////
//
// GkStatus.cxx
//
// Copyright (c) 2000-2023, Jan Willamowius
//
// This work is published under the GNU Public License version 2 (GPLv2)
// see file COPYING for details.
// We also explicitly grant the right to link this code
// with the OpenH323/H323Plus and OpenSSL library.
//
//////////////////////////////////////////////////////////////////
#include "config.h"
#ifdef HAS_LIBSSH
#if _WIN32 || _WIN64
#pragma comment(lib, LIBSSH_LIB)
#endif
#include "libssh/libssh.h"
#include "libssh/server.h"
#endif
// disable warning about comparison with zero for Intel icpc
#ifdef __INTEL_COMPILER
#pragma warning(disable: 186)
#endif
#include <ptlib.h>
#include <ptlib/sockets.h>
#include <ptclib/telnet.h>
#include <h225.h>
#include <vector>
#include "gk_const.h"
#include "stl_supp.h"
#include "SoftPBX.h"
#include "Toolkit.h"
#include "RasSrv.h"
#include "Routing.h"
#include "gkacct.h"
#include "capctrl.h"
#include "rwlock.h"
#include "gk.h"
#include "h323util.h"
#include "GkStatus.h"
void ReloadHandler(); // avoid to include...
#ifdef UNIT_TEST
void ExitGK() { }; // mockup function for unit testing
#endif
static const char *authsec = "GkStatus::Auth";
static const char *filteringsec = "GkStatus::Filtering";
// a very lightweight implementation of telnet socket
class TelnetSocket : public ServerSocket {
#ifndef LARGE_FDSET
PCLASSINFO(TelnetSocket, ServerSocket)
#endif
public:
typedef PTelnetSocket::Options Options;
typedef PTelnetSocket::Command Command;
TelnetSocket();
// override from class TCPSocket
#ifdef LARGE_FDSET
virtual bool Accept(YaTCPSocket &);
#else
virtual PBoolean Accept(PSocket &);
#endif
virtual int ReadChar();
bool SendDo(BYTE);
bool SendDont(BYTE);
bool SendWill(BYTE);
bool SendWont(BYTE);
bool SendCommand(Command, BYTE);
bool NeedEcho() const { return m_needEcho; }
protected:
enum State {
StateNormal,
StateCarriageReturn,
StateIAC,
StateDo,
StateDont,
StateWill,
StateWont,
StateSubNegotiations,
StateEndNegotiations
};
// new virtual function
virtual void OnDo(BYTE);
virtual void OnDont(BYTE);
virtual void OnWill(BYTE);
virtual void OnWont(BYTE);
bool m_needEcho;
State m_state;
};
/** Class that manages a single status interface client connection.
*/
class StatusClient : public TelnetSocket, public USocket {
#ifndef LARGE_FDSET
PCLASSINFO(StatusClient, TelnetSocket)
#endif
public:
StatusClient(
/// unique session ID (instance number) for this client
int instanceNo
);
virtual ~StatusClient();
virtual void OnDo(BYTE code);
virtual bool ReadCommand(
/// command that has been read (if ReadCommand succeeded)
PString & cmd,
/// should the command be echoed (also NeedEcho() has to be true)
bool echo = true,
/// timeout (ms) for read operation
int readTimeout = 0
);
/** Send the message (string) to the status interface client,
if the output trace level is lesser or equal to the one set
for this client.
@return
true if the message has been sent (or ignored because of trace level).
*/
virtual bool WriteString(
/// string to be sent through the socket
const PString & msg,
/// output trace level assigned to the message
int level = MIN_STATUS_TRACE_LEVEL
);
/** @return
A string with connection information about this client.
*/
PString WhoAmI() const;
/** Check the client with all configured status authentication rules.
Ask for username/password, if required.
@return
true if the client has been granted access, false to reject the client.
*/
virtual bool Authenticate();
/** Executes the given command as a new Job (in a separate Worker thread).
*/
void OnCommand(
/// command to be executed
PString cmd
);
/** @return
Unique instance number (session identifier) for this client.
*/
int GetInstanceNo() const { return m_instanceNo; }
/** @return
Output trace level for this status client. The trace level
decides what kind of information is allowed to be broadcasted
to this client.
*/
int GetTraceLevel() const { return m_traceLevel; }
/// Set the new output trace level for this status interface client
void SetTraceLevel(
/// new output trace level to be set
int newLevel
)
{
m_traceLevel = newLevel;
}
/** @return
true if one or more commands from this status interface client
are executing by Worker threads.
*/
bool IsBusy() const
{
PWaitAndSignal lock(m_cmutex);
return m_numExecutingCommands > 0;
}
bool IsDone() const { return m_done; }
const PString & GetUser() const { return m_user; }
protected:
// override from class ServerSocket
virtual void Dispatch();
/// Handle the 'Debug' command (its many variants).
void DoDebug(
/// tokenized debug command
const PStringArray & args
);
/** Check a new client connection against the specified authentication
rule.
@return
true if the client satisfied the rule (has been authenticated successfully
with this rule).
*/
bool CheckAuthRule(
/// authentication rule to be used
const PString & rule
);
/** Authenticate this status interface client through all authentication
rules and return the final result.
@return
true if the use has been authenticated.
*/
virtual bool AuthenticateUser();
/** @return
The PBKDF2 digest for the password using the salt.
*/
PString PBKDF2_Digest(const PString & salt, const PString & password) const;
/** @return
The decrypted password associated with the specified login.
*/
PString GetPassword(const PString & userName) const;
/** Parse and execute the given command. The function is called
in a separate Worker thread (as a Job).
*/
void ExecCommand(
/// the command to be executed
PString cmd
);
/** Print error message to status port and trace
*/
void CommandError(const PString & msg);
// Adds regular expression filter
void AddFilter(
// filter vector
std::vector<PString> & regexFilters,
// Regex to be matched against messages
const PString & regex
);
/** Remove regular expression filter located
at the given index from the specified vector
*/
void RemoveFilter(
// filter vector
std::vector<PString> & regexFilters,
// Index of filter to be removed
unsigned int index
);
// Checks whether the given string is to be exclude
bool IsExcludeMessage(
// String to be check against the exclude regular expressions
const PString & msg
) const;
// Print a list of all filters in the specified vector
void PrintFilters(
// filter vector
std::vector<PString> & regexFilters
);
// Checks whether the given string is to be include
bool IsIncludeMessage(
// String to be check against the include regular expressions
const PString & msg
) const;
// Match the given string against filters held by the specified vector
bool MatchFilter(
// filter vector
const std::vector<PString> & regexFilters,
// String to be matched
const PString & msg
) const;
/// the most recent command
PString m_lastCmd;
/// command being currently entered (and not yet completed)
PString m_currentCmd;
/// GkStatus instance that created this client
GkStatus * m_gkStatus;
/// status interface user that is logged in
PString m_user;
/// for atomic access to the m_numExecutingCommands counter
PMutex m_cmutex;
/// number of commands being currently executed by Worker threads
int m_numExecutingCommands;
/// unique identifier for this client
int m_instanceNo;
/// output trace level for this client
int m_traceLevel;
/// should the client be terminated, eg. after finishing a one-shot execute
bool m_done;
/// last resort flag if this status client has already been deleted
bool m_deleted;
// vectors of regular expressions to be matched against Status messages
std::vector<PString> m_excludeFilterRegex;
std::vector<PString> m_includeFilterRegex;
// this flag indicates whether filtering is active or not
bool m_isFilteringActive;
bool m_handlePasswordRule; // password rule is handled differently in SSHStatusClient subclass
};
#ifdef HAS_LIBSSH
// SSH version of the status client
class SSHStatusClient : public StatusClient {
public:
SSHStatusClient(int instanceNo);
virtual ~SSHStatusClient();
#ifdef LARGE_FDSET
virtual bool Accept(YaTCPSocket &);
#else
virtual PBoolean Accept(PSocket &);
#endif
/** Check the client with all configured status authentication rules.
Ask for username/password, if required.
@return
true if the client has been granted access, false to reject the client.
*/
virtual bool Authenticate();
/** Authenticate this status interface client through all authentication
rules and return the final result.
@return
true if the use has been authenticated.
*/
virtual bool AuthenticateUser();
virtual bool ReadCommand(
/// command that has been read (if ReadCommand succeeded)
PString& cmd,
/// should the command be echoed (also NeedEcho() has to be true)
bool echo = true,
/// timeout (ms) for read operation
int readTimeout = 0
);
virtual bool WriteData(const BYTE * msg, int len);
protected:
ssh_bind m_sshbind;
ssh_session m_session;
ssh_message m_message;
ssh_channel m_chan;
};
SSHStatusClient::SSHStatusClient(int instanceNo) : StatusClient(instanceNo)
{
m_chan = 0;
m_needEcho = true;
m_handlePasswordRule = false; // modify behavior of password rule check in super class
m_sshbind = NULL;
m_session = NULL;
m_message = NULL;
}
SSHStatusClient::~SSHStatusClient()
{
ssh_disconnect(m_session);
ssh_free(m_session);
if (m_sshbind) {
ssh_bind_set_fd(m_sshbind, -1); // make sure StatusListener is not closed
ssh_bind_free(m_sshbind);
}
GkStatus::Instance()->StatusClientDeleted();
}
#ifdef LARGE_FDSET
bool SSHStatusClient::Accept(YaTCPSocket & socket)
#else
PBoolean SSHStatusClient::Accept(PSocket & socket)
#endif
{
m_sshbind = ssh_bind_new();
m_session = ssh_new();
//ssh_bind_options_set(m_sshbind, SSH_BIND_OPTIONS_LOG_VERBOSITY_STR, "3"); // only enable for debugging
// disable compression, doesn't seem to work (bug in libssh)
ssh_options_set(m_session, SSH_OPTIONS_COMPRESSION_C_S, "none");
ssh_options_set(m_session, SSH_OPTIONS_COMPRESSION_S_C, "none");
bool keyAvailable = false;
PString dsakey = GkConfig()->GetString(authsec, "DSAKey", "/etc/ssh/ssh_host_dsa_key");
if (PFile::Exists(dsakey) && PFile::Access(dsakey, PFile::ReadOnly)) {
keyAvailable = true;
ssh_bind_options_set(m_sshbind, SSH_BIND_OPTIONS_DSAKEY, (const char *)dsakey);
PTRACE(3, "Setting DSA key to " << dsakey);
}
PString rsakey = GkConfig()->GetString(authsec, "RSAKey", "/etc/ssh/ssh_host_rsa_key");
if (PFile::Exists(rsakey) && PFile::Access(rsakey, PFile::ReadOnly)) {
keyAvailable = true;
ssh_bind_options_set(m_sshbind, SSH_BIND_OPTIONS_RSAKEY, (const char *)rsakey);
PTRACE(3, "Setting RSA key to " << rsakey);
}
if (!keyAvailable) {
PTRACE(1, "No DSA or RSA key file found");
SNMP_TRAP(7, SNMPError, Network, "No SSH keys");
socket.Close();
return false;
}
ssh_bind_set_fd(m_sshbind, socket.GetHandle());
if (ssh_bind_accept(m_sshbind, m_session) == SSH_ERROR) {
PTRACE(1, "ssh_bind_accept() failed: " << ssh_get_error(m_sshbind));
SNMP_TRAP(7, SNMPError, Network, "SSH bind failed");
return false;
}
if (ssh_handle_key_exchange(m_session)) {
PTRACE(1, "ssh_handle_key_exchange failed: " << ssh_get_error(m_session));
SNMP_TRAP(7, SNMPError, Network, "SSH key exchange failed");
return false;
}
// set handle for SocketsReader
os_handle = ssh_get_fd(m_session);
#ifdef LARGE_FDSET
socklen_t addr_len = sizeof(peeraddr);
(void)getpeername(os_handle, ((struct sockaddr *)&peeraddr), &addr_len); // OK to fail on private IPs etc.
#endif
Address raddr, laddr;
WORD rport = 0, lport = 0;
GetPeerAddress(raddr, rport);
UnmapIPv4Address(raddr);
GetLocalAddress(laddr, lport);
UnmapIPv4Address(laddr);
SetName(AsString(raddr, rport) + "=>" + AsString(laddr, lport));
return true;
}
bool SSHStatusClient::Authenticate()
{
// check the auth rules if the ssh client is denied by explicit or regex rule
bool ipcheck = StatusClient::Authenticate();
if (!ipcheck) {
PTRACE(1, "ssh client denied by IP rules");
return false;
}
const time_t now = time(NULL);
const int loginTimeout = GkConfig()->GetInteger(authsec, "LoginTimeout", 120);
bool auth = false;
const int MAX_RETRIES = 3;
int retries = 0;
do {
m_message = ssh_message_get(m_session);
if (!m_message) {
PTRACE(1, "ssh read error: " << ssh_get_error(m_session));
SNMP_TRAP(7, SNMPError, Network, PString("SSH read error: ") + ssh_get_error(m_session));
break;
}
switch(ssh_message_type(m_message)) {
case SSH_REQUEST_AUTH:
switch(ssh_message_subtype(m_message)) {
case SSH_AUTH_METHOD_PASSWORD:
retries++;
if (AuthenticateUser()) {
auth = true;
ssh_message_auth_reply_success(m_message, 0);
break;
}
// fall through intended: not authenticated, send default message
case SSH_AUTH_METHOD_NONE:
default:
ssh_message_auth_set_methods(m_message, SSH_AUTH_METHOD_PASSWORD);
ssh_message_reply_default(m_message);
break;
}
break;
default:
ssh_message_reply_default(m_message);
}
ssh_message_free(m_message);
} while (!auth && (retries < MAX_RETRIES) && ((time(NULL) - now) < loginTimeout));
if (!auth) {
return false;
}
// open channel
do {
m_message = ssh_message_get(m_session);
if (m_message) {
switch(ssh_message_type(m_message)) {
case SSH_REQUEST_CHANNEL_OPEN:
if (ssh_message_subtype(m_message) == SSH_CHANNEL_SESSION) {
m_chan = ssh_message_channel_request_open_reply_accept(m_message);
break;
}
// fall through intended
default:
ssh_message_reply_default(m_message);
}
ssh_message_free(m_message);
}
} while(m_message && !m_chan);
if (!m_chan) {
PTRACE(1, "Error establishing SSH channel: " << ssh_get_error(m_session));
SNMP_TRAP(7, SNMPError, Network, PString("SSH error: ") + ssh_get_error(m_session));
return false;
}
// handle requests
bool shell = false;
do {
m_message = ssh_message_get(m_session);
if (m_message) {
switch(ssh_message_type(m_message)) {
case SSH_REQUEST_CHANNEL:
switch (ssh_message_subtype(m_message)) {
case SSH_CHANNEL_REQUEST_UNKNOWN:
// eg. Putty X11 forwarding, deny to avoid hang
ssh_message_reply_default(m_message); // deny
break;
case SSH_CHANNEL_REQUEST_PTY:
ssh_message_channel_request_reply_success(m_message);
break;
case SSH_CHANNEL_REQUEST_EXEC:
{
shell = true;
const char * cmd = ssh_message_channel_request_command(m_message);
OnCommand(cmd);
Flush();
ssh_message_channel_request_reply_success(m_message);
m_done = true;
}
break;
case SSH_CHANNEL_REQUEST_SHELL:
shell = true;
ssh_message_channel_request_reply_success(m_message);
break;
case SSH_CHANNEL_X11:
ssh_message_reply_default(m_message); // deny X11 forwarding
break;
default:
PTRACE(3, "Unhandled SSH_REQUEST_CHANNEL message subtype " << ssh_message_subtype(m_message));
break;
}
break;
default:
PTRACE(3, "Unhandled SSH message " << ssh_message_type(m_message) << " subtype " << ssh_message_subtype(m_message));
// ignore the rest for now
}
ssh_message_free(m_message);
}
} while(m_message && !shell);
if (!m_message)
return false;
return true;
}
bool SSHStatusClient::AuthenticateUser()
{
const int delay = GkConfig()->GetInteger(authsec, "DelayReject", 0);
PString login = ssh_message_auth_user(m_message);
PString password = ssh_message_auth_password(m_message);
// PTRACE(1, "User " << login << " wants to authenticate with password " << password);
#ifdef P_SSL
PString rawPassword = GkConfig()->GetString(authsec, login, "");
if (rawPassword.Left(7) == "PBKDF2:") {
const PINDEX dashPos = rawPassword.Find("-");
const PString salt = rawPassword.Mid(7, dashPos - 7);
const PString digest = rawPassword.Mid(dashPos + 1);
if (PBKDF2_Digest(salt, password) == digest) {
m_user = login;
return true;
} else {
PTRACE(3, "STATUS\tPassword digest mismatch for user " << login);
}
}
else
#endif
{
const PString storedPassword = GetPassword(login);
if (storedPassword.IsEmpty())
PTRACE(5, "STATUS\tCould not find password in the config for user " << login);
else if (!password && password == storedPassword) {
m_user = login;
return true;
} else {
PTRACE(5, "STATUS\tPassword mismatch for user " << login);
}
}
PThread::Sleep(delay * 1000);
return false;
}
bool SSHStatusClient::ReadCommand(PString& cmd, bool echo, int readTimeout)
{
char buf[2048];
int i = 0;
do {
i = ssh_channel_read(m_chan, buf, sizeof(buf), 0);
for (int c = 0; c < i; c++) {
char ch = buf[c];
switch (ch)
{
case '\r':
case '\n':
cmd = m_currentCmd;
m_lastCmd = cmd;
m_currentCmd = PString();
if (echo && NeedEcho())
ssh_channel_write(m_chan, (void *)"\r\n", 2);
return true;
case '\b':
case 0x7f: // backspace with ssh
if (m_currentCmd.GetLength()) {
m_currentCmd = m_currentCmd.Left(m_currentCmd.GetLength() - 1);
if (echo && NeedEcho()) {
ssh_channel_write(m_chan, (void *)"\b \b", 3);
}
}
break;
case '\x03': // Ctrl-C
case '\x04': // Ctrl-D
cmd = "exit";
m_lastCmd = cmd;
m_currentCmd = PString::Empty();
return true;
default:
char byte = char(ch);
m_currentCmd += byte;
cmd = m_currentCmd.Right(3);
// Note: this only works if the telnet client doesn't buffer characters
// Windows does, my Linux telnet doesn't
if (cmd == "\x1b\x5b\x41" || cmd == "\x5b\x41") { // Up Arrow
if (echo && NeedEcho()) {
for(PINDEX i = 0; i < m_currentCmd.GetLength() - 3; i ++)
Write("\b", 1);
WriteString(m_lastCmd);
}
m_currentCmd = m_lastCmd;
} else if (cmd.Find('\x1b') == P_MAX_INDEX)
if (echo && NeedEcho())
ssh_channel_write(m_chan, &buf[c], 1);
break;
}
}
} while (i > 0);
return true;
}
bool SSHStatusClient::WriteData(const BYTE * msg, int len)
{
if (!m_chan)
return false;
int written = ssh_channel_write(m_chan, msg, len);
ssh_blocking_flush(m_session, 5000); // wait 5 sec. max
return (written == len);
}
#endif // HAS_LIBSSH
TelnetSocket::TelnetSocket() : m_needEcho(false), m_state(StateNormal)
{
}
#ifdef LARGE_FDSET
bool TelnetSocket::Accept(YaTCPSocket & socket)
#else
PBoolean TelnetSocket::Accept(PSocket & socket)
#endif
{
if (!TCPSocket::Accept(socket))
return false;
SendDo(PTelnetSocket::SuppressGoAhead);
SendWill(PTelnetSocket::StatusOption);
SendDont(PTelnetSocket::EchoOption);
#ifndef LARGE_FDSET
Address raddr, laddr;
WORD rport = 0, lport = 0;
GetPeerAddress(raddr, rport);
UnmapIPv4Address(raddr);
GetLocalAddress(laddr, lport);
UnmapIPv4Address(laddr);
SetName(AsString(raddr, rport) + "=>" + AsString(laddr, lport));
SetReadTimeout(0);
#else
// name already be set
#endif
SetOption(SO_SNDBUF, GkConfig()->GetInteger("StatusSendBufferSize", 16384));
SetOption(SO_RCVBUF, GkConfig()->GetInteger("StatusReceiveBufferSize", 16384));
return true;
}
int TelnetSocket::ReadChar()
{
bool hasData = false;
BYTE currentByte = 0;
while (!hasData) {
if (!TCPSocket::Read(¤tByte, 1)) {
const PSocket::Errors err = GetErrorCode(PSocket::LastReadError);
if ((err != PSocket::Timeout) && (err != PSocket::NoError)) {
PTRACE(3, "TELNET\t" << GetName() << " closed the connection ("
<< GetErrorCode(PSocket::LastReadError) << '/'
<< GetErrorNumber(PSocket::LastReadError) << ": "
<< GetErrorText(PSocket::LastReadError) << ')'
);
Close();
}
break;
}
switch (m_state)
{
case StateCarriageReturn:
m_state = StateNormal;
if (currentByte == '\0' || currentByte == '\n')
break; // Ignore \0 \n after CR
// else fall through intended for normal processing
case StateNormal:
if (currentByte == PTelnetSocket::IAC)
m_state = StateIAC;
else {
if (currentByte == '\r')
m_state = StateCarriageReturn;
hasData = true;
}
break;
case StateIAC:
switch (currentByte)
{
case PTelnetSocket::IAC:
hasData = true;
m_state = StateNormal;
break;
case PTelnetSocket::DO:
m_state = StateDo;
break;
case PTelnetSocket::DONT:
m_state = StateDont;
break;
case PTelnetSocket::WILL:
m_state = StateWill;
break;
case PTelnetSocket::WONT:
m_state = StateWont;
break;
default:
m_state = StateNormal;
break;
}
break;
case StateDo:
OnDo(currentByte);
m_state = StateNormal;
break;
case StateDont:
OnDont(currentByte);
m_state = StateNormal;
break;
case StateWill:
OnWill(currentByte);
m_state = StateNormal;
break;
case StateWont:
OnWont(currentByte);
m_state = StateNormal;
break;
default:
PTRACE(1, "TELNET\t" << GetName() << " telnet socket entered unrecognized state " << m_state);
m_state = StateNormal;
break;
}
}
return hasData ? currentByte : -1;
}
bool TelnetSocket::SendDo(BYTE code)
{
return SendCommand(PTelnetSocket::DO, code);
}
bool TelnetSocket::SendDont(BYTE code)
{
return SendCommand(PTelnetSocket::DONT, code);
}
bool TelnetSocket::SendWill(BYTE code)
{
return SendCommand(PTelnetSocket::WILL, code);
}
bool TelnetSocket::SendWont(BYTE code)
{
return SendCommand(PTelnetSocket::WONT, code);
}
bool TelnetSocket::SendCommand(Command cmd, BYTE opt)
{
int length = 2;
BYTE buffer[3];
buffer[0] = PTelnetSocket::IAC;
buffer[1] = (BYTE)cmd;
switch (cmd)
{
case PTelnetSocket::DO:
case PTelnetSocket::DONT:
case PTelnetSocket::WILL:
case PTelnetSocket::WONT:
buffer[2] = opt;
length = 3;
break;
default:
// do not support now
break;
}
return Write(buffer, length);
}
void TelnetSocket::OnDo(BYTE code)
{
PTRACE(6, "TELNET\t" << GetName() << " got DO " << int(code));
}
void TelnetSocket::OnDont(BYTE code)
{
PTRACE(6, "TELNET\t" << GetName() << " got DONT " << int(code));
}
void TelnetSocket::OnWill(BYTE code)
{
PTRACE(6, "TELNET\t" << GetName() << " got WILL " << int(code));
}
void TelnetSocket::OnWont(BYTE code)
{
PTRACE(6, "TELNET\t" << GetName() << " got WONT " << int(code));
if (code == PTelnetSocket::EchoOption) // Windows client?
m_needEcho = true;
}
namespace {
PString PrintGkVersion()
{
return PString("Version:\r\n") + Toolkit::GKVersion() +
SoftPBX::Uptime() + "\r\n;\r\n";
}
}
// class GkStatus
GkStatus::GkStatus() : Singleton<GkStatus>("GkStatus"), SocketsReader(500)
{
SetName("GkStatus");
m_statusClients = 0;
LoadConfig();
Execute();
}
GkStatus::~GkStatus()
{
ReadLock lock(m_listmutex);
for (iterator i = m_sockets.begin(); i != m_sockets.end(); ++i) {
(*i)->Close();
}
}
void GkStatus::LoadConfig()
{
m_maxStatusClients = GkConfig()->GetInteger("MaxStatusClients", 20);
m_eventBacklogLimit = GkConfig()->GetInteger("StatusEventBacklog", 0);
PString eventBacklogRegex = GkConfig()->GetString("StatusEventBacklogRegex", ".");
m_eventBacklogRegex = PRegularExpression(eventBacklogRegex, PRegularExpression::Extended);
if (m_eventBacklogRegex.GetErrorCode() != PRegularExpression::NoError) {
PTRACE(2, "Error '"<< m_eventBacklogRegex.GetErrorText() <<"' compiling StatusEventBacklogRegex: " << eventBacklogRegex);
m_eventBacklogRegex = PRegularExpression(".", PRegularExpression::Extended);
}
}
void GkStatus::AuthenticateClient(StatusClient * newClient)
{
if ((m_statusClients++ < m_maxStatusClients) && (newClient->Authenticate())) {
newClient->SetTraceLevel(GkConfig()->GetInteger("StatusTraceLevel", MAX_STATUS_TRACE_LEVEL));
PTRACE(1, "STATUS\tNew client authenticated successfully: " << newClient->WhoAmI()
<< ", login: " << newClient->GetUser());
// the welcome messages
newClient->WriteString(PrintGkVersion());
newClient->Flush();
AddSocket(newClient);
if (newClient->IsDone()) {
while (newClient->IsBusy()) {
PThread::Sleep(100); // give forked threads time to finish
}
newClient->Flush();
newClient->Close();
}
} else {
PTRACE(3, "STATUS\tNew client rejected: " << newClient->WhoAmI() << ", login: " << newClient->GetUser());
newClient->WriteString("\r\nAccess forbidden!\r\n");
// newClient->Flush(); // dont' flush when access is denied to avoid blocking
delete newClient;
}
}
/** Functor class used to send the message to the specified client.
*/
class ClientSignalStatus
{
public:
ClientSignalStatus(
/// message to be sent
const PString & msg,
/// output trace level assigned to the message
int level
) : m_message(msg), m_traceLevel(level) { }
/** Actual function call operator that sends the message.
*/
void operator()(
/// socket to send the message through
IPSocket* clientSocket
) const
{
StatusClient* client = static_cast<StatusClient*>(clientSocket);
if (m_traceLevel <= client->GetTraceLevel())
client->WriteString(m_message);
}
private:
/// message to be sent
const PString & m_message;
/// output trace level assigned to the message
int m_traceLevel;
};
void GkStatus::SignalStatus(
/// message string to be broadcasted
const PString & msg,
/// trace level at which the message should be broadcasted
int level
)
{
ReadLock lock(m_listmutex);
// signal event to all connected clients
ForEachInContainer(m_sockets, ClientSignalStatus(msg, level));
// save event in backlog
PWaitAndSignal eventLock(m_eventBacklogMutex);
if (m_eventBacklogLimit > 0) {
PString event = msg.Trim();
event.Replace("\r\n", "");
if (event != ";") {
PINDEX pos = 0;
if (m_eventBacklogRegex.Execute(event, pos)) {
event = Toolkit::Instance()->AsString(PTime(), "MySQL") + ": " + event;
m_eventBacklog.push_back(event);
if (m_eventBacklog.size() > m_eventBacklogLimit) {
m_eventBacklog.pop_front();
}
}
}
}
}