summaryrefslogtreecommitdiff
path: root/mailapi.c
blob: 690d2b459639a0a597731e9daa6583ca26dd1261 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
// basic JASON API to BPQ Node

// Authentication is via Telnet USER records or bbs records


#define _CRT_SECURE_NO_DEPRECATE
#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers

//#include <windows.h>
#include "CHeaders.h"
#include <stdlib.h>
#include "bpqmail.h"
#include "httpconnectioninfo.h"

struct MsgInfo * GetMsgFromNumber(int msgno);
BOOL CheckUserMsg(struct MsgInfo * Msg, char * Call, BOOL SYSOP);
char * doXMLTransparency(char * string);


// Constants
#define TOKEN_SIZE 32 // Length of the authentication token
#define TOKEN_EXPIRATION 7200 // Token expiration time in seconds (2 hours)

// Token data structure
typedef struct MailToken {
	char token[TOKEN_SIZE + 1];
	time_t expiration_time;
	struct UserInfo * User;
	char Call[10];
	int Auth;			// Security level of user

	struct MailToken* next;
} MailToken;

static MailToken * token_list = NULL;

typedef struct MailAPI
{
	char *URL;
	int URLLen;
	int (* APIRoutine)(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth);
	int Auth;
} MailAPI;

// Auth defines

#define AuthNone 0
#define AuthUser 1
#define AuthBBSUser 2
#define AuthSysop 4


static int verify_token(const char* token);
static void remove_expired_tokens();
static int  request_token(char * response);
static void add_token_to_list(MailToken* token);
static MailToken * find_token(const char* token); 

int sendMsgList(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth);
int sendFwdQueueLen(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth);
int sendFwdConfig(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth);

static struct MailAPI APIList[] =
{
	"/mail/api/v1/msgs", 17, sendMsgList, 0,
	"/mail/api/v1/FwdQLen", 20, sendFwdQueueLen, AuthSysop,
	"/mail/api/v1/FwdConfig", 22, sendFwdConfig, AuthSysop,
};

static int APICount = sizeof(APIList) / sizeof(struct MailAPI);

#ifndef WIN32
iconv_t * icu = NULL;
#endif

void APIConvertTitletoUTF8(char * Title, char * UTF8Title, int Len)
{
	if (WebIsUTF8(Title, (int)strlen(Title)) == FALSE)
	{
		// With Windows it is simple - convert using current codepage
		// I think the only reliable way is to convert to unicode and back

		int origlen = (int)strlen(Title) + 1;
#ifdef WIN32
		WCHAR BufferW[128];
		int wlen;
		int len = origlen;

		wlen = MultiByteToWideChar(CP_ACP, 0, Title, len, BufferW, origlen * 2); 
		len = WideCharToMultiByte(CP_UTF8, 0, BufferW, wlen, UTF8Title, origlen * 2, NULL, NULL); 
#else
		size_t left = Len - 1;
		size_t len = origlen;

		if (icu == NULL)
			icu = iconv_open("UTF-8//IGNORE", "CP1252");

		if (icu == (iconv_t)-1)
		{
			strcpy(UTF8Title, Title);
			icu = NULL;
			return;
		}

		char * orig = UTF8Title;

		iconv(icu, NULL, NULL, NULL, NULL);		// Reset State Machine
		iconv(icu, &Title, &len, (char ** __restrict__)&UTF8Title, &left);

#endif
	}
	else
		strcpy(UTF8Title, Title);
}

static MailToken * generate_token() 
{
	// Generate a random authentication token
	int i;

	MailToken * token = malloc(sizeof(MailToken));

	srand(time(NULL));

	for (i = 0; i < TOKEN_SIZE; i++)
	{
		token->token[i] = 'A' + rand() % 26; // Random uppercase alphabet character
	}
	token->token[TOKEN_SIZE] = '\0'; // Null-terminate the token
	token->expiration_time = time(NULL) + TOKEN_EXPIRATION; // Set token expiration time
	add_token_to_list(token);
	return token;
}

// Function to add the token to the token_list
static void add_token_to_list(MailToken * token)
{
	if (token_list == NULL)
	{
		token_list = token;
		token->next = NULL;
	}
	else
	{
		MailToken * current = token_list;
		
		while (current->next != NULL) 
			current = current->next;

		current->next = token;
		token->next = NULL;
	}
}

