forked from dyninc/OpenBFDD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommandProcessor.cpp
executable file
·2134 lines (1868 loc) · 57 KB
/
CommandProcessor.cpp
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
/**************************************************************
* Copyright (c) 2010-2013, Dynamic Network Services, Inc.
* Jake Montgomery ([email protected]) & Tom Daly ([email protected])
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
#include "common.h"
#include "CommandProcessor.h"
#include "utils.h"
#include "Beacon.h"
#include <errno.h>
#include <sys/socket.h>
#include <string.h>
#include <stdarg.h>
using namespace std;
class CommandProcessorImp : public CommandProcessor
{
protected:
Beacon *m_beacon; // never null, never changes
//
// These are only accessed from thread.
//
Socket m_listenSocket;
Socket m_replySocket;
RecvMsg m_inCommand;
vector<char> m_inReplyBuffer; // only use messageReply and friends.
string m_inCommandLogStr;
//
// These are protected by m_mainLock
//
QuickLock m_mainLock;
SockAddr m_address; /// address and port to listen on.
pthread_t m_listenThread;
volatile bool m_isThreadRunning;
volatile bool m_threadInitComplete; // Set to true after m_isThreadRunning set true the first time
volatile bool m_threadStartupSuccess; //only valid after m_isThreadRunning has been set to true.
volatile bool m_stopListeningRequested;
WaitCondition m_threadStartCondition;
public:
CommandProcessorImp(Beacon &beacon) : CommandProcessor(beacon),
m_beacon(&beacon),
m_listenSocket(),
m_replySocket(),
m_inCommand(MaxCommandSize, 0),
m_inReplyBuffer(MaxReplyLineSize + 1),
m_mainLock(true),
m_isThreadRunning(false),
m_threadInitComplete(false),
m_threadStartupSuccess(true),
m_stopListeningRequested(false)
{
m_inCommandLogStr.reserve(MaxCommandSize); // could end up needing more, but this is a good start.
}
virtual ~CommandProcessorImp()
{
StopListening();
}
/**
* See CommandProcessor::BeginListening().
*/
virtual bool BeginListening(const SockAddr &addr)
{
AutoQuickLock lock(m_mainLock, true);
pthread_attr_t attr;
if (m_isThreadRunning)
{
LogVerifyFalse("Command Processer already running.");
return true;
}
if (pthread_attr_init(&attr))
return false;
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // we will handle synchronizing
m_address = addr;
m_isThreadRunning = false;
m_threadInitComplete = false;
m_threadStartupSuccess = true;
m_stopListeningRequested = false;
if (pthread_create(&m_listenThread, NULL, doListenThreadCallback, this))
return false;
// Wait for listening, or error.
while (true)
{
lock.LockWait(m_threadStartCondition);
if (!m_threadInitComplete)
continue; // spurious signal.
// We can now allow the worker thread to shutdown if it wants to.
if (!m_threadStartupSuccess)
{
lock.UnLock();
StopListening(); // Ensure that thread is finished before we return...in case we try again immediately.
return false;
}
break;
}
return true;
}
/**
* See CommandProcessor::StopListening().
*/
virtual void StopListening()
{
AutoQuickLock lock(m_mainLock, true);
if (!m_isThreadRunning)
return;
m_stopListeningRequested = true;
// We need to wait for it to
while (m_isThreadRunning)
lock.LockWait(m_threadStartCondition);
}
protected:
static void* doListenThreadCallback(void *arg)
{
reinterpret_cast<CommandProcessorImp *>(arg)->doListenThread();
return NULL;
}
void doListenThread()
{
bool initSuccess;
AutoQuickLock lock(m_mainLock, true);
gLog.Optional(Log::AppDetail, "Listen Thread Started");
initSuccess = initListening();
m_threadStartupSuccess = initSuccess;
m_isThreadRunning = true;
m_threadInitComplete = true;
// Signal setup completed (success, or failure).
lock.SignalAndUnlock(m_threadStartCondition);
// do Stuff
if (initSuccess)
{
while (processMessage())
{}
}
lock.Lock();
m_isThreadRunning = false;
lock.SignalAndUnlock(m_threadStartCondition);
gLog.Optional(Log::AppDetail, "Listen Thread Shutdown");
return;
}
/**
*
* Call only from listen thread.
* Call with m_mainLock held.
*
* @return bool - false if listening setup failed.
*/
bool initListening()
{
// Do this so low memory will not cause distorted messages
if (!UtilsInitThread())
{
gLog.Message(Log::Error, "Failed to initialize listen thread. TLS memory failure.");
return false;
}
m_listenSocket.SetLogName(FormatShortStr("Control listen socket on %s", m_address.ToString()));
if (!m_listenSocket.OpenTCP(m_address.Type()))
return false;
if (!m_listenSocket.SetBlocking(false))
return false;
if (!m_listenSocket.SetReusePort(true))
return false;
if (!m_listenSocket.Bind(m_address))
return false;
if (!m_listenSocket.Listen(3))
return false;
gLog.Optional(Log::App, "Listening for commands on %s", m_address.ToString());
return true;
}
struct Result
{
enum Type
{
Success,
Timeout,
Error,
StopListening // requested shutdown
};
};
/**
* Waits for the socket to have read data.
*
* @param fd
* @param pollTimeInMs - poll time for m_stopListeningRequested in milliseconds.
* @param maxWaitInMs - The maximum time to wait in milliseconds. May be rounded
* to the nearest pollTimeInMs.
*
* @return Result - Success, GaveUp, Error or StopListening
*/
Result::Type waitForSocketRead(int fd, uint32_t pollTimeInMs, uint32_t maxWaitInMs = 0)
{
int result;
int waits = 0;
fd_set waitOn;
TimeSpec maxTime;
if (maxWaitInMs)
maxTime = TimeSpec::MonoNow() + TimeSpec(TimeSpec::Millisec, maxWaitInMs);
while (!isStopListeningRequested())
{
if (maxWaitInMs)
{
if (TimeSpec::MonoNow() > maxTime)
{
gLog.Optional(Log::Command, "Waiting timed out after %d polls.", waits);
return Result::Timeout;
}
}
struct timeval waitTime;
// setup fd_set and wait time
waitTime.tv_sec = pollTimeInMs / 1000;
waitTime.tv_usec = (pollTimeInMs % 1000) * 1000;
FD_ZERO(&waitOn);
FD_SET(fd, &waitOn);
result = select(fd + 1, &waitOn, NULL, NULL, &waitTime);
if (result < 0)
{
if (errno != EINTR)
{
gLog.ErrnoError(errno, "socket wait: ");
return Result::Error;
}
}
else if (result > 0)
{
LogAssert(result == 1);
return Result::Success;
}
waits++;
//gLog.Optional(Log::Debug, "Still waiting %d\n", waits);
}
return Result::StopListening;
}
/**
* Helper for processMessage.
*
* @param me
*/
static void closeSyncReplySocket(CommandProcessorImp *me)
{
if (me)
me->m_replySocket.Close();
}
/**
*
* Process the next command.
* This can return false because m_stopListeningRequested was set to true, or
* because the "Stop" command was executed, or due to a fatal error that will
* not allow listening to continue.
*
* Call only from listen thread.
*
* @throw - yes
*
* @return bool - false if listening should stop.
*/
bool processMessage()
{
Result::Type waitResult;
Socket connectedSocket;
RaiiNullBase<CommandProcessorImp, closeSyncReplySocket> syncConnectedSocket(this);
// Since we have a non-blocking socket, we must wait for a connection
waitResult = waitForSocketRead(m_listenSocket, 320);
if (waitResult != Result::Success)
return false;
// accept a connection
if (!m_listenSocket.Accept(connectedSocket))
{
// We do not quit on error?
return true;
}
connectedSocket.SetLogName(FormatShortStr("Command connection to %s", connectedSocket.GetAddress().ToString()));
m_replySocket = connectedSocket; // note connectedSocket still 'owns' the socket.
m_replySocket.SetLogName(connectedSocket.LogName());
// Got a connection for the command. Now wait for a command. Since we are
// non-blocking, we use select again.
waitResult = waitForSocketRead(connectedSocket, 200, 10000);
if (waitResult != Result::Success)
return true; // failure here does not cause full shutdown.
// Should be ready with a command
while (true)
{
if (isStopListeningRequested())
return false;
if (!m_inCommand.DoRecv(connectedSocket, MSG_DONTWAIT))
{
// Errors
if (m_inCommand.GetLastError() == EAGAIN)
gLog.Optional(Log::Command, "Incomplete message ... waiting."); // Must not have the full message. Wait for it?
else if (m_inCommand.GetLastError() == EINTR)
gLog.Optional(Log::Command, "Interrupted message ... trying again.");
else if (m_inCommand.GetLastError() == ECONNRESET)
{
gLog.Message(Log::Command, "Communication connection reset.");
return true;
}
}
else if (m_inCommand.GetDataSize() == 0)
{
gLog.LogError("Empty communication message.");
return true;
}
else
{
// Got a message
gLog.Optional(Log::Command, "Message size %zu.", m_inCommand.GetDataSize());
try
{
dispatchMessage((char *)m_inCommand.GetData(), m_inCommand.GetDataSize());
}
catch (std::exception &e)
{
messageReplyF("Unable to complete request. Exception: %s\n", e.what());
}
return true;
}
}
return true;
}
/**
* Checks the validity of the message, and handles it.
*
* Call only from listen thread.
*
* @param message
* @param message_size
*
*/
void dispatchMessage(const char *message, size_t message_size)
{
const char *pos, *end;
const char *messageEnd = message + message_size - 1;
int paramCount = 0;
if (message_size < sizeof(uint32_t))
{
gLog.Optional(Log::Command, "Communication message too short. Ignoring.");
return;
}
if (ntohl(*(uint32_t *)message) != MagicMessageNumber)
{
gLog.Optional(Log::Command, "Message invalid. No magic number. Ignoring.");
return;
}
pos = message + sizeof(uint32_t);
// Verify the message
bool log = gLog.LogTypeEnabled(Log::Command);
m_inCommandLogStr.clear();
while (true)
{
end = pos;
for (; end <= messageEnd && *end != '\0'; end++)
{}
if (end > messageEnd)
{
gLog.Optional(Log::Command, "Message invalid. No terminator. Ignoring.");
return;
}
if (end == pos)
{
if (pos != messageEnd)
{
gLog.Optional(Log::Command, "Message invalid. Terminator came before the end.");
return;
}
break;
}
else
{
paramCount++;
if (paramCount != 1)
m_inCommandLogStr.push_back(' ');
m_inCommandLogStr.append(pos);
}
pos = end + 1;
}
if (paramCount == 0)
{
gLog.Message(Log::Command, "Empty message received.");
return;
}
if (log)
gLog.Optional(Log::Command, "Message %d <%s>\n", paramCount, m_inCommandLogStr.c_str());
// We have a valid message
handleMessage(message + sizeof(uint32_t), paramCount);
}
/**
* Handles a received message
*
* Call only from listen thread.
*
* @param replySocket
* @param message - The message itself.
* @param paramCount - The number of post message parameters.
*/
void handleMessage(const char *message, int paramCount)
{
(void)paramCount;
if (0 == strcasecmp(message, "stop"))
{
handle_Stop();
}
else if (0 == strcasecmp(message, "version"))
{
handle_Version();
}
else if (0 == strcasecmp(message, "connect"))
{
handle_Connect(message);
}
else if (0 == strcasecmp(message, "allow"))
{
handle_Allow(message);
}
else if (0 == strcasecmp(message, "block"))
{
handle_Block(message);
}
else if (0 == strcasecmp(message, "status"))
{
handle_Status(message);
}
else if (0 == strcasecmp(message, "log"))
{
handle_Log(message);
}
else if (0 == strcasecmp(message, "session"))
{
handle_Session(message);
}
#ifdef BFD_DEBUG
else if (0 == strcasecmp(message, "test"))
{
handle_Test(message);
}
#endif
else
{
messageReplyF("Unknown command <%s>\n", message);
}
}
typedef intptr_t(CommandProcessorImp::*BeaconCallback)(Beacon *beacon, void *userdata);
struct BeaconCallbackData
{
CommandProcessorImp *me;
void *userdata;
BeaconCallback callback;
bool wasShuttingDown;
intptr_t result;
bool exceptionThrown;
};
static void handleBeaconCallback(Beacon *beacon, void *userdata)
{
BeaconCallbackData *data = (BeaconCallbackData *)userdata;
if (beacon->IsShutdownRequested())
{
data->wasShuttingDown = true;
return;
}
try
{
data->result = (data->me->*(data->callback))(beacon, data->userdata);
}
catch (std::exception &e) // catch all exceptions .. is this too broad?
{
data->exceptionThrown = true;
gLog.Message(Log::Error, "Beacon callback failed due to exception: %s", e.what());
}
}
/**
* Queues a beacon callback. Does not return until operation is completed.
* Will respond using messageReply if the operation can not start due to a
* pending shutdown.
*
* @param userdata
*
* @return bool - false on failure to run the callback.
*/
bool doBeaconOperation(BeaconCallback callback, void *userdata, intptr_t *result = NULL)
{
BeaconCallbackData data;
data.me = this;
data.userdata = userdata;
data.callback = callback;
data.wasShuttingDown = false;
data.result = 0;
data.exceptionThrown = false;
if (!m_beacon->QueueOperation(handleBeaconCallback, &data, true /* waitForCompletion*/))
{
messageReply("Unable to complete request (beacon is shutting down or low memory).\n");
return false;
}
if (data.exceptionThrown)
{
messageReply("Unable to complete request because an exception was thrown. Likely out of memory.\n");
return false;
}
if (data.wasShuttingDown)
{
messageReply("Unable to complete request because the beacon is shutting down.\n");
return false;
}
if (result)
*result = data.result;
return true;
}
/**
* Holds enough info to locate a session, or marks for "All" sessions.
*
*/
struct SessionID
{
SessionID() : allSessions(false), whichId(0), whichRemoteAddr(), whichLocalAddr() { }
void Clear() { allSessions = false; whichId = 0; whichRemoteAddr.clear(); whichLocalAddr.clear();}
bool IsValid() const { return allSessions || whichId != 0 || HasIpAddresses();}
bool HasIpAddresses() const { return whichRemoteAddr.IsValid() && whichLocalAddr.IsValid();}
void SetAddress(bool local, const IpAddr &addr) { if (local)
whichLocalAddr = addr;
else
whichRemoteAddr = addr;}
bool allSessions;
uint32_t whichId;
IpAddr whichRemoteAddr;
IpAddr whichLocalAddr;
};
/**
* Converts a set of parameters to a local/remote ip address pair.
*
* @param inOutParam [in/out] - The first parameter to examine. On success this
* will point to the last parameter used. On failure it will
* remain unchanged.
* @param sessionId [out] - Cleared on input. On success will have ip address
* (sessionId.HasIpAddresses() will be true).
* @param errorMsg [out] - On error it will contain a message.
*
* @return bool - false if the string could not be converted.
*/
bool paramToIpPair(const char **inOutParam, SessionID &sessionId, string &errorMsg)
{
const char *command = *inOutParam;
const char *str = *inOutParam;
bool local;
SessionID temp;
IpAddr addrVal;
sessionId.Clear();
if (0 == strcmp(str, "remote"))
local = false;
else if (0 == strcmp(str, "local"))
local = true;
else
{
errorMsg = FormatBigStr("Error: Unknown <%s> should be 'remote' or 'local'.", str);
return false;
}
str = getNextParam(str);
if (!str)
{
errorMsg = FormatBigStr("Error: '%s' should be followed by an Pv4 or IPv6 address.", command);
return false;
}
if (!addrVal.FromString(str))
{
errorMsg = FormatBigStr("Error: <%s> is not an IPv4 or IPv6 address.", str);
return false;
}
temp.SetAddress(local, addrVal);
str = getNextParam(str);
if (!str)
{
errorMsg = FormatBigStr("Error: '%s' not found.", local ? "remote" : "local");
return false;
}
local = !local;
if (0 != strcmp(str, local ? "local" : "remote"))
{
errorMsg = FormatBigStr("Error: unknown <%s>. '%s' ip must be followed by '%s'.", str, command, local ? "local" : "remote");
return false;
}
command = str;
str = getNextParam(str);
if (!str)
{
errorMsg = FormatBigStr("Error: '%s' should be followed by an ip address.", command);
return false;
}
if (!addrVal.FromString(str))
{
errorMsg = FormatBigStr("Error: <%s> is not an IPv4 or IPv6 address.", str);
return false;
}
temp.SetAddress(local, addrVal);
if (temp.whichLocalAddr.Type() != temp.whichRemoteAddr.Type())
{
errorMsg = FormatBigStr("Error: can not mix IPv4 and IPv6 addresses.");
return false;
}
sessionId = temp;
*inOutParam = str;
return true;
}
/**
*
* Converts a parameter (or set of parameters) to an id or ip address, or "all".
* On failure sessionId is cleared.
*
* @param inOutParam [in/out] - The first parameters to examine. On parameters this
* will point to the last parameter used. On failure it will
* remain unchanged.
* @param sessionId [out]
* @param errorMsg [out] - On error it will contain a message.
*
* @return bool - false if the string could not be converted.
*/
bool paramToIdOrIp(const char **inOutParam, SessionID &sessionId, string &errorMsg)
{
int64_t val;
const char *str = *inOutParam;
sessionId.Clear();
if (0 == strcmp(str, "all"))
{
sessionId.allSessions = true;
return true;
}
if (0 == strcmp(str, "remote") || 0 == strcmp(str, "local"))
return paramToIpPair(inOutParam, sessionId, errorMsg);
// must be an id
if (StringToInt(str, val) && val != 0)
{
sessionId.whichId = (uint32_t)val;
return true;
}
errorMsg = FormatBigStr("Unknown <%s>.", str);
return false;
}
/**
*
* Call only from callback thread.
* Finds the session for the id or ip.
* Only one will be used.
*
* @param beacon
* @param sessionId [in] - The session to find. Fails if allSessions.
*
* @return Session* - NULL if there is no such session. Or sessionId is "all"
*/
Session* findSession(Beacon *beacon, const SessionID &sessionId)
{
if (!beacon)
return NULL;
if (!sessionId.IsValid() || sessionId.allSessions)
return NULL;
if (sessionId.whichId != 0)
return beacon->FindSessionId(sessionId.whichId);
if (sessionId.HasIpAddresses())
return beacon->FindSessionIp(sessionId.whichRemoteAddr, sessionId.whichLocalAddr);
return NULL;
}
/**
*
* Clears and fill the vector with all the sessions as described by sessionId.
*
* @param outList
*
* @return - false if sessionId is invalid, or does not represent an live
* session. true if there are no sessions, but sessionId is all. true
* if sessions found
*/
bool findSessionIdList(Beacon *beacon, const SessionID &sessionId, std::vector<uint32_t> &outList)
{
if (!sessionId.IsValid())
return false;
if (sessionId.allSessions)
{
beacon->GetSessionIdList(outList);
return true;
}
outList.clear();
Session *session = findSession(beacon, sessionId);
if (!session)
return false;
outList.push_back(session->GetId());
return true;
}
/**
* Sends reply message complaining that the given session could not be located.
*
* @param sessionId [in] - The session to find. Fails if allSessions.
*/
void reportNoSuchSession(const SessionID &sessionId)
{
if (sessionId.whichId != 0)
messageReplyF("No session with id=%u.\n", sessionId.whichId);
else if (sessionId.HasIpAddresses())
messageReplyF("No session with local ip=%s and remote ip=%s.\n", sessionId.whichLocalAddr.ToString(), sessionId.whichRemoteAddr.ToString());
else
messageReply("Unknown session specifier.\n");
}
void handle_Stop()
{
m_beacon->RequestShutdown();
messageReply("stopping\n");
}
void handle_Version()
{
messageReplyF("%s v%s\n", BeaconAppName, SofwareVesrion);
}
/**
* "log" command.
* Format 'log' 'level' name - to set logging level
* Format 'log' type ['yes'|'no'] - enable/disable specific logging.
*
*/
void handle_Log(const char *message)
{
const char *itemString;
static const char *itemValues = "'level', 'type' or 'timing'";
itemString = getNextParam(message);
if (!itemString)
{
messageReplyF("Must specify: %s.\n", itemValues);
return;
}
if (0 == strcmp(itemString, "level"))
{
Log::Level level;
const char *levelString = getNextParam(itemString);
if (!levelString)
{
messageReply("Must specify a level name or 'list'.\n");
return;
}
if (0 == strcmp("list", levelString))
{
string str;
str.reserve(Log::LevelCount * 10);
for (int index = 0; index < Log::LevelCount; index++)
{
if (!str.empty())
str += ", ";
str += gLog.LogLevelToString(Log::Level(index));
}
messageReplyF("Available log levels: %s\n", str.c_str());
return;
}
level = gLog.StringToLogLevel(levelString);
if (level == Log::LevelCount)
{
messageReplyF("Unknown level: %s.\n", levelString);
return;
}
gLog.SetLogLevel(level);
messageReplyF("Log level set to %s.\n", levelString);
return;
}
else if (0 == strcmp(itemString, "type"))
{
Log::Type type;
bool enable, wasEnabled;
const char *paramString = getNextParam(itemString);
if (!paramString)
{
messageReply("'type' must be followed by 'list' or a log type.\n");
return;
}
if (0 == strcmp("list", paramString))
{
string str;
str.reserve(Log::TypeCount * 30);
for (type = Log::Type(0); type < Log::TypeCount; type = Log::Type(type + 1))
{
const char *desc = gLog.LogTypeDescription(type);
if (*desc != '\0')
str += FormatMediumStr(" %s - %s\n", gLog.LogTypeToString(Log::Type(type)), desc);
else
str += FormatMediumStr(" %s\n", gLog.LogTypeToString(Log::Type(type)));
}
messageReplyF("Available log types:\n%s", str.c_str());
return;
}
type = gLog.StringToLogType(paramString);
if (type == Log::TypeCount)
{
messageReplyF("Unknown log type: %s.\n", paramString);
return;
}
const char *actionString = getNextParam(paramString);
if (!actionString)
{
messageReply("Must specify 'yes' or 'no'.\n");
return;
}
if (0 == strcmp("yes", actionString))
enable = true;
else if (0 == strcmp("no", actionString))
enable = false;
else
{
messageReply("Must specify 'yes' or 'no'.\n");
return;
}
wasEnabled = gLog.LogTypeEnabled(type);
gLog.EnableLogType(type, enable);
messageReplyF("Log type %s set to %s, was %s\n", paramString, enable ? "yes" : "no", wasEnabled ? "yes" : "no");
return;
}
else if (0 == strcmp(itemString, "timing"))
{
bool enable;
const char *actionString = getNextParam(itemString);
if (!actionString)
{
messageReply("Must specify 'yes' or 'no'.\n");
return;
}
if (0 == strcmp("yes", actionString))
enable = true;
else if (0 == strcmp("no", actionString))
enable = false;
else
{
messageReply("Must specify 'yes' or 'no'.\n");
return;
}
gLog.SetExtendedTimeInfo(enable ? Logger::TimeInfo::Mono : Logger::TimeInfo::None);
messageReplyF("Extended time logging %s.\n", enable ? "enabled" : "disabled");
return;
}
else
{
messageReplyF("'log' must be followed by one of %s. Unknown <%s>\n", itemValues, itemString);
}
}
/**
* "connect" command.
* Format 'connect' ip.
* Starts an 'active' session with the given ip.
*/
void handle_Connect(const char *message)
{
SessionID address;
const char *addressString;
intptr_t result;
string error;
addressString = getNextParam(message);
if (!addressString)
{
messageReply("Must supply 'local ip remote ip' address pair.\n");
return;
}
if (!paramToIpPair(&addressString, address, error))
{
messageReplyF("'connect' must be followed by an ip pair. %s\n", error.c_str());
return;
}
if (doBeaconOperation(&CommandProcessorImp::doHandleConnect, &address, &result))
{
if (result)
messageReplyF("Opened connection from local %s to remote %s\n", address.whichLocalAddr.ToString(), address.whichRemoteAddr.ToString());