summaryrefslogtreecommitdiff
path: root/protocols/YAMN/src/proto/pop3/pop3comm.cpp
blob: d712bff6c0b424fa5c4432fb1783457ef709a5c3 (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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
/*
 * This code implements POP3 server checking for new mail and so on.
 * There's function SynchroPOP3 in this file- for checking and synchronising POP3 account
 * and DeleteMailsPOP3- for deleting mails from POP3 server
 *
 * Note this file acts as main file for internal plugin.
 *
 * (c) majvan 2002-2004
 * 18/08
 */


#include "../../stdafx.h"

#define ERRORSTR_MAXLEN	1024	// in wide-chars

HANDLE hNetLib = nullptr;
SCOUNTER CPOP3Account::AccountWriterSO;

// Creates new CPOP3Account structure
CAccount* MIR_CDECL CreatePOP3Account(YAMN_PROTOPLUGIN *Plugin);

// Deletes CPOP3Account structure
void MIR_CDECL DeletePOP3Account(CAccount *Which);

// Sets stop flag to account
void MIR_CDECL StopPOP3Account(CAccount *Which);

// Function registers standard functions for YAMN
int RegisterPOP3Plugin(WPARAM, LPARAM);

// Unloads all variables created on heap (delete[])
DWORD MIR_CDECL UnLoadPOP3(void *);

// Function stores plugin's data for account to file
DWORD MIR_CDECL WritePOP3Options(HANDLE, CAccount *);

// Function reads plugin's data for account from file
DWORD MIR_CDECL ReadPOP3Options(CAccount *, char **, char *);

// Creates new mail for an account
HYAMNMAIL MIR_CDECL CreatePOP3Mail(CAccount *Account);

// Function does all needed work when connection failed or any error occured
// Creates structure containing error code, closes internet session, runs "bad connect" function
static void PostErrorProc(CPOP3Account *ActualAccount, void *ParamToBadConnect, uint32_t POP3PluginParam, BOOL UseSSL);

// Checks POP3 account and stores all info to account. It deletes old mails=> synchro
// WhichTemp- pointer to strucure containing needed information
void MIR_CDECL SynchroPOP3(CheckParam *WhichTemp);

// Deletes mails from POP3 server
// WhichTemp- structure containing needed information (queued messages to delete)
// Function deletes from memory queue in WhichTemp structure
void __cdecl DeleteMailsPOP3(void *param);

// Function makes readable message about error. It sends it back to YAMN, so YAMN then
// can show it to the message window
wchar_t *MIR_CDECL GetErrorString(DWORD Code);

// Function deletes string allocated in GetErrorString
void MIR_CDECL DeleteErrorString(LPVOID String);

// Extracts info from result of POP3's STAT command
// stream- source string
// len- length of source string
// mboxsize- adreess to integer, that receives size of mailbox
// mails- adreess to integer, that receives number of mails
void ExtractStat(char *stream, int *mboxsize, int *mails);

// Extracts mail ID on mailbox
// stream- source string
// len- length of source string
// queue- address of first message, where first ID will be stored
void ExtractUIDL(char *stream, int len, HYAMNMAIL queue);

// Extracts mail size on mailbox
// stream- source string
// len- length of source string
// queue- address of first message, where size of message #1 will be stored
void ExtractList(char *stream, int len, HYAMNMAIL queue);

void ExtractMail(char *stream, int len, HYAMNMAIL queue);

YAMN_PROTOIMPORTFCN POP3ProtocolFunctions =
{
	CreatePOP3Account,
	DeletePOP3Account,
	StopPOP3Account,
	WritePOP3Options,
	ReadPOP3Options,
	SynchroPOP3,
	SynchroPOP3,
	SynchroPOP3,
	DeleteMailsPOP3,
	GetErrorString,
	nullptr,
	DeleteErrorString,
	WritePOP3Accounts,
	nullptr,
	UnLoadPOP3,
};

YAMN_MAILIMPORTFCN POP3MailFunctions =
{
	CreatePOP3Mail,
	nullptr,
	nullptr,
	nullptr,
};

YAMN_PROTOPLUGIN *POP3Plugin = nullptr;

YAMN_PROTOREGISTRATION POP3ProtocolRegistration =
{
	"POP3 protocol (internal)",
	__VERSION_STRING_DOTS,
	__COPYRIGHT,
	__DESCRIPTION,
	__AUTHORWEB,
};

static CMStringW wszFileName;

HANDLE RegisterNLClient(char *name);

// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------

CPOP3Account::CPOP3Account()
{
	// NOTE! This constructor constructs CAccount structure. If your plugin is not internal,
	// you will need these constructors. All you need is in Account.cpp. Just copy to your source code
	// constructor and destructor of CAccount.
	UseInternetFree = CreateEvent(nullptr, FALSE, TRUE, nullptr);
	AbilityFlags = YAMN_ACC_BROWSE | YAMN_ACC_POPUP;

	SetStatusFcn(this, TranslateT("Disconnected"));
}

CPOP3Account::~CPOP3Account()
{
	CloseHandle(UseInternetFree);
}

CAccount* MIR_CDECL CreatePOP3Account(YAMN_PROTOPLUGIN *)
{
	// First, we should check whether CAccountVersion matches.
	// But this is internal plugin, so YAMN's CAccount structure and our CAccount structure are
	// the same, so we do not need to test version. Otherwise, if CAccount version does not match
	// in your plugin, you should return NULL, like this:
	// 	if (CAccountVersion != YAMN_ACCOUNTVERSION) return NULL;

	// Now it is needed to construct our POP3 account and return its handle
	return new CPOP3Account();
}

void MIR_CDECL DeletePOP3Account(CAccount *Which)
{
	delete (CPOP3Account *)Which;
}

void MIR_CDECL StopPOP3Account(CAccount *Which)
{
	((CPOP3Account *)Which)->Client.Stopped = TRUE;
	if (((CPOP3Account *)Which)->Client.NetClient != nullptr)			// we should inform also network client. Usefull only when network client implements this feature
		((CPOP3Account *)Which)->Client.NetClient->Stopped = TRUE;
}

// This function is like main function for POP3 internal protocol
int RegisterPOP3Plugin(WPARAM, LPARAM)
{
	// Register new pop3 user in netlib
	if (nullptr == (hNetLib = RegisterNLClient("YAMN (POP3)"))) {
		UnLoadPOP3(nullptr);
		return 0;
	}

	// First, we register this plugin
	// it is quite impossible this function returns zero (failure) as YAMN and internal plugin structre versions are the same
	POP3ProtocolRegistration.Name = Translate("POP3 protocol (internal)");
	POP3ProtocolRegistration.Description = Translate(__DESCRIPTION);
	if (nullptr == (POP3Plugin = RegisterProtocolPlugin(&POP3ProtocolRegistration)))
		return 0;

	// Next we set our imported functions for YAMN
	if (!SetProtocolPluginFcnImportFcn(POP3Plugin, &POP3ProtocolFunctions, &POP3MailFunctions))
		return 0;

	// Then, we read all mails for accounts.
	// You must first register account, before using this function as YAMN must use CreatePOP3Account function to add new accounts
	// But if CreatePOP3Account is not implemented (equals to NULL), YAMN creates account as YAMN's standard CAccount *
	wszFileName = GetFileName(L"pop3");

	switch (AddAccountsFromFile(POP3Plugin, wszFileName)) {
	case EACC_FILEVERSION:
		MessageBox(nullptr, TranslateT("Found new version of account book, not compatible with this version of YAMN."), TranslateT("YAMN (internal POP3) read error"), MB_OK);
		wszFileName.Empty();
		return 0;
	case EACC_FILECOMPATIBILITY:
		MessageBox(nullptr, TranslateT("Error reading account file. Account file corrupted."), TranslateT("YAMN (internal POP3) read error"), MB_OK);
		wszFileName.Empty();
		return 0;
	case EACC_ALLOC:
		MessageBox(nullptr, TranslateT("Memory allocation error while data reading"), TranslateT("YAMN (internal POP3) read error"), MB_OK);
		wszFileName.Empty();
		return 0;
	case EACC_SYSTEM:
		if (ERROR_FILE_NOT_FOUND != GetLastError()) {
			wchar_t temp[1024] = { 0 };
			mir_snwprintf(temp, L"%s\n%s", TranslateT("Reading file error. File already in use?"), wszFileName.c_str());
			MessageBox(nullptr, temp, TranslateT("YAMN (internal POP3) read error"), MB_OK);
			wszFileName.Empty();
			return 0;
		}
		break;
	}

	for (CAccount *pAcc = POP3Plugin->FirstAccount; pAcc; pAcc = pAcc->Next) {
		pAcc->hContact = 0;
		for (auto &hContact : Contacts(YAMN_DBMODULE)) {
			if (g_plugin.getMStringA(hContact, "Id") == pAcc->Name) {
				pAcc->hContact = hContact;
				break;
			}
		}

		pAcc->RefreshContact();
	}

	return 0;
}

DWORD MIR_CDECL UnLoadPOP3(void *)
{
	Netlib_CloseHandle(hNetLib); hNetLib = nullptr;
	return 1;
}

// Function writes POP3 accounts using YAMN exported functions
DWORD MIR_CDECL WritePOP3Accounts()
{
	uint32_t ReturnValue = WriteAccountsToFile(POP3Plugin, wszFileName);
	if (ReturnValue == EACC_SYSTEM) {
		wchar_t temp[1024] = { 0 };
		mir_snwprintf(temp, L"%s\n%s", TranslateT("Error while copying data to disk occurred. Is file in use?"), wszFileName.c_str());
		MessageBox(nullptr, temp, TranslateT("POP3 plugin - write file error"), MB_OK);
	}

	return ReturnValue;
}

DWORD MIR_CDECL WritePOP3Options(HANDLE File, CAccount *Which)
{
	DWORD WrittenBytes;
	uint32_t Ver = POP3_FILEVERSION;

	if ((!WriteFile(File, (char *)&Ver, sizeof(uint32_t), &WrittenBytes, nullptr)) ||
		(!WriteFile(File, (char *)&((CPOP3Account *)Which)->CP, sizeof(uint16_t), &WrittenBytes, nullptr)))
		return EACC_SYSTEM;
	return 0;
}

DWORD MIR_CDECL ReadPOP3Options(CAccount *Which, char **Parser, char *End)
{
	uint32_t Ver;
	#ifdef DEBUG_FILEREAD
	wchar_t Debug[256];
	#endif
	Ver = *(uint32_t *)(*Parser);
	(*Parser) += sizeof(uint32_t);
	if (*Parser >= End)
		return EACC_FILECOMPATIBILITY;
	if (Ver != POP3_FILEVERSION)
		return EACC_FILECOMPATIBILITY;

	((CPOP3Account *)Which)->CP = *(uint16_t *)(*Parser);
	(*Parser) += sizeof(uint16_t);
	if (*Parser >= End)
		return EACC_FILECOMPATIBILITY;
	#ifdef DEBUG_FILEREAD
	mir_snwprintf(Debug, L"CodePage: %d, remaining %d chars", ((CPOP3Account *)Which)->CP, End - *Parser);
	MessageBox(NULL, Debug, L"debug", MB_OK);
	#endif
	return 0;
}

HYAMNMAIL MIR_CDECL CreatePOP3Mail(CAccount *Account)
{
	HYAMNMAIL NewMail;
	// First, we should check whether MAILDATA matches.
	// But this is internal plugin, so YAMN's MAILDATA structure and our MAILDATA structure are
	// the same, so we do not need to test version. Otherwise, if MAILDATA version does not match
	// in your plugin, you should return NULL, like this:
	// 	if (MailDataVersion != YAMN_MAILDATAVERSION) return NULL;

	// Now it is needed to construct our POP3 account and return its handle
	if (nullptr == (NewMail = new YAMNMAIL))
		return nullptr;

	if (nullptr == (NewMail->MailData = new CMailData())) {
		delete NewMail;
		return nullptr;
	}
	NewMail->MailData->CP = ((CPOP3Account *)Account)->CP;
	return (HYAMNMAIL)NewMail;
}

static void SetContactStatus(CAccount *account, int status)
{
	if (account->NewMailN.Flags & YAMN_ACC_CONT)
		g_plugin.setWord(account->hContact, "Status", status);
}

static void PostErrorProc(CPOP3Account *ActualAccount, void *ParamToBadConnection, uint32_t POP3PluginParam, BOOL UseSSL)
{
	// We create new structure, that we pass to bad connection dialog procedure. This procedure next calls YAMN imported fuction
	// from POP3 protocol to determine the description of error. We can describe error from our error code structure, because later,
	// when YAMN calls our function, it passes us our error code. This is pointer to structure for POP3 protocol in fact. 
	POP3_ERRORCODE *ErrorCode = new POP3_ERRORCODE();
	ErrorCode->SSL = UseSSL;
	ErrorCode->AppError = ActualAccount->SystemError;
	ErrorCode->POP3Error = ActualAccount->Client.POP3Error;
	ErrorCode->NetError = ActualAccount->Client.NetClient->NetworkError;
	ErrorCode->SystemError = ActualAccount->Client.NetClient->SystemError;
	
	// if it was normal YAMN call (force check or so on)
	if (POP3PluginParam == 0) {
		try {
			char *DataRX = ActualAccount->Client.Quit();
			if (DataRX != nullptr)
				free(DataRX);
		}
		catch (...) {
		}
		// We always close connection if error occured
		try {
			ActualAccount->Client.NetClient->Disconnect();
		}
		catch (...) {
		}

		SetStatusFcn(ActualAccount, TranslateT("Disconnected"));
	}

	if ((ActualAccount->BadConnectN.Flags & YAMN_ACC_MSG) || (ActualAccount->BadConnectN.Flags & YAMN_ACC_ICO) || (ActualAccount->BadConnectN.Flags & YAMN_ACC_POP))
		RunBadConnection(ActualAccount, (UINT_PTR)ErrorCode, ParamToBadConnection);

	// if it was normal YAMN call
	if (POP3PluginParam == 0)
		SetEvent(ActualAccount->UseInternetFree);
}

// Checks POP3 account and synchronizes it
void MIR_CDECL SynchroPOP3(CheckParam *WhichTemp)
{
	CPop3Client *MyClient;
	HYAMNMAIL NewMails = nullptr, MsgQueuePtr = nullptr;
	char *DataRX = nullptr;
	int mboxsize, msgs, i;
	SYSTEMTIME now;
	BOOL UsingInternet = FALSE;

	ptrA ServerName, ServerLogin, ServerPasswd;
	uint32_t ServerPort, Flags, NFlags, NNFlags;

	auto *ActualAccount = (CPOP3Account *)WhichTemp->AccountParam;
	auto CheckFlags = WhichTemp->Flags;
	delete WhichTemp;

	SCGuard sc(ActualAccount->UsingThreads);
	{
		SReadGuard sra(ActualAccount->AccountAccessSO);
		if (!sra.Succeeded())
			return;

		MyClient = &ActualAccount->Client;
		// Now, copy all needed information about account to local variables, so ActualAccount is not blocked in read mode during all connection process, which can last for several minutes.
		ServerName = mir_strdup(ActualAccount->Server->Name);
		ServerPort = ActualAccount->Server->Port;
		Flags = ActualAccount->Flags;
		ServerLogin = mir_strdup(ActualAccount->Server->Login);
		ServerPasswd = mir_strdup(ActualAccount->Server->Passwd);
		NFlags = ActualAccount->NewMailN.Flags;
		NNFlags = ActualAccount->NoNewMailN.Flags;
	}
	{
		SCGuard scq(ActualAccount->InternetQueries);
		WaitForSingleObject(ActualAccount->UseInternetFree, INFINITE);
	}
	
	// OK, we enter the "use internet" section. But after we start communication, we can test if we did not enter the "use internet" section only for the reason,
	// that previous thread release the internet section because this account has stop signal (we stop account and there are 2 threads: one communicating,
	// the second one waiting for network access- the first one ends because we want to stop account, this one is released, but should be stopped as well).
	if (!ActualAccount->AbleToWork) {
		SetEvent(ActualAccount->UseInternetFree);
		return;
	}
	UsingInternet = TRUE;

	GetLocalTime(&now);
	ActualAccount->SystemError = 0; // now we can use internet for this socket. First, clear errorcode.
	try {
		SetContactStatus(ActualAccount, ID_STATUS_OCCUPIED);

		// if we are already connected, we have open session (another thread left us open session), so we don't need to login
		// note that connected state without logging cannot occur, because if we close session, we always close socket too 
		// (we must close socket is the right word :))
		if ((MyClient->NetClient == nullptr) || !MyClient->NetClient->Connected()) {
			SetStatusFcn(ActualAccount, TranslateT("Connecting to server"));

			DataRX = MyClient->Connect(ServerName, ServerPort, Flags & YAMN_ACC_SSL23, Flags & YAMN_ACC_NOTLS);
			char *timestamp = nullptr;

			if (DataRX != nullptr) {
				if (Flags & YAMN_ACC_APOP) {
					char *lpos = strchr(DataRX, '<');
					char *rpos = strchr(DataRX, '>');
					if (lpos && rpos && rpos > lpos) {
						int sz = (int)(rpos - lpos + 2);
						timestamp = new char[sz];
						memcpy(timestamp, lpos, sz - 1);
						timestamp[sz - 1] = '\0';
					}
				}
				free(DataRX);
				DataRX = nullptr;
			}

			SetStatusFcn(ActualAccount, TranslateT("Entering POP3 account"));

			if (Flags & YAMN_ACC_APOP) {
				DataRX = MyClient->APOP(ServerLogin, ServerPasswd, timestamp);
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				delete[] timestamp;
			}
			else {
				DataRX = MyClient->User(ServerLogin);
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				DataRX = MyClient->Pass(ServerPasswd);
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
			}
		}
		SetStatusFcn(ActualAccount, TranslateT("Searching for new mail message"));

		DataRX = MyClient->Stat();

		ExtractStat(DataRX, &mboxsize, &msgs);

		if (DataRX != nullptr)
			free(DataRX);
		DataRX = nullptr;
		for (i = 0; i < msgs; i++) {
			if (!i)
				MsgQueuePtr = NewMails = CreateAccountMail(ActualAccount);
			else {
				MsgQueuePtr->Next = CreateAccountMail(ActualAccount);
				MsgQueuePtr = MsgQueuePtr->Next;
			}
			if (MsgQueuePtr == nullptr) {
				ActualAccount->SystemError = EPOP3_QUEUEALLOC;
				throw (uint32_t)ActualAccount->SystemError;
			}
		}

		if (msgs) {
			DataRX = MyClient->List();
			ExtractList(DataRX, MyClient->NetClient->Rcv, NewMails);
			if (DataRX != nullptr)
				free(DataRX);

			DataRX = MyClient->Uidl();
			ExtractUIDL(DataRX, MyClient->NetClient->Rcv, NewMails);

			if (DataRX != nullptr)
				free(DataRX);
			DataRX = nullptr;
		}
		{
			SWriteGuard swm(ActualAccount->MessagesAccessSO);
			if (!swm.Succeeded())
				throw (uint32_t)(ActualAccount->SystemError = EACC_STOPPED);

			ActualAccount->LastChecked = now;
			for (MsgQueuePtr = (HYAMNMAIL)ActualAccount->Mails; MsgQueuePtr != nullptr; MsgQueuePtr = MsgQueuePtr->Next) {
				if (MsgQueuePtr->Flags & YAMN_MSG_BODYREQUESTED) {
					HYAMNMAIL NewMsgsPtr = nullptr;
					for (NewMsgsPtr = (HYAMNMAIL)NewMails; NewMsgsPtr != nullptr; NewMsgsPtr = NewMsgsPtr->Next) {
						if (!mir_strcmp(MsgQueuePtr->ID, NewMsgsPtr->ID)) {
							wchar_t accstatus[512];
							mir_snwprintf(accstatus, TranslateT("Reading body %s"), NewMsgsPtr->ID);
							SetStatusFcn(ActualAccount, accstatus);
							DataRX = MyClient->Top(MsgQueuePtr->Number, 100);
							if (DataRX == nullptr)
								continue;

							char *Temp = DataRX;
							while ((Temp < DataRX + MyClient->NetClient->Rcv) && (WS(Temp) || ENDLINE(Temp)))
								Temp++;

							if (OKLINE(DataRX))
								for (Temp = DataRX; (Temp < DataRX + MyClient->NetClient->Rcv) && (!ENDLINE(Temp)); Temp++);
							while ((Temp < DataRX + MyClient->NetClient->Rcv) && ENDLINE(Temp))
								Temp++;

							// delete all the headers of the old mail MsgQueuePtr->MailData->TranslatedHeader
							struct CMimeItem *TH = MsgQueuePtr->MailData->TranslatedHeader;
							if (TH) for (; MsgQueuePtr->MailData->TranslatedHeader != nullptr;) {
								TH = TH->Next;
								if (MsgQueuePtr->MailData->TranslatedHeader->name != nullptr)
									delete[] MsgQueuePtr->MailData->TranslatedHeader->name;
								if (MsgQueuePtr->MailData->TranslatedHeader->value != nullptr)
									delete[] MsgQueuePtr->MailData->TranslatedHeader->value;
								delete MsgQueuePtr->MailData->TranslatedHeader;
								MsgQueuePtr->MailData->TranslatedHeader = TH;
							}

							TranslateHeaderFcn(Temp, MyClient->NetClient->Rcv - (Temp - DataRX), &MsgQueuePtr->MailData->TranslatedHeader);

							MsgQueuePtr->Flags |= YAMN_MSG_BODYRECEIVED;

							if (DataRX != nullptr)
								free(DataRX);
							DataRX = nullptr;
							break;
						}
					}
				}
			}

			SynchroMessagesFcn(ActualAccount, (HYAMNMAIL *)&ActualAccount->Mails, nullptr, (HYAMNMAIL *)&NewMails, nullptr);		// we get only new mails on server!
		}

		for (MsgQueuePtr = (HYAMNMAIL)ActualAccount->Mails; MsgQueuePtr != nullptr; MsgQueuePtr = MsgQueuePtr->Next) {
			if ((MsgQueuePtr->Flags & YAMN_MSG_BODYREQUESTED) && (MsgQueuePtr->Flags & YAMN_MSG_BODYRECEIVED)) {
				MsgQueuePtr->Flags &= ~YAMN_MSG_BODYREQUESTED;
				if (MsgQueuePtr->MsgWindow)
					SendMessage(MsgQueuePtr->MsgWindow, WM_YAMN_CHANGECONTENT, 0, 0);
			}
		}

		for (msgs = 0, MsgQueuePtr = NewMails; MsgQueuePtr != nullptr; MsgQueuePtr = MsgQueuePtr->Next, msgs++);			// get number of new mails

		try {
			wchar_t accstatus[512];

			for (i = 0, MsgQueuePtr = NewMails; MsgQueuePtr != nullptr; i++) {
				BOOL autoretr = (ActualAccount->Flags & YAMN_ACC_BODY) != 0;
				DataRX = MyClient->Top(MsgQueuePtr->Number, autoretr ? 100 : 0);
				mir_snwprintf(accstatus, TranslateT("Reading new mail messages (%d%% done)"), 100 * i / msgs);
				SetStatusFcn(ActualAccount, accstatus);

				if (DataRX == nullptr)
					continue;

				char *Temp = DataRX;
				while ((Temp < DataRX + MyClient->NetClient->Rcv) && (WS(Temp) || ENDLINE(Temp)))
					Temp++;

				if (OKLINE(DataRX))
					for (Temp = DataRX; (Temp < DataRX + MyClient->NetClient->Rcv) && (!ENDLINE(Temp)); Temp++);
				while ((Temp < DataRX + MyClient->NetClient->Rcv) && ENDLINE(Temp))
					Temp++;

				TranslateHeaderFcn(Temp, MyClient->NetClient->Rcv - (Temp - DataRX), &MsgQueuePtr->MailData->TranslatedHeader);

				#ifdef DEBUG_DECODE
				mir_writeLogA(DecodeFile, "</New mail>\n");
				#endif
				MsgQueuePtr->Flags |= YAMN_MSG_NORMALNEW;
				if (autoretr)
					MsgQueuePtr->Flags |= YAMN_MSG_BODYRECEIVED;

				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;

				// MsgQueuePtr->MailData->Body=MyClient->Retr(MsgQueuePtr->Number);

				MsgQueuePtr = MsgQueuePtr->Next;

			}

			{
				SWriteGuard swm(ActualAccount->MessagesAccessSO);
				if (!swm.Succeeded())
					throw (uint32_t)ActualAccount->SystemError == EACC_STOPPED;

				if (ActualAccount->Mails == nullptr)
					ActualAccount->Mails = NewMails;
				else {
					ActualAccount->LastMail = ActualAccount->LastChecked;
					AppendQueueFcn((HYAMNMAIL)ActualAccount->Mails, NewMails);
				}
			}

			// 	we are going to delete mails having SPAM flag level3 and 4 (see m_mails.h) set
			// 	Delete mails from server. Here we should not be in write access for account's mails
			DeleteMailsPOP3(new DeleteParam(ActualAccount, POP3_DELETEFROMCHECK));

			// 	if there is no waiting thread for internet connection close it
			// 	else leave connection open
			if (0 == ActualAccount->InternetQueries.GetNumber()) {
				DataRX = MyClient->Quit();
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				MyClient->NetClient->Disconnect();

				SetStatusFcn(ActualAccount, TranslateT("Disconnected"));
			}

			UsingInternet = FALSE;
			SetEvent(ActualAccount->UseInternetFree);

			ActualAccount->LastSChecked = ActualAccount->LastChecked;
			ActualAccount->LastSynchronised = ActualAccount->LastChecked;
		}
		catch (...) {
			throw;			// go to the main exception handling
		}

		YAMN_MAILBROWSERPARAM Param = { ActualAccount, NFlags, NNFlags, 0 };
		if (CheckFlags & YAMN_FORCECHECK)
			Param.nnflags |= YAMN_ACC_POP;  // if force check, show popup anyway and if mailbrowser was opened, do not close
		Param.nnflags |= YAMN_ACC_MSGP;    // do not close browser if already open
		RunMailBrowser(&Param);

		SetContactStatus(ActualAccount, ActualAccount->isCounting ? ID_STATUS_ONLINE : ID_STATUS_OFFLINE);
	}
	#ifdef DEBUG_COMM
	catch (uint32_t ErrorCode)
		#else
	catch (uint32_t)
		#endif
	{
		if (ActualAccount->Client.POP3Error == EPOP3_STOPPED)
			ActualAccount->SystemError = EACC_STOPPED;
		#ifdef DEBUG_COMM
		mir_writeLogA(CommFile, "ERROR: %x\n", ErrorCode);
		#endif
		{
			SWriteGuard swm(ActualAccount->MessagesAccessSO);
			if (swm.Succeeded())
				ActualAccount->LastChecked = now;
		}

		DeleteMessagesToEndFcn(ActualAccount, NewMails);

		if (DataRX != nullptr)
			free(DataRX);
		DataRX = nullptr;
		switch (ActualAccount->SystemError) {
		case EACC_QUEUEALLOC:
		case EACC_STOPPED:
			ActualAccount->Client.NetClient->Disconnect();
			break;
		default:
			PostErrorProc(ActualAccount, 0, 0, MyClient->SSL);	// it closes internet connection too
		}

		if (UsingInternet)	// if our thread still uses internet
			SetEvent(ActualAccount->UseInternetFree);

		SetContactStatus(ActualAccount, ID_STATUS_NA);
	}

	#ifdef DEBUG_COMM
	mir_writeLogA(CommFile, "</--------Communication-------->\n");
	#endif
}

void __cdecl DeleteMailsPOP3(void *param)
{
	DeleteParam *WhichTemp = (DeleteParam *)param;

	HYAMNMAIL DeleteMails, NewMails = nullptr, MsgQueuePtr = nullptr;
	int mboxsize = 0, msgs = 0, i;

	ptrA ServerName, ServerLogin, ServerPasswd;
	uint32_t ServerPort, Flags, NFlags, NNFlags;

	// copy address of structure from calling thread to stack of this thread
	CPOP3Account *ActualAccount = (CPOP3Account *)WhichTemp->AccountParam;
	int POP3PluginParam = WhichTemp->Flags;
	delete WhichTemp;

	SCGuard sc(ActualAccount->UsingThreads);

	CPop3Client *MyClient;
	{
		SReadGuard sra(ActualAccount->AccountAccessSO);
		if (!sra.Succeeded())
			return;

		// if there's no mail for deleting, return
		if (nullptr == (DeleteMails = CreateNewDeleteQueueFcn((HYAMNMAIL)ActualAccount->Mails))) {
			// We do not wait for free internet when calling from SynchroPOP3. It is because UseInternetFree is blocked
			if (POP3_DELETEFROMCHECK != POP3PluginParam) {
				YAMN_MAILBROWSERPARAM Param = { ActualAccount, YAMN_ACC_MSGP, YAMN_ACC_MSGP, 0 };		// Just update the window
				RunMailBrowser(&Param);
			}
			return;
		}

		MyClient = &ActualAccount->Client;

		// Now, copy all needed information about account to local variables, so ActualAccount is not blocked in read mode during all connection process, which can last for several minutes.
		ServerName = mir_strdup(ActualAccount->Server->Name);
		ServerPort = ActualAccount->Server->Port;
		Flags = ActualAccount->Flags;
		ServerLogin = mir_strdup(ActualAccount->Server->Login);
		ServerPasswd = mir_strdup(ActualAccount->Server->Passwd);
		NFlags = ActualAccount->NewMailN.Flags;
		NNFlags = ActualAccount->NoNewMailN.Flags;
	}
	{
		SCGuard scq(ActualAccount->InternetQueries);	// This is POP3-internal SCOUNTER, we set another thread wait for this account to be connected to inet
		if (POP3_DELETEFROMCHECK != POP3PluginParam)	// We do not wait for free internet when calling from SynchroPOP3. It is because UseInternetFree is blocked
			WaitForSingleObject(ActualAccount->UseInternetFree, INFINITE);
	}

	BOOL UsingInternet = TRUE;

	try {
		SetContactStatus(ActualAccount, ID_STATUS_OCCUPIED);
		#ifdef DEBUG_COMM
		mir_writeLogA(CommFile, "<--------Communication-------->\n");
		#endif
		if ((MyClient->NetClient == nullptr) || !MyClient->NetClient->Connected()) {
			SetStatusFcn(ActualAccount, TranslateT("Connecting to server"));

			char *DataRX = MyClient->Connect(ServerName, ServerPort, Flags & YAMN_ACC_SSL23, Flags & YAMN_ACC_NOTLS);

			char *timestamp = nullptr;
			if (DataRX != nullptr) {
				if (ActualAccount->Flags & YAMN_ACC_APOP) {
					char *lpos = strchr(DataRX, '<');
					char *rpos = strchr(DataRX, '>');
					if (lpos && rpos && rpos > lpos) {
						int sz = (int)(rpos - lpos + 2);
						timestamp = new char[sz];
						memcpy(timestamp, lpos, sz - 1);
						timestamp[sz - 1] = '\0';
					}
				}
				free(DataRX);
				DataRX = nullptr;
			}
			SetStatusFcn(ActualAccount, TranslateT("Entering POP3 account"));

			if (ActualAccount->Flags & YAMN_ACC_APOP) {
				DataRX = MyClient->APOP(ServerLogin, ServerPasswd, timestamp);
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				delete[] timestamp;
			}
			else {
				DataRX = MyClient->User(ServerLogin);
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				DataRX = MyClient->Pass(ServerPasswd);
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
			}
		}

		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<--------Deleting requested mails-------->\n");
		#endif
		if (POP3_DELETEFROMCHECK != POP3PluginParam)	// We do not need to get mails on server as we have already it from check function
		{
			SetStatusFcn(ActualAccount, TranslateT("Deleting requested mails"));

			char *DataRX = MyClient->Stat();

			#ifdef DEBUG_DECODE
			mir_writeLogA(DecodeFile, "<Extracting stat>\n");
			#endif
			ExtractStat(DataRX, &mboxsize, &msgs);
			#ifdef DEBUG_DECODE
			mir_writeLogA(DecodeFile, "<MailBoxSize>%d</MailBoxSize>\n", mboxsize);
			mir_writeLogA(DecodeFile, "<Msgs>%d</Msgs>\n", msgs);
			mir_writeLogA(DecodeFile, "</Extracting stat>\n");
			#endif
			if (DataRX != nullptr)
				free(DataRX);
			DataRX = nullptr;
			for (i = 0; i < msgs; i++) {
				if (!i)
					MsgQueuePtr = NewMails = CreateAccountMail(ActualAccount);
				else {
					MsgQueuePtr->Next = CreateAccountMail(ActualAccount);
					MsgQueuePtr = MsgQueuePtr->Next;
				}
				if (MsgQueuePtr == nullptr) {
					ActualAccount->SystemError = EPOP3_QUEUEALLOC;
					throw (uint32_t)ActualAccount->SystemError;
				}
			}

			if (msgs) {
				#ifdef DEBUG_DECODE
				mir_writeLogA(DecodeFile, "<Extracting UIDL>\n");
				#endif
				DataRX = MyClient->Uidl();
				ExtractUIDL(DataRX, MyClient->NetClient->Rcv, NewMails);
				#ifdef DEBUG_DECODE
				mir_writeLogA(DecodeFile, "</Extracting UIDL>\n");
				#endif
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				// we get "new mails" on server (NewMails will contain all mails on server not found in DeleteMails)
				// but also in DeleteMails we get only those, which are still on server with their responsable numbers
				SynchroMessagesFcn(ActualAccount, (HYAMNMAIL *)&DeleteMails, nullptr, (HYAMNMAIL *)&NewMails, nullptr);
			}
		}
		else SetStatusFcn(ActualAccount, TranslateT("Deleting spam"));

		{
			SWriteGuard swm(ActualAccount->MessagesAccessSO);
			if (!swm.Succeeded())
				throw (uint32_t)EACC_STOPPED;

			if (msgs || POP3_DELETEFROMCHECK == POP3PluginParam) {
				for (i = 0, MsgQueuePtr = DeleteMails; MsgQueuePtr != nullptr; i++) {
					if (!(MsgQueuePtr->Flags & YAMN_MSG_VIRTUAL)) {	// of course we can only delete real mails, not virtual
						char *DataRX = MyClient->Dele(MsgQueuePtr->Number);
						HYAMNMAIL Temp = MsgQueuePtr->Next;
						if (POP3_FOK == MyClient->AckFlag) { // if server answers that mail was deleted
							DeleteMessageFromQueueFcn((HYAMNMAIL *)&DeleteMails, MsgQueuePtr);
							HYAMNMAIL DeletedMail = FindMessageByIDFcn((HYAMNMAIL)ActualAccount->Mails, MsgQueuePtr->ID);
							if ((MsgQueuePtr->Flags & YAMN_MSG_MEMDELETE)) { // if mail should be deleted from memory (or disk)
								DeleteMessageFromQueueFcn((HYAMNMAIL *)&ActualAccount->Mails, DeletedMail);	// remove from queue
								DeleteAccountMail(POP3Plugin, DeletedMail);
							}
							else { // else mark it only as "deleted mail"
								DeletedMail->Flags |= (YAMN_MSG_VIRTUAL | YAMN_MSG_DELETED);
								DeletedMail->Flags &= ~(YAMN_MSG_NEW | YAMN_MSG_USERDELETE | YAMN_MSG_AUTODELETE);	// clear "new mail"
							}
							delete   MsgQueuePtr->MailData;
							delete[] MsgQueuePtr->ID;
							delete   MsgQueuePtr;
						}
						MsgQueuePtr = Temp;

						if (DataRX != nullptr)
							free(DataRX);
						DataRX = nullptr;
					}
					else MsgQueuePtr = MsgQueuePtr->Next;
				}

				if (NewMails != nullptr)
					// 	in ActualAccount->Mails we have all mails stored before calling this function
					// 	in NewMails we have all mails not found in DeleteMails (in other words: we performed new ID checking and we
					// 	stored all mails found on server, then we deleted the ones we wanted to delete in this function
					// 	and NewMails queue now contains actual state of mails on server). But we will not use NewMails as actual state, because NewMails does not contain header data (subject, from...)
					// 	We perform deleting from ActualAccount->Mails: we remove from original queue (ActualAccount->Mails) all deleted mails
					SynchroMessagesFcn(ActualAccount, (HYAMNMAIL *)&ActualAccount->Mails, nullptr, (HYAMNMAIL *)&NewMails, nullptr);
				// 	Now ActualAccount->Mails contains all mails when calling this function except the ones, we wanted to delete (these are in DeleteMails)
				// 	And in NewMails we have new mails (if any)
				else if (POP3_DELETEFROMCHECK != POP3PluginParam) {
					DeleteMessagesToEndFcn(ActualAccount, (HYAMNMAIL)ActualAccount->Mails);
					ActualAccount->Mails = nullptr;
				}
			}
			else {
				DeleteMessagesToEndFcn(ActualAccount, (HYAMNMAIL)ActualAccount->Mails);
				ActualAccount->Mails = nullptr;
			}
		}

		#ifdef DEBUG_DECODE     	
		mir_writeLogA(DecodeFile, "</--------Deleting requested mails-------->\n");
		#endif

		// 	TODO: now, we have in NewMails new mails. If NewMails is not NULL, we found some new mails, so Checking for new mail should be performed
		// 	now, we do not call CheckPOP3

		// 	if there is no waiting thread for internet connection close it
		// 	else leave connection open
		// 	if this functin was called from SynchroPOP3, then do not try to disconnect 
		if (POP3_DELETEFROMCHECK != POP3PluginParam) {
			YAMN_MAILBROWSERPARAM Param = { ActualAccount, NFlags, YAMN_ACC_MSGP, 0 };
			RunMailBrowser(&Param);

			if (0 == ActualAccount->InternetQueries.GetNumber()) {
				char *DataRX = MyClient->Quit();
				if (DataRX != nullptr)
					free(DataRX);
				DataRX = nullptr;
				MyClient->NetClient->Disconnect();

				SetStatusFcn(ActualAccount, TranslateT("Disconnected"));
			}

			UsingInternet = FALSE;
			SetEvent(ActualAccount->UseInternetFree);
		}
		SetContactStatus(ActualAccount, ActualAccount->isCounting ? ID_STATUS_ONLINE : ID_STATUS_OFFLINE);
	}
	#ifdef DEBUG_COMM
	catch (uint32_t ErrorCode)
		#else
	catch (uint32_t)
		#endif
	{
		if (ActualAccount->Client.POP3Error == EPOP3_STOPPED)
			ActualAccount->SystemError = EACC_STOPPED;
		#ifdef DEBUG_COMM
		mir_writeLogA(CommFile, "ERROR %x\n", ErrorCode);
		#endif

		switch (ActualAccount->SystemError) {
		case EACC_QUEUEALLOC:
		case EACC_STOPPED:
			ActualAccount->Client.NetClient->Disconnect();
			break;
		default:
			PostErrorProc(ActualAccount, 0, POP3PluginParam, MyClient->SSL);	// it closes internet connection too
		}

		if (UsingInternet && (POP3_DELETEFROMCHECK != POP3PluginParam))	// if our thread still uses internet and it is needed to release internet
			SetEvent(ActualAccount->UseInternetFree);
	}

	DeleteMessagesToEndFcn(ActualAccount, NewMails);
	DeleteMessagesToEndFcn(ActualAccount, DeleteMails);

	#ifdef DEBUG_COMM
	mir_writeLogA(CommFile, "</--------Communication-------->\n");
	#endif

	// 	WriteAccounts();
	return;
}

void ExtractStat(char *stream, int *mboxsize, int *mails)
{
	char *finder = stream;
	while (WS(finder) || ENDLINE(finder)) finder++;
	if (ACKLINE(finder)) {
		SkipNonSpaces(finder);
		SkipSpaces(finder);
	}
	if (1 != sscanf(finder, "%d", mails))
		throw (uint32_t)EPOP3_STAT;

	SkipNonSpaces(finder);
	SkipSpaces(finder);
	if (1 != sscanf(finder, "%d", mboxsize))
		throw (uint32_t)EPOP3_STAT;
}
void ExtractMail(char *stream, int len, HYAMNMAIL queue)
{
	char *finder = stream;
	char *finderend;
	int msgnr, i;
	HYAMNMAIL queueptr = queue;

	while (WS(finder) || ENDLINE(finder)) finder++;
	while (!ACKLINE(finder)) finder++;
	while (!ENDLINE(finder)) finder++;			// now we at the end of first ack line
	while (finder <= (stream + len)) {
		while (ENDLINE(finder)) finder++;		// go to the new line
		if (DOTLINE(finder + 1))					// at the end of stream
			break;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Message>\n");
		#endif
		SkipSpaces(finder);			// jump whitespace
		if (1 != sscanf(finder, "%d", &msgnr))
			throw (uint32_t)EPOP3_UIDL;

		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Nr>%d</Nr>\n", msgnr);
		#endif

		SkipNonSpaces(finder);
		SkipSpaces(finder);
		finderend = finder + 1;
		while (!WS(finderend) && !ENDLINE(finderend)) finderend++;
		queueptr->ID = new char[finderend - finder + 1];
		for (i = 0; finder != finderend; finder++, i++)
			queueptr->MailData->Body[i] = *finder;
		queueptr->MailData->Body[i] = 0;				// ends string
		queueptr->Number = msgnr;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<ID>%s</ID>\n", queueptr->MailData->Body);
		mir_writeLogA(DecodeFile, "</Message>\n");
		#endif
		queueptr = queueptr->Next;
		while (!ENDLINE(finder)) finder++;
	}
}

void ExtractUIDL(char *stream, int len, HYAMNMAIL queue)
{
	char *finder = stream;
	char *finderend;
	int msgnr, i;
	HYAMNMAIL queueptr = queue;

	while (WS(finder) || ENDLINE(finder)) finder++;
	while (!ACKLINE(finder)) finder++;
	while (!ENDLINE(finder)) finder++;			// now we at the end of first ack line
	while (finder <= (stream + len)) {
		while (ENDLINE(finder)) finder++;		// go to the new line
		if (DOTLINE(finder + 1))					// at the end of stream
			break;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Message>\n");
		#endif
		SkipSpaces(finder);
		if (1 != sscanf(finder, "%d", &msgnr))
			throw (uint32_t)EPOP3_UIDL;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Nr>%d</Nr>\n", msgnr);
		#endif
		// 		for (i=1,queueptr=queue;(queueptr->Next != NULL) && (i<msgnr);queueptr=queueptr->Next,i++);
		// 		if (i != msgnr)
		// 			throw (uint32_t)EPOP3_UIDL;
		SkipNonSpaces(finder);
		SkipSpaces(finder);
		finderend = finder + 1;
		while (!WS(finderend) && !ENDLINE(finderend)) finderend++;
		queueptr->ID = new char[finderend - finder + 1];
		for (i = 0; finder != finderend; finder++, i++)
			queueptr->ID[i] = *finder;
		queueptr->ID[i] = 0;				// ends string
		queueptr->Number = msgnr;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<ID>%s</ID>\n", queueptr->ID);
		mir_writeLogA(DecodeFile, "</Message>\n");
		#endif
		queueptr = queueptr->Next;
		while (!ENDLINE(finder)) finder++;
	}
}

void ExtractList(char *stream, int len, HYAMNMAIL queue)
{
	char *finder = stream;
	char *finderend;
	int msgnr, i;
	HYAMNMAIL queueptr;

	while (WS(finder) || ENDLINE(finder)) finder++;
	while (!ACKLINE(finder)) finder++;
	while (!ENDLINE(finder)) finder++;			// now we at the end of first ack line
	while (finder <= (stream + len)) {
		while (ENDLINE(finder)) finder++;		// go to the new line
		if (DOTLINE(finder + 1))				// at the end of stream
			break;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Message>\n", NULL, 0);
		#endif
		SkipSpaces(finder);
		if (1 != sscanf(finder, "%d", &msgnr))		// message nr.
			throw (uint32_t)EPOP3_LIST;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Nr>%d</Nr>\n", msgnr);
		#endif

		for (i = 1, queueptr = queue; (queueptr->Next != nullptr) && (i < msgnr); queueptr = queueptr->Next, i++);
		if (i != msgnr)
			throw (uint32_t)EPOP3_LIST;

		SkipNonSpaces(finder);
		SkipSpaces(finder);			// jump whitespace
		finderend = finder + 1;
		if (1 != sscanf(finder, "%u", &queueptr->MailData->Size))
			throw (uint32_t)EPOP3_LIST;
		#ifdef DEBUG_DECODE
		mir_writeLogA(DecodeFile, "<Nr>%d</Nr>\n", queueptr->MailData->Size);
		#endif
		while (!ENDLINE(finder)) finder++;
	}
}

wchar_t *MIR_CDECL GetErrorString(DWORD Code)
{
	static wchar_t *POP3Errors[] =
	{
		LPGENW("Memory allocation error."),		// memory allocation
		LPGENW("Account is about to be stopped."),	// stop account
		LPGENW("Cannot connect to POP3 server."),
		LPGENW("Cannot allocate memory for received data."),
		LPGENW("Cannot login to POP3 server."),
		LPGENW("Bad user or password."),
		LPGENW("Server does not support APOP authorization."),
		LPGENW("Error while executing POP3 command."),
		LPGENW("Error while executing POP3 command."),
		LPGENW("Error while executing POP3 command."),
	};

	static wchar_t *NetlibErrors[] =
	{
		LPGENW("Cannot connect to server with NetLib."),
		LPGENW("Cannot send data."),
		LPGENW("Cannot receive data."),
		LPGENW("Cannot allocate memory for received data."),
	};

	static wchar_t *SSLErrors[] =
	{
		LPGENW("OpenSSL not loaded."),
		LPGENW("Windows socket 2.0 init failed."),
		LPGENW("DNS lookup error."),
		LPGENW("Error while creating base socket."),
		LPGENW("Error connecting to server with socket."),
		LPGENW("Error while creating SSL structure."),
		LPGENW("Error connecting socket with SSL."),
		LPGENW("Server rejected connection with SSL."),
		LPGENW("Cannot write SSL data."),
		LPGENW("Cannot read SSL data."),
		LPGENW("Cannot allocate memory for received data."),
	};

	wchar_t *ErrorString = new wchar_t[ERRORSTR_MAXLEN];
	POP3_ERRORCODE *ErrorCode = (POP3_ERRORCODE *)(UINT_PTR)Code;

	mir_snwprintf(ErrorString, ERRORSTR_MAXLEN, TranslateT("Error %d-%d-%d-%d:"), ErrorCode->AppError, ErrorCode->POP3Error, ErrorCode->NetError, ErrorCode->SystemError);
	if (ErrorCode->POP3Error)
		mir_snwprintf(ErrorString, ERRORSTR_MAXLEN, L"%s\n%s", ErrorString, TranslateW(POP3Errors[ErrorCode->POP3Error - 1]));
	if (ErrorCode->NetError) {
		if (ErrorCode->SSL)
			mir_snwprintf(ErrorString, ERRORSTR_MAXLEN, L"%s\n%s", ErrorString, TranslateW(SSLErrors[ErrorCode->NetError - 1]));
		else
			mir_snwprintf(ErrorString, ERRORSTR_MAXLEN, L"%s\n%s", ErrorString, TranslateW(NetlibErrors[ErrorCode->NetError - 4]));
	}

	return ErrorString;
}

void MIR_CDECL DeleteErrorString(LPVOID String)
{
	delete (char *)String;
}