static void remove_expired_tokens()
{
	time_t current_time = time(NULL);
	MailToken* current_token = token_list;
	MailToken* prev_token = NULL;
	MailToken* next_token;

	while (current_token != NULL)
	{
		if (current_time > current_token->expiration_time) 
		{
			// Token has expired, remove it from the token list
			if (prev_token == NULL)
			{
				token_list = current_token->next;
			} else {
				prev_token->next = current_token->next;
			}
			next_token = current_token->next;
			free(current_token);
			current_token = next_token;
		} else {
			prev_token = current_token;
			current_token = current_token->next;
		}
	}
}

static MailToken * find_token(const char* token) 
{
	MailToken * current_token = token_list;

	while (current_token != NULL) 
	{
		if (strcmp(current_token->token, token) == 0) 
		{
			return current_token;
		}
		current_token = current_token->next;
	}
	return NULL;
}

static int send_http_response(char * response, const char* msg)
{
	return sprintf(response, "HTTP/1.1 %s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", msg);
}


int MailAPIProcessHTTPMessage(struct HTTPConnectionInfo * Session, char * response, char * Method, char * URL, char * request, BOOL LOCAL, char  *Params, char * TokenString)
{
	char * pass = strlop(Params, '&');
	int Flags = 0, n;
	MailToken * Token;
	char Msg[64];
	struct UserInfo * User;
	int Auth = 0;

	if (LOCAL)
		Auth = AuthSysop;

	// Check if the request is for token generation

	if (strcmp(Method, "GET") != 0)
		return send_http_response(response, "403 (Bad Method)");

	if (_stricmp(URL, "/mail/api/v1/login") == 0)
	{
		// Key is in Session->Key
		
		// Signon may have been validated in Node. If Session->Callsign is set
		
		if (Session->Callsign[0] == 0)
		{
			// Try BBS logon
			
			User = LookupCall(Params);
			
			if (User)
			{
				// Check Password

				if (pass[0] == 0 || strcmp(User->pass, pass) != 0 || User->flags & F_Excluded)
					return send_http_response(response, "403 (Login Failed)");		
			
				strcpy(Session->Callsign, User->Call);
				Auth = AuthBBSUser;
				if (User->flags & F_SYSOP)
					Auth |= AuthSysop;



			}
		}
		else
		{
			User = LookupCall(Session->Callsign);

			if (User)
			{
				Auth = AuthUser;
				if (User->flags & F_SYSOP)
					Auth |= AuthSysop;
			}
		}

		n = sprintf_s(Msg, sizeof(Msg), "API Connect from %s", _strupr(Params));
		WriteLogLine(NULL, '|',Msg, n, LOG_BBS);

		Token = zalloc(sizeof(MailToken));

		strcpy(Token->token, Session->Key);
		strcpy(Token->Call, Session->Callsign);
		Token->Auth = Auth;

		Token->expiration_time = time(NULL) + TOKEN_EXPIRATION; // Set token expiration time
		add_token_to_list(Token);

		// Return Token

		sprintf(response, "{\"access_token\":\"%s\", \"expires_at\":%d, \"scope\":\"create\"}\r\n",
			Token->token, Token->expiration_time);

		return strlen(response);
	}

	// Find Token

	if (TokenString[0])					// Token form Auth Header
		Token = find_token(TokenString);
	else
		Token = find_token(Params);		// Token form URL

	if (Token != NULL)
	{
		// Check if the token has expired
	
		time_t current_time = time(NULL);
		if (current_time > Token->expiration_time)
		{
			// Token has expired, remove it from the token list
			remove_expired_tokens();
			Token = NULL;
		}
	}

	if (Token)
		Auth |= Token->Auth;

	// Determine the requested API endpoint

	for (n = 0; n < APICount; n++)
	{
		struct MailAPI * APIEntry;
		char * rest;
		
		APIEntry = &APIList[n];

		if (_memicmp(URL, APIEntry->URL, APIEntry->URLLen) == 0)
		{
			rest = &request[4 + APIEntry->URLLen];	// Anything following?

			if (rest[0] =='?')
			{
				//Key

				strlop(rest, ' ');
				strlop(rest, '&');

				Token = find_token(&rest[1]);

				if (Token)
				{
					strcpy(Session->Callsign, Token->Call);
					strcpy(Session->Key, Token->token);
				}
				else
					return send_http_response(response, "403 (Invalid Security Token)");
			}
			
			if (APIEntry->Auth)
			{
				// Check Level 

				if ((Auth & APIEntry->Auth) == 0)
					return send_http_response(response, "403 (Not Authorized)");
			}

			if (rest[0] == ' ' || rest[0] == '/' || rest[0] == '?')
			{
				return APIEntry->APIRoutine(Session, response, rest, Auth);
			}
		}

	}

	return send_http_response(response, "401 Invalid API Call");


	return 0;
}

