-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathcsocket.cpp
More file actions
1583 lines (1417 loc) · 48.9 KB
/
csocket.cpp
File metadata and controls
1583 lines (1417 loc) · 48.9 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
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
// csocket.cpp - handles client/server behaviors (not needed in a product)
/*
* C++ sockets on Unix and Windows Copyright (C) 2002 --- see HEADER file
*/
#ifdef INFORMATION
We have these threads :
1. HandleTCPClient which runs on a thread to service a particular client(as many threads as clients)
2. AcceptSockets, which is a simnple thread waiting for user connections
3. ChatbotServer, which is the sole server to be the chatbot
4. main thread, which is a simple thread that creates ChatbotServer threads as needed(if ones crash in LINUX, it can spawn a new one)
chatLock - either chatbot engine or a client controls it.It is how a client gets started and then the server is summoned
While processing chat, the client holds the clientlock and the server holds the chatlock and donelock.
The client is waiting for the donelock.
When the server finishes, he releases the donelock and waits for the clientlock.
If the client exists, server gets the donelock, then releases it and waits for the clientlock.
If the client doesnt exist anymore, he has released clientlock.
It releases the clientlock and the chatlock and tries to reacquire chatlock with flag on.
when it succeeds, it has a new client.
We have these variables :
chatbotExists - the chatbot engine is now initialized.
serverFinishedBy is what time the answer must be delivered(1 second before the memory will disappear)
#endif
#include "common.h"
#ifndef WIN32
#include <ifaddrs.h>
#include <net/if.h>
#endif
static int servertransfersize;
bool echoServer = false;
char serverIP[100];
static int pass = 0;
static int fail = 0;
typedef unsigned int (*initsystem)(int, char* [], char*, char*, char*, USERFILESYSTEM*, DEBUGAPI, DEBUGAPI);
typedef unsigned int (*performchat)(char*, char*, char*, char*, char*) ;
void GetPrimaryIP(char* buffer)
{
#ifdef WIN32
InitWinsock();
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1 ) printf("Error at socket(): %d\n", WSAGetLastError());
const char* kGoogleDnsIp = "8.8.8.8";
uint16_t kDnsPort = 53;
struct sockaddr_in serv;
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
serv.sin_port = htons(kDnsPort);
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
int err = connect(sock, (const sockaddr*)&serv, sizeof(serv));
sockaddr_in name;
socklen_t namelen = sizeof(name);
err = getsockname(sock, (sockaddr*)&name, &namelen);
const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, MAX_WORD_SIZE);
closesocket(sock);
if (!server) WSACleanup();
#else
struct ifaddrs *ifaddr, *ifa;
// get a linked list of network interfaces
// https://man7.org/linux/man-pages/man3/getifaddrs.3.html
if (getifaddrs(&ifaddr) == -1) return;
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
// only want the IPv4 address from an interface that is up and not a loopback
// the name could be "en0" or "eth0"
if (ifa->ifa_addr->sa_family == AF_INET && ifa->ifa_flags & IFF_UP && !(ifa->ifa_flags & IFF_LOOPBACK))
{
char host[NI_MAXHOST];
if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
{
sprintf(buffer,"%s",host);
break;
}
}
}
freeifaddrs(ifaddr);
#endif
// use localhost if nothing found
if (!*buffer) sprintf(buffer,"127.0.0.1");
}
#ifndef DISCARDSERVER
#ifdef EVSERVER
#include "cs_ev.h"
#include "evserver.h"
#endif
#define DOSOCKETS 1
#endif
#ifndef DISCARDCLIENT
#define DOSOCKETS 1
#endif
#ifndef DISCARDTCPOPEN
#define DOSOCKETS 1
#endif
#ifdef DOSOCKETS
// CODE below here is from PRACTICAL SOCKETS, needed for either a server or a client
// SocketException Code
SocketException::SocketException(const string &message, bool inclSysMsg)
throw() : userMessage(message) {
if (inclSysMsg) {
userMessage.append((char*)": ");
userMessage.append(strerror(errno));
}
}
SocketException::~SocketException() throw() {}
const char *SocketException::what() const throw() { return userMessage.c_str(); }
// Function to fill in address structure given an address and port
static void fillAddr(const string &address, unsigned short myport, sockaddr_in &addr) {
memset(&addr, 0, sizeof(addr)); // Zero out address structure
addr.sin_family = AF_INET; // Internet address
hostent *host; // Resolve name
if ((host = gethostbyname(address.c_str())) == NULL) throw SocketException((char*)"Failed to resolve name (gethostbyname())");
strcpy(hostname, host->h_name);
addr.sin_addr.s_addr = *((unsigned long *)host->h_addr_list[0]);
addr.sin_port = htons(myport); // Assign port in network byte order
}
// Socket Code
#define MAKEWORDX(a, b) ((unsigned short)(((BYTE)(((DWORD_PTR)(a)) & 0xff)) | (((unsigned short)((BYTE)(((DWORD_PTR)(b)) & 0xff))) << 8)))
CSocket::CSocket(int type, int protocol) throw(SocketException) {
#ifdef WIN32
if (InitWinsock() == FAILRULE_BIT) throw SocketException((char*)"Unable to load WinSock DLL"); // Load WinSock DLL
#endif
// Make a new socket
if ((sockDesc = socket(PF_INET, type, protocol)) < 0) throw SocketException((char*)"Socket creation failed (socket())", true);
}
CSocket::CSocket(int sockDesc) { this->sockDesc = sockDesc; }
CSocket::~CSocket() {
#ifdef WIN32
::closesocket(sockDesc);
#else
::close(sockDesc);
#endif
sockDesc = -1;
}
string CSocket::getLocalAddress() throw(SocketException) {
sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
if (getsockname(sockDesc, (sockaddr *)&addr, (socklen_t *)&addr_len) < 0) throw SocketException((char*)"Fetch of local address failed (getsockname())", true);
return inet_ntoa(addr.sin_addr);
}
unsigned short CSocket::getLocalPort() throw(SocketException) {
sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
if (getsockname(sockDesc, (sockaddr *)&addr, (socklen_t *)&addr_len) < 0) throw SocketException((char*)"Fetch of local port failed (getsockname())", true);
return ntohs(addr.sin_port);
}
void CSocket::setLocalPort(unsigned short localPort) throw(SocketException) {
#ifdef WIN32
if (InitWinsock() == FAILRULE_BIT) throw SocketException((char*)"Unable to load WinSock DLL");
#endif
int on = 1;
int off = 0;
#ifdef WIN32
setsockopt(sockDesc, SOL_SOCKET, SO_REUSEADDR, (char*)&off, sizeof(on));
#else
setsockopt(sockDesc, SOL_SOCKET, SO_REUSEADDR, (void*)&off, sizeof(on));
#endif
// Bind the socket to its port
sockaddr_in localAddr;
memset(&localAddr, 0, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(localPort);
if (::bind(sockDesc, (sockaddr *)&localAddr, sizeof(sockaddr_in)) < 0) throw SocketException((char*)"Set of local port failed (bind())", true);
}
void CSocket::setLocalAddressAndPort(const string &localAddress,
unsigned short localPort) throw(SocketException) {
// Get the address of the requested host
sockaddr_in localAddr;
fillAddr(localAddress, localPort, localAddr);
int on = 1;
int off = 0;
#ifdef WIN32
setsockopt(sockDesc, SOL_SOCKET, SO_REUSEADDR, (char*)&off, sizeof(on));
#else
setsockopt(sockDesc, SOL_SOCKET, SO_REUSEADDR, (void*)&off, sizeof(on));
#endif
if (::bind(sockDesc, (sockaddr *)&localAddr, sizeof(sockaddr_in)) < 0) throw SocketException((char*)"Set of local address and port failed (bind())", true);
}
void CSocket::cleanUp() throw(SocketException) {
#ifdef WIN32
if (WSACleanup() != 0) throw SocketException((char*)"WSACleanup() failed");
#endif
}
unsigned short CSocket::resolveService(const string &service,
const string &protocol) {
struct servent *serv; /* Structure containing service information */
if ((serv = getservbyname(service.c_str(), protocol.c_str())) == NULL) return (unsigned short)atoi(service.c_str()); /* Service is port number */
else return ntohs(serv->s_port); /* Found port (network byte order) by name */
}
// CommunicatingSocket Code
CommunicatingSocket::CommunicatingSocket(int type, int protocol) throw(SocketException) : CSocket(type, protocol) {
}
CommunicatingSocket::CommunicatingSocket(int newConnSD) : CSocket(newConnSD) {
}
void CommunicatingSocket::connect(const string &foreignAddress, unsigned short foreignPort) throw(SocketException) {
// Get the address of the requested host
sockaddr_in destAddr;
fillAddr(foreignAddress, foreignPort, destAddr);
// Try to connect to the given port
if (::connect(sockDesc, (sockaddr *)&destAddr, sizeof(destAddr)) < 0) throw SocketException((char*)"Connect failed (connect())", true);
}
void CommunicatingSocket::send(const void *buffer, int bufferLen) throw(SocketException) {
if (::send(sockDesc, (raw_type *)buffer, bufferLen, 0) < 0) throw SocketException((char*)"Send failed (send())", true);
}
int CommunicatingSocket::recv(void *buffer, int bufferLen) throw(SocketException) {
int rtn;
if ((rtn = ::recv(sockDesc, (raw_type *)buffer, bufferLen, 0)) < 0) throw SocketException((char*)"Received failed (recv())", true);
return rtn;
}
string CommunicatingSocket::getForeignAddress() throw(SocketException) {
sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
if (getpeername(sockDesc, (sockaddr *)&addr, (socklen_t *)&addr_len) < 0) throw SocketException((char*)"Fetch of foreign address failed (getpeername())", true);
return inet_ntoa(addr.sin_addr);
}
unsigned short CommunicatingSocket::getForeignPort() throw(SocketException) {
sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
if (getpeername(sockDesc, (sockaddr *)&addr, (socklen_t *)&addr_len) < 0) throw SocketException((char*)"Fetch of foreign port failed (getpeername())", true);
return ntohs(addr.sin_port);
}
// TCPSocket Code
TCPSocket::TCPSocket() throw(SocketException) : CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
}
TCPSocket::TCPSocket(const string &foreignAddress, unsigned short foreignPort) throw(SocketException) : CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
connect(foreignAddress, foreignPort);
}
TCPSocket::TCPSocket(int newConnSD) : CommunicatingSocket(newConnSD) {
}
// TCPServerSocket Code
TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen) throw(SocketException) : CSocket(SOCK_STREAM, IPPROTO_TCP) {
setLocalPort(localPort);
setListen(queueLen);
}
TCPServerSocket::TCPServerSocket(const string &localAddress, unsigned short localPort, int queueLen) throw(SocketException) : CSocket(SOCK_STREAM, IPPROTO_TCP) {
setLocalAddressAndPort(localAddress, localPort);
setListen(queueLen);
}
TCPSocket *TCPServerSocket::accept() throw(SocketException) {
int newConnSD;
if ((newConnSD = ::accept(sockDesc, NULL, 0)) < 0) throw SocketException((char*)"Accept failed (accept())", true);
return new TCPSocket(newConnSD);
}
void TCPServerSocket::setListen(int queueLen) throw(SocketException) {
if (listen(sockDesc, queueLen) < 0) throw SocketException((char*)"Set listening socket failed (listen())", true);
}
#endif
#ifndef DISCARDCLIENT
static void ReadSocket(TCPSocket* sock, char* response)
{
int bytesReceived = 1; // Bytes read on each recv()
int totalBytesReceived = 0; // Total bytes read
char* base = response;
*response = 0;
while (bytesReceived > 0)
{
// Receive up to the buffer size bytes from the sender
bytesReceived = sock->recv(base, MAX_WORD_SIZE);
totalBytesReceived += bytesReceived;
base += bytesReceived;
if (trace) (*printer)((char*)"Received %d bytes\r\n", bytesReceived);
if (totalBytesReceived > 2 && response[totalBytesReceived - 3] == 0
&& (unsigned char)response[totalBytesReceived - 2] == (unsigned char)0xfe && (unsigned char)response[totalBytesReceived - 1] == (unsigned char)0xff) break; // positive confirmation was enabled
}
*base = 0;
}
void NoBlankStart(char* ptr, char* where)
{
while (*ptr == ' ') ++ptr;
strcpy(where, ptr);
size_t len = strlen(ptr);
while (where[len - 1] == ' ') where[--len] = 0;
}
static bool GetSourceFile(char* ptr)
{
char file[SMALL_WORD_SIZE];
ReadCompiledWord(ptr, file);
sourceFile = fopen(file, (char*)"rb");
if (!sourceFile)
{
sourceFile = stdin;
printf("No such source file %s\r\n", file);
return false;
}
else return true;
}
void Client(char* login)// test client for a server
{
#ifndef DISCARDSERVER
InitStackHeap();
sourceFile = stdin;
char word[MAX_WORD_SIZE];
if (!trace) echo = false;
(*printer)((char*)"%s", (char*)"\r\n\r\n** Client launched\r\n");
char* from = login;
char priorcat[MAX_WORD_SIZE];
char prioruser[MAX_WORD_SIZE];
char priorspec[MAX_WORD_SIZE];
char* data = AllocateBuffer(); // read from user or file
char* preview = AllocateBuffer();
char* totalConvo = AllocateBuffer();
char* response = AllocateBuffer(); // returned from chatbot
char* sendbuffer = (char* ) mymalloc(fullInputLimit +maxBufferSize+100); // staged message to chatbot
char user[500];
size_t userlen;
size_t botlen;
size_t msglen;
*prioruser = 0;
*priorcat = 0;
*priorspec = 0;
*user = 0;
char* msg;
char bot[500];
*bot = 0;
char* botp = bot;
*data = 0;
int count = -1;
int skip = 0;
if (*from == '*') // let user go first.
{
++from;
(*printer)((char*)"%s", (char*)"\r\ninput: ");
ReadALine(data, sourceFile); // actual user input
msg = data;
}
else msg = (char*)"";
restart: // start with user
char* separator = strchr(from, ':'); // login is username or username:botname or username:botname/trace or username:trace
if (separator)
{
*separator = 0;
botp = separator + 1;
strcpy(bot, botp);
}
else
{
botp = from + strlen(from); // just a 0
*botp = 0;
}
sprintf(logFilename, (char*)"log-%s.txt", from);
strcpy(user, from);
// message to server is 3 strings- username, botname, null (start conversation) or message
char* ptr = sendbuffer;
strcpy(ptr, user); // username
ptr += strlen(user);
*ptr++ = 0;
strcpy(ptr, botp);
ptr += strlen(ptr); // botname (and may have optional flags on it)
*ptr++ = 0;
*ptr = 0;
size_t baselen = ptr - sendbuffer; // length of message user/bot header not including message
bool jaconverse = false;
bool jamonologue = false;
bool jastarts = false;
bool source = false;
bool raw = false;
bool botturn = false;
bool converse = false;
bool endConvo = false;
if (!*loginID) strcpy(loginID, user);
try
{
SOURCE:
if (!strnicmp(ptr, (char*)":converse ", 9))
{
char file[SMALL_WORD_SIZE];
ReadCompiledWord(ptr + 8, file);
sourceFile = fopen(file, (char*)"rb");
converse = true;
}
else if (!strnicmp(ptr, (char*)":jastarts ", 9))
{
char file[SMALL_WORD_SIZE];
ptr = ReadCompiledWord(ptr + 9, file);
sourceFile = fopen(file, (char*)"rb");
if (!sourceFile)
{
printf("%s not found\r\n", file);
myexit("not found");
}
jastarts = true;
ptr = SkipWhitespace(ptr);
char num[100];
ptr = ReadCompiledWord(ptr, num);
count = atoi(num);
if (count == 0) count = 1000000; // count and skip optional, default to all
ptr = ReadCompiledWord(ptr, num);
skip = atoi(num);
ptr = data;
}
else if (!strnicmp(ptr, (char*)":jaconverse", 11) || !strnicmp(ptr, (char*)":jamonologue", 12))
{
char file[SMALL_WORD_SIZE];
int diff = 11;
if (!strnicmp(ptr, (char*)":jamonologue", 12))
{
jamonologue = true;
diff += 1;
}
ptr = ReadCompiledWord(ptr + diff, file);
sourceFile = fopen(file, (char*)"rb");
if (!sourceFile)
{
printf("%s not found\r\n", file);
myexit("not found");
}
jastarts = true;
jaconverse = true;
botturn = true;
ptr = SkipWhitespace(ptr);
char num[100];
ptr = ReadCompiledWord(ptr, num);
count = atoi(num);
if (count == 0) count = 1000000; // count and skip optional, default to all
ptr = ReadCompiledWord(ptr, num);
skip = atoi(num);
ptr = data;
}
else if (!strnicmp(ptr, (char*)":raw ", 5))
{
char file[SMALL_WORD_SIZE];
ptr = ReadCompiledWord(ptr + 5, file);
sourceFile = fopen(file, (char*)"rb");
raw = true;
ptr = SkipWhitespace(ptr);
char num[100];
ptr = ReadCompiledWord(ptr, num);
count = atoi(num);
if (count == 0) count = 1000000;
ptr = ReadCompiledWord(ptr, num);
skip = atoi(num);
ptr = data;
}
char* sep = NULL;
TCPSocket *sock;
bool failonce = false;
int n = 0;
char copy[MAX_BUFFER_SIZE];
char output[MAX_WORD_SIZE * 10];
*output = 0;
while (ALWAYS)
{
if ((++n % 100) == 0) (*printer)((char*)"On Line %d\r\n", n);
if (!strnicmp(ptr, (char*)":source ", 8))
{
source = GetSourceFile(ptr + 8);
}
if (source)
{
int ans = ReadALine(ptr, sourceFile, fullInputLimit + maxBufferSize - 100);
if (ans <= 0)
{
source = false;
sourceFile = stdin;
ans = ReadALine(ptr, sourceFile, fullInputLimit + maxBufferSize - 100);
continue;
}
}
else if (converse) // do a conversation of multiple lines each tagged with user until done, not JA style
{
ptr = data;
if (Myfgets(ptr, 100000 - 100, sourceFile) == NULL) break;
if (HasUTF8BOM(ptr)) memmove(data, data + 3, strlen(data + 2));// UTF8 BOM
// (*printer)((char*)"Read %s\r\n", data);
strcpy(copy, ptr);
size_t l = strlen(ptr);
ptr[l - 2] = 0; // remove crlf
// a line is username message
char* blank = strchr(ptr, '\t'); // user / botname
if (!blank) continue;
*blank = 0; // user string now there
sep = strchr(blank + 1, '\t'); // botname / message
if (!sep) continue;
*sep = 0; // bot string now there
strcpy(bot, blank + 1);
botp = bot;
botlen = strlen(bot);
if (stricmp(ptr, user)) // change over user with null start message
{
strcpy(user, data);
strcpy(sendbuffer, user);
userlen = strlen(user);
sendbuffer[userlen + 1] = 0;
botlen = strlen(bot);
strcpy(sendbuffer + userlen + 1, bot);
sendbuffer[userlen + 1 + botlen + 1] = 0;
baselen = userlen + botlen + 2;
sendbuffer[baselen] = 0;
// (*printer)((char*)"Sent login %s\r\n", data);
sock = new TCPSocket(serverIP, (unsigned short)port);
sock->send(sendbuffer, baselen + 1);
ReadSocket(sock, response);
delete(sock);
}
msg = sep + 1;
ptr = msg;
}
else if (jastarts) // includes single lines and continuous conversations
{
if (*preview) strcpy(data, preview); // become primary
else *data = 0;
if (Myfgets(preview, 100000 - 100, sourceFile) == NULL)
{
if (failonce) break; // really over
failonce = true; // now only have preview copy left
}
if (!*data) continue; // starting out, priming preview buffer
if (--skip > 0) continue;
if (--count < 0) break;
char newuser[1000];
char* blank = strchr(preview, '\t');
if (!blank) continue;
*blank = 0;
NoBlankStart(preview, newuser);
*blank = '\t';
ptr = data; // process current data
if (HasUTF8BOM(ptr)) memmove(data, data + 3, strlen(data + 2));// UTF8 BOM
// Get User name
blank = strchr(ptr, '\t');
if (!blank) continue;
*blank = 0; // user string now there
NoBlankStart(data, user);
*blank = '\t'; // user string now there
endConvo = failonce || strcmp(newuser, user) || strstr(preview, "a secure page"); // changing user or last line of data
strcpy(copy, ptr);
size_t l = strlen(ptr);
while (ptr[l - 1] == '\t' || ptr[l - 1] == '\n' || ptr[l - 1] == '\r') ptr[--l] = 0; // remove trailing tabs
strcpy(copy, ptr);
char cat[MAX_WORD_SIZE];
char spec[MAX_WORD_SIZE];
char loc[MAX_WORD_SIZE];
// userid, cat, spec, loc, message, {output}
// userid can be blank, we overwrite with user1 name
// if userid is 1, these are conversations which end when cat/spec changes
// get category
ptr = blank + 1; // cat star
blank = strchr(ptr, '\t');
if (!blank) continue;
*blank = 0;
NoBlankStart(ptr, cat);
char* space = cat;
while ((space = strchr(space, ' ')))
{
if (space && IsAlphaUTF8(space[1]) && space[1] != ' ') *space = '_';
else ++space;
}
// get specialty
ptr = blank + 1; // spec
blank = strchr(ptr, '\t');
if (!blank) continue;
*blank = 0;
NoBlankStart(ptr, spec);
space = spec;
while ((space = strchr(space, ' ')))
{
if (space && IsAlphaUTF8(space[1]) && space[1] != ' ') *space = '_';
else ++space;
}
if (!stricmp(spec, "none") || !stricmp(spec, "null") || *spec == 0) strcpy(spec, "general");
// get location
ptr = blank + 1; // loc
blank = strchr(ptr, '\t'); // end of loc
if (!blank) continue;
*blank = 0;
if (*ptr == ' ') ++ptr;
NoBlankStart(ptr, loc);
// Get Input & check output
ptr = blank + 1; // start of message
blank = strchr(ptr, '\t');
if (blank) // input has output column
{
strcpy(output, blank + 1);
*blank = 0; // mark end of input message
}
else *output = 0;
bool newstart = false;
// do we send the start message (new user, category, or specialty)
if (stricmp(user, prioruser) || stricmp(cat, priorcat) || stricmp(spec, priorspec)) // changing cat/spec
{
newstart = true;
botturn = true;
}
if (jaconverse) botturn = !botturn; // flip viewpoint
if (jaconverse && !botturn && !newstart && !jamonologue) continue; // ignore this as swallowed
strcpy(priorcat, cat);
strcpy(priorspec, spec);
strcpy(prioruser, user);
if (!stricmp(cat, "general")) continue; // sip rerouter, we have no idea where it went
// construct std start message user,bot,0
sprintf(sendbuffer, "%s",loginID); // same user here always -- fails to clear some globals w/o :reset:
// else strcpy(sendbuffer, user);
userlen = strlen(sendbuffer);
*bot = 0;
botlen = strlen(bot);
sendbuffer[userlen + 1] = 0;
strcpy(sendbuffer + userlen + 1, bot);
sendbuffer[userlen + 1 + botlen + 1] = 0;
baselen = userlen + botlen + 2;
char* at = sendbuffer + baselen;
if (newstart)
{
*totalConvo = 0;
if (*output)
{
if (!*loc) sprintf(at, ":reset: [ category: %s specialty: %s id: %s expect: \"%s\"]", cat, spec, user, output);
else sprintf(at, ":reset: [ category: %s specialty: %s id: %s location: %s expect: \"%s\"]", cat, spec, user, loc, output);
}
else
{
if (!*loc) sprintf(at, ":reset: [ category: %s specialty: %s id: %s ]", cat, spec, user);
else sprintf(at, ":reset: [ category: %s specialty: %s id: %s location: %s ]", cat, spec, user, loc);
}
sock = new TCPSocket(serverIP, (unsigned short)port);
sock->send(sendbuffer, baselen + 1 + strlen(at));
ReadSocket(sock, response);
delete(sock);
}
if (jaconverse && !botturn && !jamonologue) continue; // ignore this now that converse is started
else
{
strcat(totalConvo, " | ");
strcat(totalConvo, ptr);
}
}
else if (raw)
{
ptr = data;
if (Myfgets(ptr, 100000 - 100, sourceFile) == NULL)
break;
if (--skip > 0) continue;
if (--count < 0)
break;
strcpy(copy, ptr);
if (HasUTF8BOM(data)) memmove(data, data + 3, strlen(data + 2));// UTF8 BOM
strcpy(user, "user1");
strcpy(sendbuffer, user);
userlen = strlen(sendbuffer);
*bot = 0;
botlen = strlen(bot);
sendbuffer[userlen + 1] = 0;
strcpy(sendbuffer + userlen + 1, bot);
sendbuffer[userlen + 1 + botlen + 1] = 0;
baselen = userlen + botlen + 2;
char* at = sendbuffer + baselen;
sprintf(at, "[ category: %s ]", "legal");
sock = new TCPSocket(serverIP, (unsigned short)port);
sock->send(sendbuffer, baselen + 1 + strlen(at));
ReadSocket(sock, response);
delete(sock);
}
// send our normal message now
msglen = strlen(ptr);
char* at = sendbuffer + baselen;
if (*output || endConvo)
{
if (*output && endConvo) sprintf(at, "[expect: %s end: \"%s\"] ", output, totalConvo);
else if (*output) sprintf(at, "[expect: %s] ", output);
else sprintf(at, "[end: \"totalConvo\"] ");
at += strlen(at);
}
strncpy(at, ptr, msglen + 1);
size_t len = baselen + strlen(sendbuffer + baselen) + 1;
sock = new TCPSocket(serverIP, (unsigned short)port);
sock->send(sendbuffer, len);
if (!converse && !jastarts && !raw) (*printer)((char*)"Sent %d bytes of data to port %d - %s|%s\r\n", (int)len, port, sendbuffer, msg);
ReadSocket(sock, response);
if (!trace) echo = !converse;
delete(sock);
char* pastoob = strrchr(response, ']');
if (pastoob) ++pastoob;
*data = 0;
// we say that until :exit
if (!converse && !jastarts && !raw && !source)
{
(*printer)((char*)"%s", response);
(*printer)((char*)"%s", (char*)"\r\n> ");
// check for oob callback
ProcessOOB(response);
while (ProcessInputDelays(data + 1, KeyReady())) { ; }// use our fake callback input? loop waiting if no user input found
}
else if (jastarts || raw) {}
else Log(USERLOG, "%s %s %s\r\n", user, bot, response);
if (!converse && !jastarts && !jaconverse && !raw && !source)
{
if (*data) {}
else if (ReadALine(data, sourceFile, 100000 - 100) < 0) break; // next thing we want to send
strcat(data, (char*)" "); // never send empty line
msg = data;
ptr = data;
// special instructions
if (!strnicmp(SkipWhitespace(data), (char*)":quit", 5)) break;
else if (!strnicmp(SkipWhitespace(data), (char*)":source", 7)) goto SOURCE;
else if (!strnicmp(SkipWhitespace(data), (char*)":jastarts", 7))
{
ptr = data;
goto SOURCE;
}
else if (!strnicmp(SkipWhitespace(data), (char*)":jaconverse", 11) || !strnicmp(SkipWhitespace(data), (char*)":jamonologue", 12))
{
ptr = data;
goto SOURCE;
}
else if (!strnicmp(ptr, (char*)":dllchat", 8))
{
#ifdef WIN32
HINSTANCE hGetProcIDDLL = LoadLibrary((LPCSTR)"chatscript.dll");
if (!hGetProcIDDLL) {
printf("could not load cs dll\r\n");
myexit("no dll");
}
// resolve function address here
initsystem x = (initsystem)GetProcAddress(hGetProcIDDLL, "InitSystem");
//unsigned int InitSystem(int argcx, char* argvx[], char* unchangedPath, char* readablePath, char* writeablePath, USERFILESYSTEM* userfiles, DEBUGAPI infn, DEBUGAPI outfn)
if (!x) {
printf("could not locate InitSystem\r\n");
return;
}
printf("Loading DLL\r\n");
if (x(0, NULL, NULL, NULL, NULL, NULL, NULL, NULL)) {
printf(" InitSystem failed\r\n");
return;
}
performchat y = (performchat)GetProcAddress(hGetProcIDDLL, "PerformChat");
// PerformChat(loginID, computerID, ourMainInputBuffer, NULL, ourMainOutputBuffer); // no ip
if (!y) {
printf("could not locate PerformChat\r\n");
return;
}
char file[SMALL_WORD_SIZE];
ReadCompiledWord(ptr + 8, file);
char* input = AllocateBuffer();
char* output = AllocateBuffer();
sourceFile = fopen(file, (char*)"rb");
sprintf(serverLogfileName, "%s/serverlogdll.txt",logsfolder);
while (ReadALine(input, sourceFile, MAX_BUFFER_SIZE) >= 0)
{
*output = 0;
server = true;
Log(SERVERLOG, "ServerPre: %s (%s) size:%d %s\r\n", user, bot, strlen(input), input);
server = false;
y((char*)"dll-user", (char*)"", input, (char*)"11.11.11.11", output);
server = true;
Log(SERVERLOG, "Respond: %s (%s) %s\r\n", user, bot, output);
printf(output);
server = false;
}
FClose(sourceFile);
printf("\r\ndone\r\n");
FreeBuffer();
FreeBuffer();
#endif
exit(0);
}
else if (!strnicmp(SkipWhitespace(data), (char*)":jaraw", 4))
{
ptr = data;
goto SOURCE;
}
else if (!converse && !strncmp(data, (char*)":converse ", 9))
{
char file[SMALL_WORD_SIZE];
ReadCompiledWord(data + 9, file);
sourceFile = fopen(file, (char*)"rb");
converse = true;
continue;
}
else if (!strnicmp(SkipWhitespace(data), (char*)":restart", 8))
{
// send restart on to server...
sock = new TCPSocket(serverIP, (unsigned short)port);
sock->send(data, strlen(data) + 1);
(*printer)((char*)":restart sent data to port %d\r\n", port);
ReadSocket(sock, response);
Log(USERLOG,"%s", response); // chatbot replies this
delete(sock);
(*printer)((char*)"%s", (char*)"\r\nEnter client user name: ");
ReadALine(word, sourceFile);
(*printer)((char*)"%s", (char*)"\r\n");
from = word;
goto restart;
}
}
}
}
catch (SocketException e) {
myexit((char*)"failed to connect to server");
}
FClose(sourceFile);
#endif
}
#endif
#ifndef DISCARDSERVER
#define SERVERTRANSERSIZE (4 + 100 + fullInputLimit) // offset to output buffer
#ifdef WIN32
#pragma warning(push,1)
#pragma warning(disable: 4290)
#include <process.h>
#endif
#include <cstdio>
#include <errno.h>
using namespace std;
static TCPServerSocket* serverSocket = NULL;
unsigned int serverFinishedBy = 0; // server must complete by this or not bother
// buffers used to send in and out of chatbot
static char* clientBuffer; // current client spot input was and output goes
static bool chatWanted = false; // client is still expecting answer (has not timed out/canceled)
static bool chatbotExists = false; // has chatbot engine been set up and ready to go?
static int pendingClients = 0; // number of clients waiting for server to handle them
#ifndef EVSERVER
static void* MainChatbotServer();
static void* HandleTCPClient(void* sock1);
static void* AcceptSockets(void*);
static unsigned int errorCount = 0;
static time_t lastCrash = 0;
#endif
static int loadid = 0;
#ifndef WIN32 // for LINUX
#include <pthread.h>
#include <signal.h>
pthread_t chatThread;
static pthread_mutex_t chatLock = PTHREAD_MUTEX_INITIALIZER; // access lock to shared chatbot processor
static pthread_mutex_t testLock = PTHREAD_MUTEX_INITIALIZER; // right to use test memory
static pthread_cond_t server_var = PTHREAD_COND_INITIALIZER; // client ready for server to proceed
static pthread_cond_t server_done_var = PTHREAD_COND_INITIALIZER; // server ready for clint to take data
#else // for WINDOWS
#include <winsock2.h>
HANDLE hChatLockMutex;
CRITICAL_SECTION TestCriticalSection;
#endif
void CloseServer() {
if (serverSocket != NULL) {
delete serverSocket;
serverSocket = NULL;
}
}
void* RegressLoad(void* junk)// test load for a server
{
FILE* in = FopenReadOnly((char*)"REGRESS/bigregress.txt");
if (!in) return 0;
char buffer[8000];
(*printer)((char*)"\r\n\r\n** Load %d launched\r\n", ++loadid);
char data[MAX_WORD_SIZE];
char from[100];
sprintf(from, (char*)"%d", loadid);
const char* bot = "";
sprintf(logFilename, (char*)"log-%s.txt", from);
unsigned int msg = 0;
unsigned int volleys = 0;
unsigned int longVolleys = 0;
unsigned int xlongVolleys = 0;
int maxTime = 0;
int cycleTime = 0;
int currentCycleTime = 0;
int avgTime = 0;
// message to server is 3 strings- username, botname, null (start conversation) or message
echo = true;
char* ptr = data;
strcpy(ptr, from);
ptr += strlen(ptr) + 1;
strcpy(ptr, bot);
ptr += strlen(ptr) + 1;
*buffer = 0;
int counter = 0;
while (1)
{
if (ReadALine(revertBuffer + 1, in, maxBufferSize - 100) < 0) break; // end of input
// when reading from file, see if line is empty or comment
char word[MAX_WORD_SIZE];
ReadCompiledWord(revertBuffer + 1, word);
if (!*word || *word == '#' || *word == ':') continue;
strcpy(ptr, revertBuffer + 1);
try
{
size_t len = (ptr - data) + 1 + strlen(ptr);
++volleys;
uint64 start_time = ElapsedMilliseconds();
TCPSocket *sock = new TCPSocket(serverIP, port);
sock->send(data, len);
int bytesReceived = 1; // Bytes read on each recv()
int totalBytesReceived = 0; // Total bytes read
char* base = ptr;
while (bytesReceived > 0)
{
// Receive up to the buffer size bytes from the sender
bytesReceived = sock->recv(base, MAX_WORD_SIZE);
totalBytesReceived += bytesReceived;
base += bytesReceived;
}
uint64 end_time = ElapsedMilliseconds();