int WebMailAPIProcessHTTPMessage(char * response, char * Method, char * URL, char * request, BOOL LOCAL, char  *Params)
{
	char * pass = strlop(Params, '&');
	int Flags = 0;
	MailToken * Token;


	// Check if the request is for token generation

	if (strcmp(Method, "GET") != 0)
		return send_http_response(response, "403 (Bad Method)");

	if (_stricmp(URL, "/mail/api/login") == 0)
	{
		// user is in Params and Password in pass

		struct UserInfo * User;
		char Msg[256];
		int n;

		User = LookupCall(Params);

		if (User)
		{
			// Check Password

			if (pass[0] == 0 || strcmp(User->pass, pass) != 0 || User->flags & F_Excluded)
				return send_http_response(response, "403 (Login Failed)");		
			
			n=sprintf_s(Msg, sizeof(Msg), "API Connect from %s", _strupr(Params));
			WriteLogLine(NULL, '|',Msg, n, LOG_BBS);

			Token = generate_token();
			add_token_to_list(Token);

			Token->User = User;

			strcpy(Token->Call, Params);

			// Return Token

			sprintf(response, "{\"access_token\":\"%s\", \"expires_in\":%d, \"scope\":\"create\"}\r\n",
					Token->token, Token->expiration_time);

			return strlen(response);

		}
	}

	return 0;
}

//	Unauthenticated users can only get bulls.
//	Authenticated users may read only that users messages or all messages depending on sysop status

int sendMsgList(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth)
{
 	struct UserInfo * User = LookupCall(Session->Callsign);
	int m;
	struct MsgInfo * Msg;
	char * ptr = response;
	int n = NumberofMessages; //LineCount;
	char Via[64];
	int Count = 0;
	struct UserInfo DummyUser = {""};
	ptr[0] = 0;

	if (User == 0)
		User=&DummyUser;

	n = sprintf(ptr,"{\"msgs\":[\r\n");
	ptr += n;

	for (m = LatestMsg; m >= 1; m--)
	{
		if (ptr > &response[244000])
			break;						// protect buffer

		Msg = GetMsgFromNumber(m);

		if (Msg == 0 || Msg->type == 0 || Msg->status == 0)
			continue;					// Protect against corrupt messages
		
		if (Msg && CheckUserMsg(Msg, User->Call, Auth & AuthSysop))
		{
			char UTF8Title[4096];
			char  * EncodedTitle;
			
			// List if it is the right type

			ptr += sprintf(ptr, "{\r\n");

			strcpy(Via, Msg->via);
			strlop(Via, '.');

			// make sure title is HTML safe (no < > etc) and UTF 8 encoded

			EncodedTitle = doXMLTransparency(Msg->title);

			memset(UTF8Title, 0, 4096);		// In case convert fails part way through
			APIConvertTitletoUTF8(EncodedTitle, UTF8Title, 4095);

			ptr += sprintf(ptr, "\"id\": \"%d\",\r\n", Msg->number);
			ptr += sprintf(ptr, "\"mid\": \"%s\",\r\n", Msg->bid);
			ptr += sprintf(ptr, "\"rcvd\": \"%d\",\r\n", Msg->datecreated);
			ptr += sprintf(ptr, "\"type\": \"%c\",\r\n", Msg->type);
			ptr += sprintf(ptr, "\"status\": \"%c\",\r\n", Msg->status);
			ptr += sprintf(ptr, "\"to\": \"%s\",\r\n", Msg->to);
			ptr += sprintf(ptr, "\"from\": \"%s\",\r\n", Msg->from);
			ptr += sprintf(ptr, "\"size\": \"%d\",\r\n", Msg->length);
			ptr += sprintf(ptr, "\"subject\": \"%s\"\r\n", UTF8Title);

			free(EncodedTitle);
			
			ptr += sprintf(ptr, "},\r\n"); 

		}
	}

	if (response[n] == 0)		// No entries
	{
		response[strlen(response) - 2] = '\0';          // remove \r\n
		strcat(response, "]}\r\n");
	}
	else
	{
		response[strlen(response)-3 ] = '\0';          // remove ,\r\n
		strcat(response, "\r\n]}\r\n");
	}
	return strlen(response);
}

int sendFwdQueueLen(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth)
{
	struct UserInfo * USER;
	char * ptr = response;
	int n;
	int i = 0;
	int Len = 0;

	n = sprintf(ptr,"{\"forwardqueuelength\":[\r\n");
	ptr += n;
	
	for (USER = BBSChain; USER; USER = USER->BBSNext)
	{
		int Count = CountMessagestoForward (USER);

		ptr += sprintf(ptr, "{");
		ptr += sprintf(ptr, "\"call\": \"%s\",", USER->Call);
		ptr += sprintf(ptr, "\"queueLength\": \"%d\"", Count);
		ptr += sprintf(ptr, "},\r\n");
	}

	if (response[n] == 0)		// No entries
	{
		response[strlen(response) - 2] = '\0';          // remove \r\n
		strcat(response, "]}\r\n");
	}
	else
	{
		response[strlen(response)-3 ] = '\0';          // remove ,\r\n
		strcat(response, "\r\n]}\r\n");
	}
	return strlen(response);
}

VOID APIMultiStringValue(char ** values, char * Multi)
{
	char ** Calls;
	char * ptr = &Multi[0];

	*ptr = 0;

	if (values)
	{
		Calls = values;

		while(Calls[0])
		{
			ptr += sprintf(ptr, "\"%s\",", Calls[0]);
			Calls++;
		}
		if (ptr != &Multi[0])
			*(--ptr) = 0;
	}
}

char * APIConvTime(int ss)
{
	int hh, mm;
	static char timebuf[64];

	hh = ss / 3600;
	mm = (ss - (hh * 3600)) / 60;
	ss = ss % 60;

	sprintf(timebuf, "\"%02d:%02d:%02d\"", hh, mm, ss);

	return timebuf;
}


int sendFwdConfig(struct HTTPConnectionInfo * Session, char * response, char * Rest, int Auth)
{
	struct UserInfo * USER;
	char * ptr = response;
	int n = 0;
	int i = 0;
	int Len = 0;

	response[n] = 0;

	n = sprintf(ptr, "{\r\n");
	ptr += n;

	for (USER = BBSChain; USER; USER = USER->BBSNext)
	{
		struct BBSForwardingInfo * FWDInfo = USER->ForwardingInfo;

		int Count = CountMessagestoForward (USER);

		char TO[2048] = "";
		char AT[2048] = "";
		char TIMES[2048] = "";
		char FWD[100000] = "";
		char HRB[2048] = "";
		char HRP[2048] = "";

		APIMultiStringValue(FWDInfo->TOCalls, TO);
		APIMultiStringValue(FWDInfo->ATCalls, AT);
		APIMultiStringValue(FWDInfo->FWDTimes, TIMES);
		APIMultiStringValue(FWDInfo->ConnectScript, FWD);
		APIMultiStringValue(FWDInfo->Haddresses, HRB);
		APIMultiStringValue(FWDInfo->HaddressesP, HRP);



		ptr += sprintf(ptr, " \"%s\": {\r\n", USER->Call);
		ptr += sprintf(ptr, "  \"queueLength\": %d,\r\n", Count);
		ptr += sprintf(ptr, "  \"to\": [%s],\r\n", TO);
		ptr += sprintf(ptr, "  \"at\": [%s],\r\n", AT);
		ptr += sprintf(ptr, "  \"hrp\": [%s],\r\n",HRP);
		ptr += sprintf(ptr, "  \"hrb\": [%s],\r\n",HRB);
		ptr += sprintf(ptr, "  \"times\": [%s],\r\n",TIMES);
		ptr += sprintf(ptr, "  \"connectScript\": [%s],\r\n",FWD);
		ptr += sprintf(ptr, "  \"bbsHa\": \"%s\",\r\n", (FWDInfo->BBSHA)?FWDInfo->BBSHA:"");
		ptr += sprintf(ptr, "  \"enableForwarding\": %s,\r\n", (FWDInfo->Enabled)?"true":"false");
		ptr += sprintf(ptr, "  \"forwardingInterval\": %s,\r\n", APIConvTime(FWDInfo->FwdInterval));
		ptr += sprintf(ptr, "  \"requestReverse\": %s,\r\n", (FWDInfo->ReverseFlag)?"true":"false");
		ptr += sprintf(ptr, "  \"reverseInterval\": %s,\r\n", APIConvTime(FWDInfo->RevFwdInterval));
		ptr += sprintf(ptr, "  \"sendNewMessagesWithoutWaiting\": %s,\r\n", (FWDInfo->SendNew)?"true":"false");
		ptr += sprintf(ptr, "  \"fbbBlocked\": %s,\r\n", (FWDInfo->AllowBlocked)?"true":"false");
		ptr += sprintf(ptr, "  \"maxBlock\": %d,\r\n", FWDInfo->MaxFBBBlockSize);
		ptr += sprintf(ptr, "  \"sendPersonalMailOnly\": %s,\r\n", (FWDInfo->PersonalOnly)?"true":"false");
		ptr += sprintf(ptr, "  \"allowBinary\": %s,\r\n", (FWDInfo->AllowCompressed)?"true":"false");
		ptr += sprintf(ptr, "  \"useB1Protocol\": %s,\r\n", (FWDInfo->AllowB1)?"true":"false");
		ptr += sprintf(ptr, "  \"useB2Protocol\": %s,\r\n", (FWDInfo->AllowB2)?"true":"false");
		ptr += sprintf(ptr, "  \"incomingConnectTimeout\": %s\r\n", APIConvTime(FWDInfo->ConTimeout));
		ptr += sprintf(ptr, " },\r\n");
	}

	if (response[n] == 0)		// No entries
	{
		strcpy(response, "{}\r\n");
	}
	else
	{
		response[strlen(response)-3 ] = '\0';          // remove ,\r\n
		strcat(response, "\r\n}\r\n");
	}

	return strlen(response);
}



/*
{
  "GB7BEX": {
    "queueLength": 0,
    "forwardingConfig": {
      "to": [],
      "at": [
        "OARC",
        "GBR",
        "WW"
      ],
      "times": [],
      "connectScript": [
        "PAUSE 3",
        "INTERLOCK 3",
        "NC 3 !GB7BEX"
      ],
      "hierarchicalRoutes": [],
      "hr": [
        "#38.GBR.EURO"
      ],
      "bbsHa": "GB7BEX.#38.GBR.EURO",
      "enableForwarding": true,
      "forwardingInterval": "00:56:40",
      "requestReverse": false,
      "reverseInterval": "00:56:40",
      "sendNewMessagesWithoutWaiting": true,
      "fbbBlocked": true,
      "maxBlock": 1000,
      "sendPersonalMailOnly": false,
      "allowBinary": true,
      "useB1Protocol": false,
      "useB2Protocol": true,
      "sendCtrlZInsteadOfEx": false,
      "incomingConnectTimeout": "00:02:00"
    }
  },
  "GB7RDG": {
    "queueLength": 0,
    "forwardingConfig": {
      "to": [],
...
      "incomingConnectTimeout": "00:02:00"
    }
  }
}



# HELP packetmail_queue_length The number of messages in the packetmail queue
# TYPE packetmail_queue_length gauge
packetmail_queue_length{partner="DM4RW"} 0 1729090716916
packetmail_queue_length{partner="G8BPQ"} 3 1729090716916
packetmail_queue_length{partner="GB7BEX"} 0 1729090716916
packetmail_queue_length{partner="GB7BPQ"} 1 1729090716916
packetmail_queue_length{partner="GB7MNS"} 0 1729090716916
packetmail_queue_length{partner="GB7NOT"} 0 1729090716916
packetmail_queue_length{partner="GB7NWL"} 0 1729090716916
packetmail_queue_length{partner="GM8BPQ"} 0 1729090716916

*/


// Stuff send to  packetnodes.spots.radio/api/bbsdata/{bbsCall}
//https://nodes.ukpacketradio.network/swagger/index.html


/*
BbsData{
callsign*	[...]
time*	[...]
hroute*	[...]
peers	[...]
software*	[...]
version*	[...]
mailQueues	[...]
messages	[...]
latitude	[...]
longitude	[...]
locator	[...]
location	[...]
unroutable	[...]
}

[

{
    "callsign": "GE8PZT",
    "time": "2024-11-25T10:07:41+00:00",
    "hroute": ".#24.GBR.EU",
    "peers": [
      "GB7BBS",
      "VE2PKT",
      "GB7NXT",
      "VA2OM"
    ],
    "software": "XrLin",
    "version": "504a",
    "mailQueues": [],
    "messages": [
      {
        "to": "TECH@WW",
        "mid": "20539_GB7CIP",
        "rcvd": "2024-11-24T09:27:59+00:00",
        "routing": [
          "R:241124/0927Z @:GE8PZT.#24.GBR.EU [Lamanva] #:2315 XrLin504a",
 

      {
        "to": "TNC@WW",
        "mid": "37_PA2SNK",
        "rcvd": "2024-11-18T21:56:55+00:00",
        "routing": [
          "R:241118/2156Z @:GE8PZT.#24.GBR.EU [] #:2215 XrLin504a",
          "R:241118/2156Z 12456@VE2PKT.#TRV.QC.CAN.NOAM BPQ6.0.24",
          "R:241118/2130Z 51539@VE3KPG.#ECON.ON.CAN.NOAM BPQK6.0.23",
          "R:241118/2130Z 26087@VE3CGR.#SCON.ON.CAN.NOAM LinBPQ6.0.24",
          "R:241118/2130Z 37521@PA8F.#ZH1.NLD.EURO LinBPQ6.0.24",
          "R:241118/2129Z 48377@PI8LAP.#ZLD.NLD.EURO LinBPQ6.0.24",
          "R:241118/2129Z @:PD0LPM.FRL.EURO.NLD #:33044 [Joure] $:37_PA2SNK"
        ]
      }
    ],
    "latitude": 50.145832,
    "longitude": -5.125,
    "locator": "IO70KD",
    "location": "Lamanva",
    "unroutable": [
      {
        "type": "P",
        "at": "WW"
      },
      {
        "type": "P",
        "at": "G8PZT-2"
      },
      {
        "type": "P",
        "at": "g8pzt._24.gbr.eu"
      },
      {
        "type": "P",
        "at": "G8PZT.#24.GBR.EU"
      },
      {
        "type": "P",
        "at": "GE8PZT.#24.GBR.EU"
      },
      {
        "type": "P",
        "at": "G8PZT.#24.GBR.EURO"
      }
    ]
  },

*/


//	https://packetnodes.spots.radio/swagger/index.html

// 	   "unroutable": [{"type": "P","at": "WW"}, {"type": "P", "at": "G8PZT.#24.GBR.EURO"}]

char * ViaList[100000];			// Pointers to the Message Header field
char TypeList[100000];

int unroutableCount = 0;


void CheckifRoutable(struct MsgInfo * Msg)
{
	char NextBBS[64];
	int n;

	if (Msg->status == 'K')
		return;

	if (Msg->via[0] == 0)		// No routing
		return;

	strcpy(NextBBS, Msg->via);
	strlop(NextBBS, '.');

	if (strcmp(NextBBS, BBSName) == 0)	// via this BBS
		return;

	if ((memcmp(Msg->fbbs, zeros, NBMASK) != 0) || (memcmp(Msg->forw, zeros, NBMASK) != 0))	// Has Forwarding Info
		return;

	// See if we already have it

	for (n = 0; n < unroutableCount; n++)
	{
		if ((TypeList[n] == Msg->type) && strcmp(ViaList[n], Msg->via) == 0)
			return;

	}

	// Add to list

	TypeList[unroutableCount] = Msg->type;
	ViaList[unroutableCount] = Msg->via;

	unroutableCount++;
}


extern char LOC[7];


DllExport VOID WINAPI SendWebRequest(char * Host, char * Request, char * Params, char * Return);

#ifdef LINBPQ
extern double LatFromLOC;
extern double LonFromLOC;
#else
typedef int (WINAPI FAR *FARPROCX)();
extern FARPROCX pSendWebRequest;
extern FARPROCX pGetLatLon;
double LatFromLOC = 0;
double LonFromLOC = 0;
#endif

void SendBBSDataToPktMap()
{
	char Request[64];
	char * Params;
	char * ptr;
	int paramLen;
	struct MsgInfo * Msg;

	struct UserInfo * ourBBSRec = LookupCall(BBSName);
	struct UserInfo * USER;
	char Time[64];
	struct tm * tm;
	time_t Date = time(NULL);
	char Peers[2048] = "[]";
	char MsgQueues[16000] = "[]";
	char * Messages = malloc(1000000);	
	char * Unroutables;
	int m;
	char * MsgBytes;
	char * Rlineptr;
	char * Rlineend;
	char * RLines;
	char * ptr1, * ptr2;
	int n;

#ifndef LINBPQ
	if (pSendWebRequest == 0)
		return;						// Old Version of bpq32.dll

	pGetLatLon(&LatFromLOC, &LonFromLOC);

#endif
	if (ourBBSRec == 0)
		return;		// Wot!!

	// Get peers and Mail Queues

	ptr = &Peers[1];
	ptr1 = &MsgQueues[1];

	for (USER = BBSChain; USER; USER = USER->BBSNext)
	{
		if (strcmp(USER->Call, BBSName) != 0)
		{
			int Bytes;
			
			int Count = CountMessagestoForward(USER);	
			
			ptr += sprintf(ptr, "\"%s\",", USER->Call);

			if (Count)
			{
				Bytes = CountBytestoForward(USER);

				ptr1 += sprintf(ptr1, "{\"peerCall\": \"%s\", \"numQueued\": %d, \"bytesQueued\": %d},",
					USER->Call, Count, Bytes);
			}
      }
	}

	if ((*ptr) != ']')		// Have some entries
	{
		ptr--;				// over trailing comms
		*(ptr++) = ']';
		*(ptr) = 0;
	}

	if ((*ptr1) != ']')		// Have some entries
	{
		ptr1--;				// over trailing comms
		*(ptr1++) = ']';
		*(ptr1) = 0;
	}

	// Get Messages

	strcpy(Messages, "[]");
	ptr = &Messages[1];

	for (m = LatestMsg; m >= 1; m--)
	{
		if (ptr > &Messages[999000])
			break;						// protect buffer

		Msg = GetMsgFromNumber(m);

		if (Msg == 0 || Msg->type == 0 || Msg->status == 0)
			continue;					// Protect against corrupt messages

		// Paula suggests including H and K but limit it to the last 30 days or the last 100 messages, whichever is the smaller.

//		if (Msg->status == 'K' || Msg->status == 'H')
//			continue;

		if ((Date - Msg->datereceived) > 30 * 86400)		// Too old
			continue;

		CheckifRoutable(Msg);

		tm = gmtime((time_t *)&Msg->datereceived);

		sprintf(Time, "%04d-%02d-%02dT%02d:%02d:%02d+00:00", 
			tm->tm_year + 1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);

		// Get Routing

		MsgBytes = ReadMessageFile(Msg->number);
		RLines = malloc(Msg->length * 2);				// Very unlikely to need so much but better safe..

		strcpy(RLines, "[]");

		ptr2 = &RLines[1];
		
		// Need to skip B2 header if B2 Message

		Rlineptr = MsgBytes;

		// If it is a B2 Message, Must Skip B2 Header

		if (Msg->B2Flags & B2Msg)
		{
			Rlineptr = strstr(Rlineptr, "\r\n\r\n");
			if (Rlineptr)
				Rlineptr += 4;
			else
				Rlineptr = MsgBytes;
		}

		// We have to process R: lines one at a time as we need to send each one as a separate string

		while (memcmp(Rlineptr, "R:", 2) == 0)
		{
			// Have R Lines

			Rlineend = strstr(Rlineptr, "\r\n");
			Rlineend[0] = 0;
			ptr2 += sprintf(ptr2, "\"%s\",", Rlineptr);

			Rlineptr = Rlineend + 2;		// over crlf
		}

		if ((*ptr2) == ']')		// no entries
			continue;

		ptr2--;				// over trailing comms
		*(ptr2++) = ']';
		*(ptr2) = 0;
	
		ptr += sprintf(ptr, "{\"to\": \"%s\", \"mid\": \"%s\", \"rcvd\": \"%s\", \"routing\": %s},",
			Msg->to, Msg->bid, Time, RLines);

		free(MsgBytes);
		free(RLines);

	}

	if ((*ptr) != ']')	// Have some entries?
	{
		ptr--;				// over trailing comms
		*(ptr++) = ']';
		*(ptr) = 0;
	}

	// Get unroutables

	Unroutables = malloc((unroutableCount + 1) * 100);

	strcpy(Unroutables, "[]");
	ptr = &Unroutables[1];


	for (n = 0; n < unroutableCount; n++)
	{
		ptr += sprintf(ptr, "{\"type\": \"%c\",\"at\": \"%s\"},", TypeList[n], ViaList[n]);
	}

	if ((*ptr) != ']')	// Have some entries?
	{
		ptr--;				// over trailing comms
		*(ptr++) = ']';
		*(ptr) = 0;
	}



	/*
char * ViaList[100000];			// Pointers to the Message Header field
char TypeList[100000];

int unroutableCount = 0;
	   "unroutable": [{"type": "P","at": "WW"}, {"type": "P", "at": "G8PZT.#24.GBR.EURO"}]
	*/


	tm = gmtime(&Date);

	sprintf(Time, "%04d-%02d-%02dT%02d:%02d:%02d+00:00", 
		tm->tm_year + 1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);


	paramLen = strlen(Peers) + strlen(MsgQueues) + strlen(Messages) + strlen(Unroutables);

	Params = malloc(paramLen + 1000);

	if (Params == 0)
	{
		free(Messages);
		free(Unroutables);
		return;
	}

	ptr = Params;

	sprintf(Request, "/api/bbsdata/%s", BBSName);

	ptr += sprintf(ptr, "{\"callsign\": \"%s\",\r\n", BBSName);
	ptr += sprintf(ptr, "\"time\": \"%s\",\r\n", Time);
	ptr += sprintf(ptr, "\"hroute\": \"%s\",\r\n", HRoute);
	ptr += sprintf(ptr, "\"peers\": %s,\r\n", Peers);
#ifdef LINBPQ
	ptr += sprintf(ptr, "\"software\": \"%s\",\r\n", "linbpq");
#else
	ptr += sprintf(ptr, "\"software\": \"%s\",\r\n", "BPQMail");
#endif
	ptr += sprintf(ptr, "\"version\": \"%s\",\r\n", VersionString);
	ptr += sprintf(ptr, "\"mailQueues\": %s,\r\n", MsgQueues);
	ptr += sprintf(ptr, "\"messages\": %s,\r\n", Messages);
	ptr += sprintf(ptr, "\"latitude\": %1.6f,\r\n", LatFromLOC);
	ptr += sprintf(ptr, "\"longitude\": %.6f,\r\n", LonFromLOC);
	ptr += sprintf(ptr, "\"locator\": \"%s\",\r\n", LOC);
	ptr += sprintf(ptr, "\"location\": \"%s\",\r\n", ourBBSRec->Address);
	ptr += sprintf(ptr, "\"unroutable\": %s\r\n}\r\n", Unroutables);

#ifdef LINBPQ
	SendWebRequest("packetnodes.spots.radio", Request, Params, 0);
#else
	pSendWebRequest("packetnodes.spots.radio", Request, Params, 0);
#endif
	free(Messages);
	free(Unroutables);
	free(Params);
}