summaryrefslogtreecommitdiff
path: root/plugins/!NotAdopted/mDynDNS/mDynDNS.cpp
blob: 855377055276f986a47369238366dac10737ba69 (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
/*
Komentarz
*/
#include "mDynDNS.h"
#include "Windowsx.h"

// Prototypes ///////////////////////////////////////////////////////////////////////////

//Information gathered by Miranda, displayed in the plugin pane of the Option Dialog
PLUGININFOEX pluginInfo={
	sizeof(PLUGININFOEX),
	__PLUGIN_NAME,		// altered here and on file listing, so as not to match original
	PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM),
	__DESC,
	__AUTHOR,
	__AUTHOREMAIL,
	__COPYRIGHT,
	__AUTHORWEB,
	0,		//not transient
	MIID_MDYNDNS
};

HINSTANCE hInst;			//!< Global reference to the application
HANDLE hNetlibUser;			//!< Netlib Register User
HANDLE hKAThread;
HICON hDynDnsIcon;			//!< DynDNS icon

int hLangpack;

BOOL closing	= FALSE;
int delay		= 10;		//!< requirement by DynDns (Client must not query CheckIP more than once every 10 minutes.)

void DoIPCheck();
static INT_PTR CALLBACK mdyndns_optsdlgproc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
static INT_PTR CALLBACK DnsPopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
static void DnsPopupPreview(HWND hwndDlg);
unsigned long __stdcall KeepAliveThread(LPVOID param);
void WakeThread(HANDLE hThread);
void NetlibInit(void);
void NetlibClose(void);
static int SystemPShutdown(WPARAM wParam, LPARAM lParam);
static int OnModulesLoaded(WPARAM wParam, LPARAM lParam);
static int mdyndns_options_init(WPARAM wParam, LPARAM lParam);


// Functions ////////////////////////////////////////////////////////////////////////////

/** DLL entry point
* Required to store the instance handle
*/
extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
	hInst = hinstDLL;
	return TRUE;
}

/** Called by Miranda to get the information associated to this plugin.
* It only returns the PLUGININFO structure, without any test on the version
* @param mirandaVersion The version of the application calling this function
*/
extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
{
	pluginInfo.cbSize = sizeof(PLUGININFOEX);
	return &pluginInfo;
}

extern "C" __declspec(dllexport) const MUUID MirandaInterfaces[] = { MIID_MDYNDNS, MIID_LAST };

/** Initializes the services provided and the link to those needed
* Called when the plugin is loaded into Miranda
*/
extern "C" int __declspec(dllexport) Load()
{
    closing = FALSE;
	
	// set first delay for IP check on miranda start
	DWORD dwTime, dwDiff, dwLastTs;
	dwLastTs	= db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_LASTIPCHECK, 0);
	dwTime		= (DWORD)time(0);
	dwDiff		= (dwTime - dwLastTs);
	if (dwDiff < (DWORD)(delay * 60)) delay = ((delay * 60 - dwDiff + 59) / 60) + delay;

	HookEvent( ME_SYSTEM_MODULESLOADED, OnModulesLoaded);
	HookEvent( ME_OPT_INITIALISE, mdyndns_options_init);
	//HookEvent( ME_SYSTEM_OKTOEXIT, OkToExit);
	HookEvent( ME_SYSTEM_PRESHUTDOWN, SystemPShutdown);

	hDynDnsIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDI_ICON1));
	//hDynDnsIcon = LoadImage(hInst,MAKEINTRESOURCE(IDI_ICON1),IMAGE_ICON,0,0,LR_DEFAULTSIZE);
	return 0;
}

/** Prepare the plugin to stop
* Called by Miranda when it will exit or when the plugin gets deselected
*/
extern "C" int __declspec(dllexport) Unload(void)
{
	UnhookEvent(SystemPShutdown);
	DestroyIcon(hDynDnsIcon);

 	return 0;
}

static int SystemPShutdown(WPARAM wParam, LPARAM lParam)
{
    closing = TRUE;
	UnhookEvent(OnModulesLoaded);
	UnhookEvent(mdyndns_options_init);

	// close Thread
	WakeThread(hKAThread);
	WaitForSingleObject(hKAThread, INFINITE);
	CloseHandle(hKAThread);

	// Netlib unregister
	NetlibClose();

	return 0;
}

unsigned long __stdcall KeepAliveThread(LPVOID param)
{
	Thread_Push(0, 0);
	while(!Miranda_Terminated()) 
	{
		SleepEx(60000*(delay-9), TRUE);		//Wait 60sec util check ( + extra sec on mirandastart)
		if (closing) break;
		delay = 10;
		DoIPCheck();
		if (closing) break;
		SleepEx(60000*(delay-1), TRUE);		//Wait 10 min until next check
	}
	Thread_Pop();
	return 0;
}

void WINAPI NullAPC (DWORD_PTR dwData) { }

void WakeThread(HANDLE hThread)
{
	QueueUserAPC(NullAPC, hThread, 0);
}

// Netlib
void NetlibInit(void) 
{
	NETLIBUSER nlu = {0};
	nlu.cbSize = sizeof(nlu);
	nlu.szSettingsModule = (char*)PLUGNAME;
	nlu.szDescriptiveName = Translate("mDynDNS HTTP connections");
	nlu.flags = NUF_OUTGOING|NUF_HTTPCONNS;			//|NUF_NOHTTPSOPTION;
	hNetlibUser = (HANDLE)CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM)&nlu);
}

void NetlibClose(void) 
{
	Netlib_CloseHandle(hNetlibUser);
}

// Plugin
static int OnModulesLoaded(WPARAM wParam, LPARAM lParam)
{
	// Netlib register
	NetlibInit();

	// create Thread
	DWORD tid;
	hKAThread = CreateThread(0, 0, KeepAliveThread, 0, 0, &tid);

	// install known modules strings to database
	db_set_s(NULL, "KnownModules", PLUGNAME, PLUGNAME);

	return 0;
}

static int PluginMenuCommand(WPARAM wParam,LPARAM lParam)
{
	return 0;
}
// Options Page : Init
static int mdyndns_options_init(WPARAM wParam, LPARAM lParam)
{
	char title[64];
    OPTIONSDIALOGPAGE odp = { 0 };
	strncpy(title, PLUGNAME, sizeof(title));

    odp.cbSize = sizeof(odp);
    odp.position = 1003000;
    odp.hInstance = hInst;
    odp.pszGroup = Translate("Services");
    odp.pszTemplate = MAKEINTRESOURCE(IDD_OPT_MDYNDNS);
    odp.pszTitle = title;
    odp.pfnDlgProc = mdyndns_optsdlgproc;
    odp.flags = ODPF_BOLDGROUPS;
    Options_AddPage(wParam, &odp);

    if (ServiceExists(MS_POPUP_ADDPOPUP)) {
		ZeroMemory(&odp,sizeof(odp));
		odp.cbSize = sizeof(odp);
		odp.position = 100000000;
		odp.hInstance = hInst;
		odp.pszGroup = Translate("Popups");
		odp.pszTemplate = MAKEINTRESOURCE(IDD_OPT_POPUPS);
		odp.pszTitle = title; //PLUGNAME;
		odp.pfnDlgProc = DnsPopupsDlgProc;
		odp.flags=ODPF_BOLDGROUPS;
		//odp.nIDBottomSimpleControl = 0;
		Options_AddPage(wParam,&odp);
	}

    return 0;
}

static INT_PTR CALLBACK mdyndns_optsdlgproc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) 
	{
		case WM_INITDIALOG:
		{
			DBVARIANT dbv;
 
			if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_USERNAME, &dbv)) {
				SetDlgItemText(hwndDlg, IDC_USERNAME, dbv.pszVal);
				db_free(&dbv);
			}

			if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_PASSWORD, &dbv)) {
				CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal) + 1, (LPARAM) dbv.pszVal);
				SetDlgItemText(hwndDlg, IDC_PASSWORD, dbv.pszVal);
				db_free(&dbv);
			}

			if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_DOMAIN, &dbv)) {
				SetDlgItemText(hwndDlg, IDC_DOMAIN, dbv.pszVal);
				db_free(&dbv);
			}
			TranslateDialogDefault(hwndDlg);
		}
		break;
		case WM_COMMAND:
		{
			switch (LOWORD(wParam)) 
			{
				case IDC_DOMAIN:
				case IDC_USERNAME:
				case IDC_PASSWORD:
					if ((HWND)lParam==GetFocus() && HIWORD(wParam)==EN_CHANGE)
						SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;
				case IDC_CREATEACCOUNT:
					CallService(MS_UTILS_OPENURL, 1, (LPARAM)URL_DYNDNS);
				break;
				default:
					SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
				break;
			}
		}
		break;
		case WM_NOTIFY:
		{
			switch (((LPNMHDR) lParam)->code) 
			{
				case PSN_APPLY:
				{
					char str[128];

					// Write Dyndns username
					GetDlgItemText(hwndDlg, IDC_USERNAME, str, sizeof(str));
					db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_USERNAME, str);
					// Write Dyndns Password
					GetDlgItemText(hwndDlg, IDC_PASSWORD, str, sizeof(str));
					CallService(MS_DB_CRYPT_ENCODESTRING, sizeof(str), (LPARAM) str);
					db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_PASSWORD, str);
					// Write Domain Alias
					GetDlgItemText(hwndDlg, IDC_DOMAIN, str, sizeof(str));
					db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_DOMAIN, str);
				}
				break;
			}
		}
		break;
	}
	return FALSE;
}

static INT_PTR CALLBACK DnsPopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
		case WM_INITDIALOG: {

			BYTE delayMode, colorMode;
			// general
			CheckDlgButton(hwndDlg, IDC_ENABLEPOPUP, db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPENAB, TRUE));
			CheckDlgButton(hwndDlg, IDC_ENABLEUPDATEPOPUP, db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPUPD, TRUE));
			// color
			SendDlgItemMessage(hwndDlg, IDC_COLOR_BKG, CPM_SETCOLOUR, 0, db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_POPUPBACK, POPUP_DEFAULT_COLORBKG));
			SendDlgItemMessage(hwndDlg, IDC_COLOR_TXT, CPM_SETCOLOUR, 0, db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_POPUPTEXT, POPUP_DEFAULT_COLORTXT));
			colorMode = db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPCOLM, 0);
			if (colorMode==1) {
				CheckDlgButton(hwndDlg, IDC_COLOR_CUSTOM, TRUE);
			} else {
				if (colorMode==2) {
					CheckDlgButton(hwndDlg, IDC_COLOR_OS, TRUE);
				} else {
					CheckDlgButton(hwndDlg, IDC_COLOR_POPUP, TRUE);
				}
			EnableWindow(GetDlgItem(hwndDlg, IDC_COLOR_BKG), IsDlgButtonChecked(hwndDlg, IDC_COLOR_CUSTOM) == BST_CHECKED ? TRUE : FALSE);
			EnableWindow(GetDlgItem(hwndDlg, IDC_COLOR_TXT), IsDlgButtonChecked(hwndDlg, IDC_COLOR_CUSTOM) == BST_CHECKED ? TRUE : FALSE);
			}
			// delay
			delayMode = db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPDELM, 0);
			if (delayMode==1) {
				CheckDlgButton(hwndDlg, IDC_DELAY_CUSTOM, TRUE);
			} else if (delayMode==2) {
				CheckDlgButton(hwndDlg, IDC_DELAY_PERMANENT, TRUE);
			} else {
				CheckDlgButton(hwndDlg, IDC_DELAY_POPUP, TRUE);
			}
			SetDlgItemInt(hwndDlg, IDC_DELAY, db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_POPUPDELAY, 4), FALSE);
			EnableWindow(GetDlgItem(hwndDlg, IDC_DELAY), IsDlgButtonChecked(hwndDlg, IDC_DELAY_CUSTOM) == BST_CHECKED ? TRUE : FALSE);
			TranslateDialogDefault(hwndDlg);
		} // end: case WM_INITDIALOG
		break;

		case WM_COMMAND: {
			switch (LOWORD(wParam)) {
				case IDC_ENABLEPOPUP:
				case IDC_ENABLEUPDATEPOPUP:
				// color
				case IDC_COLOR_CUSTOM:
					case IDC_COLOR_TXT:
					case IDC_COLOR_BKG:
				case IDC_COLOR_OS:
				case IDC_COLOR_POPUP:
					EnableWindow(GetDlgItem(hwndDlg, IDC_COLOR_BKG), IsDlgButtonChecked(hwndDlg, IDC_COLOR_CUSTOM) == BST_CHECKED ? TRUE : FALSE);
					EnableWindow(GetDlgItem(hwndDlg, IDC_COLOR_TXT), IsDlgButtonChecked(hwndDlg, IDC_COLOR_CUSTOM) == BST_CHECKED ? TRUE : FALSE);
					// enable the 'apply' button
					SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
					break;
				// delay
				case IDC_DELAY:
					if (Edit_GetModify(GetDlgItem(hwndDlg, IDC_DELAY))) {
						// enable the 'apply' button
						SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
					}
					break;
				case IDC_DELAY_CUSTOM:
				case IDC_DELAY_PERMANENT:
				case IDC_DELAY_POPUP:
					EnableWindow(GetDlgItem(hwndDlg, IDC_DELAY), IsDlgButtonChecked(hwndDlg, IDC_DELAY_CUSTOM) == BST_CHECKED ? TRUE : FALSE);
					// enable the 'apply' button
					SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
					break;
				case IDC_PREVIEW: {
					DnsPopupPreview (hwndDlg);
				} // end: case IDC_PREVIEW:
			} //end: switch (LOWORD(wParam))
		} //end: WM_COMMAND
		break;

		case WM_NOTIFY:	{
			switch (((LPNMHDR) lParam)->code) {
				case PSN_APPLY: {
					BYTE delayMode, colorMode;
					// general
					db_set_b	(NULL, PLUGNAME, MDYNDNS_KEY_POPUPENAB,	(BYTE) IsDlgButtonChecked(hwndDlg, IDC_ENABLEPOPUP));
					db_set_b	(NULL, PLUGNAME, MDYNDNS_KEY_POPUPUPD,	(BYTE) IsDlgButtonChecked(hwndDlg, IDC_ENABLEUPDATEPOPUP));
					// color
					db_set_dw	(NULL, PLUGNAME, MDYNDNS_KEY_POPUPBACK,	(DWORD) SendDlgItemMessage(hwndDlg,IDC_COLOR_BKG,CPM_GETCOLOUR,0,0));
					db_set_dw	(NULL, PLUGNAME, MDYNDNS_KEY_POPUPTEXT,	(DWORD) SendDlgItemMessage(hwndDlg,IDC_COLOR_TXT,CPM_GETCOLOUR,0,0));
					if (IsDlgButtonChecked(hwndDlg, IDC_COLOR_CUSTOM)) {
						colorMode=1;
					} else if (IsDlgButtonChecked(hwndDlg, IDC_COLOR_OS)) {
						colorMode=2;
					} else {
						colorMode=0;
					}
					db_set_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPCOLM, colorMode);
					// delay
					db_set_dw	(NULL, PLUGNAME, MDYNDNS_KEY_POPUPDELAY,(DWORD) GetDlgItemInt(hwndDlg,IDC_DELAY, NULL, FALSE));
					if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_CUSTOM)) {
						delayMode=1;
					} else if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_PERMANENT)) {
						delayMode=2;
					} else {
						delayMode=0;
					}
					db_set_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPDELM, delayMode);
				} //PSN_APPLY end
				break;
			} //switch (((LPNMHDR) lParam)->code): end
		} //WM_NOTIFY end
		break;
	} // switch (msg): end
	return FALSE;
}

// Popup
static void DnsPopupPreview(HWND hwndDlg)
{
	POPUPDATA ppd;

	ZeroMemory(&ppd, sizeof(ppd));
	ppd.lchContact = NULL;
	ppd.PluginWindowProc = NULL;
	ppd.PluginData=NULL;
	strcat(ppd.lpzContactName,PLUGNAME);
	strcat(ppd.lpzText,Translate("Your IP on dyndns.org account, has been updated."));
	// icon
	ppd.lchIcon = hDynDnsIcon;
	//ppd.lchIcon = LoadSkinnedIcon(SKINICON_OTHER_MIRANDA);
	// color
	if (IsDlgButtonChecked(hwndDlg, IDC_COLOR_CUSTOM)) {
		ppd.colorBack = SendDlgItemMessage(hwndDlg,IDC_COLOR_BKG,CPM_GETCOLOUR,0,0);
		ppd.colorText = SendDlgItemMessage(hwndDlg,IDC_COLOR_TXT,CPM_GETCOLOUR,0,0);
	} else if (IsDlgButtonChecked(hwndDlg, IDC_COLOR_OS)) {
		ppd.colorBack = GetSysColor(COLOR_BTNFACE);
		ppd.colorText = GetSysColor(COLOR_WINDOWTEXT);
	} else {
		ppd.colorBack = ppd.colorText = 0;
	}

	if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
		if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_CUSTOM)) {
			ppd.iSeconds = (int) GetDlgItemInt(hwndDlg,IDC_DELAY, NULL, FALSE);
		} else if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_PERMANENT)) {
			ppd.iSeconds = -1;
		} else {
			ppd.iSeconds = 0;
		}
		CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
	}
	else if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
		CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
	}
}


static void DnsPopup(BOOL err,char *mesg)
{
	POPUPDATA ppd;
	char *lpzContactName;

	if (!db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPENAB, TRUE)) {
		return;
	}
	   
    if (err && !db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPUPD, TRUE)) {
       return;
    }
    
    if ( err == TRUE )
	   lpzContactName = MDYNDNS_ERROR_TITLE;
    else
       lpzContactName = PLUGNAME; 
	
	ZeroMemory(&ppd, sizeof(ppd));
	ppd.lchContact = NULL;
	ppd.PluginWindowProc = NULL;
	ppd.PluginData=NULL;
	lstrcpy(ppd.lpzContactName, lpzContactName);
	lstrcpy(ppd.lpzText, mesg);	
	// icon
	ppd.lchIcon = hDynDnsIcon;
	//ppd.lchIcon = LoadSkinnedIcon(SKINICON_OTHER_MIRANDA);
	// color
	switch (db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPCOLM, 0)) {
		case MODE_OWN1:
			ppd.colorBack = db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_POPUPBACK, 0);
			ppd.colorText = db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_POPUPTEXT, 0);
			break;
		case MODE_OWN2:
			ppd.colorBack = GetSysColor(COLOR_BTNFACE);
			ppd.colorText = GetSysColor(COLOR_WINDOWTEXT);
			break;
		case MODE_POPUP:
		default:
			ppd.colorBack = ppd.colorText = 0;
			break;
	}

	if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
		// delay (Custom delay time in seconds. -1 means "forever", 0 means "default time")
		switch (db_get_b(NULL, PLUGNAME, MDYNDNS_KEY_POPUPDELM, 0)) {
			case MODE_OWN1:
				ppd.iSeconds = db_get_dw(NULL, PLUGNAME, MDYNDNS_KEY_POPUPDELAY, 4);
				break;
			case MODE_OWN2:
				ppd.iSeconds = -1;
				break;
			case MODE_POPUP:
			default:
				ppd.iSeconds = 0;
				break;
		}
		CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
	}
	else if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
		CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
	}
}


// Error handler
static int PrintError(int err_num)
{
	char *err = "Unknown Error.";

	switch (err_num)
	{
	//Failed to register NetLib user
	case 1:
		err = "Netlib Error.";
		break;
	//Failed to connect with Netlib.
	case 2:
		err = "Netlib Connection Error.";
		break;
	//Error in parsing server response.
	case 3:
		err = "Error in parsing server respose.";
		break;
	case 4:
		err = "Miranda mDynDns plugin has been blocked on server for not following specifications - it won't work anymore :(";
		break;
	case 5:
		err = "The username or password specified in options are incorrect. Please check your account details.";
		break;
	case 6:
		err = "The domain alias specified in options has incorrect format. Should be 'yourdomain.dyndns.org'.";
		break;
	case 7:
		err = "The domain alias specified in options does not exist. Please check your account details.";
		break;
	case 8:
		err = "The domain alias specified in options exists, but you are not it's owner.";
		break;
	case 9:
		err = "DNS error encountered.";
		break;
	case 10:
		err = "There is a serious problem with the dyndns.org server";
		break;
	case 11:
		err = "There was a serious problem with updating domain alias to it's previous IP. In order not to get abuse the mDynDns plugin will stop working. To get additional information please refer to the readme.txt.";
		break;
	case 12:
		err = "The specified hostname has been blocked because of update abuse. In order not to get situation worse the mDynDns plugin will stop working. To get additional information please refer to the readme.txt.";
		break;
	case 13:
		err = "Due to some errors mDynDNS plugin has been turned off to prevent blocking on server.";
		break;
	default:
		err = "Unknown Error.";
		break;
	}
	err = Translate(err);

	if(ServiceExists( MS_POPUP_ADDPOPUP ))
		DnsPopup(TRUE, err);
	else
		MessageBox(NULL,err,MDYNDNS_ERROR_TITLE,MB_OK);
	return 1;
}

// DynDNS stuff
char *GetHostIP(char *name)
{
	DBVARIANT dbv;
	char *Ip = (char*)malloc(17);	//static char Ip[17];
	// get IP from DB
	if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_LASTIP, &dbv)) {
		strcpy(Ip,dbv.pszVal);
		db_free(&dbv);
		return Ip;
	}
	// get IP from DNS query if no IP store in DB
	char hostname[25];
	WSADATA wsaData;
	struct hostent *pHostEnt;
	struct sockaddr_in tmpSockAddr;
	char FAR *pszIp;

	WSAStartup(MAKEWORD(2,0),&wsaData);
	strcpy(hostname,name);
	pHostEnt = gethostbyname(hostname);
	if(!pHostEnt){
		PrintError(2);
		strcpy (Ip, (char*)MDYNDNS_ERROR_CODE);
		return Ip;
	}
	memcpy(&tmpSockAddr.sin_addr,pHostEnt->h_addr,pHostEnt->h_length);
	pszIp = inet_ntoa(tmpSockAddr.sin_addr);
	if (!pszIp) PrintError(5);
	else strcpy (Ip, pszIp);
	WSACleanup();
	db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_LASTIP, Ip);
	return Ip;
}

void Block_plugin(BOOL blok)
{
	if(blok == TRUE)
		db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_BLOCKED, MDYNDNS_BLOCK_CODE);
	else
		db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_BLOCKED, MDYNDNS_UNBLOCK_CODE);
}

void UpdateIP(char *ip_num)
{
	DBVARIANT dbv;
	NETLIBHTTPREQUEST nlhr = {0};
	NETLIBHTTPREQUEST *nlreply;

	char szUrl[500] = "";
	int ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0, count;
	char username[64] = "";
	char passwd[64] = "";
	char domain[128] = "";
	char str[128] = "";
	char encd[128] = "";
	char auth[150] = "";
	char newip[128] = "";
	char return_code[256] = "";
	char *notf = ""; 
	char szAgent[100] = "";
	char szVersion[16];

	if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_USERNAME, &dbv))
	{
		strcpy(username,dbv.pszVal);
		db_free(&dbv);
	}
	else
		return;

	if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_PASSWORD, &dbv))
	{
		CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal) + 1, (LPARAM) dbv.pszVal);
		strcpy(passwd,dbv.pszVal);
		db_free(&dbv);
	}
	else
		return;

	if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_DOMAIN, &dbv))
	{
		strcpy(domain,dbv.pszVal);
		db_free(&dbv);
	}
	else
		return;

	count = sscanf(ip_num , "%d.%d.%d.%d", &ip1, &ip2, &ip3, &ip4);
	if (count != 4 || ip1 <= 0 || ip1 > 255 || ip2 < 0 || ip2 > 255 ||
		ip3 < 0 || ip3 > 255 || ip4 < 0 || ip4 > 255 )
		return;

	strcat(str, username);
	strcat(str, ":");
	strcat(str, passwd);

	mir_base64_encodebuf((PBYTE)str, strlen(str), encd, 128);

	strcat(auth, "Basic ");
	strcat(auth, encd);

	strcat(szUrl,"http://members.dyndns.org/nic/update?");    
	strcat(szUrl,"hostname=");
	strcat(szUrl,domain);
	strcat(szUrl,"&myip=");
	strcat(szUrl,ip_num);	
	strcat(szUrl,"&wildcard=NOCHG");
	strcat(szUrl,"&mx=NOCHG");
	strcat(szUrl,"&backmx=NOCHG");

	strcat(szAgent,"MirandaIM - ");
	strcat(szAgent,__PLUGIN_NAME);
	strcat(szAgent," plugin - ");
	///strcat(szAgent,CreateVersionStringPluginEx(&pluginInfo, szVersion)); // TODO: fix this
          	
	// initialize the netlib request
 	nlhr.cbSize					= sizeof(nlhr);
    nlhr.requestType			= REQUEST_GET;
    nlhr.flags					= NLHRF_DUMPASTEXT;
    nlhr.szUrl					= (char*)szUrl;
    nlhr.headersCount			= 3;
	nlhr.headers=(NETLIBHTTPHEADER*)mir_alloc(sizeof(NETLIBHTTPHEADER)*nlhr.headersCount);
    nlhr.headers[0].szName		= "Host";
	nlhr.headers[0].szValue		= "members.dyndns.org";
	nlhr.headers[1].szName		= "Authorization";
    nlhr.headers[1].szValue		= auth;		//Basic base-64-authorization
	nlhr.headers[2].szName		= "User-Agent";
    nlhr.headers[2].szValue		= szAgent;	//__USER_AGENT_STRING;    
  
	nlreply	= (NETLIBHTTPREQUEST *) CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM) hNetlibUser, (LPARAM) & nlhr);    
	if( nlreply )
	{
      if( nlreply->resultCode >= 200 && nlreply->resultCode < 300 ) 
		{
			nlreply->pData[nlreply->dataLength] = 0;// make sure its null terminated
			strcpy(return_code,nlreply->pData);
	        if (strncmp (return_code,"badagent",8) == 0)
               PrintError(4);
            if (strncmp (return_code,"badauth",7) == 0)
               PrintError(5);
            if (strncmp (return_code,"good",4) == 0)
            {
				db_set_s(NULL, PLUGNAME, MDYNDNS_KEY_LASTIP, ip_num);
				notf = "Your IP on dyndns.org account, has been updated.";
				notf = Translate(notf) ;        
				DnsPopup(FALSE,notf);
            }
            if (strncmp (return_code,"nochg",5) == 0)
            {
               PrintError(11);
               Block_plugin(TRUE);
            }
            if (strncmp (return_code,"notfqdn",7) == 0)
               PrintError(6);
            if (strncmp (return_code,"nohost",6) == 0)
               PrintError(7);
            if (strncmp (return_code,"!yours",6) == 0)
               PrintError(8);
            if (strncmp (return_code,"abuse",5) == 0)
            {
               PrintError(12);
               Block_plugin(TRUE);
            }
            if (strncmp (return_code,"dnserr",6) == 0)
               PrintError(9);
            if (strncmp (return_code,"911",3) == 0)
               PrintError(10);		
        }
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM) nlreply);
	}
	mir_free(nlhr.headers);
}

char *GetExternIP()
{
	if( !hNetlibUser ) {
		PrintError(1);
		return 0;
	}
	char szAgent[100] = "";
	char szVersion[16];
	char *ip_str = (char*)malloc(17);
	char szUrl[ 500 ] = DYN_DNS_SERVER;
	int ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0, count;
	bool result = FALSE;
	NETLIBHTTPREQUEST nlhr = {0};
	NETLIBHTTPREQUEST *nlreply;
	ZeroMemory(&nlhr, sizeof(nlhr));

	strcat(szAgent,"MirandaIM - ");
	strcat(szAgent,__PLUGIN_NAME);
	strcat(szAgent," plugin - ");
	///strcat(szAgent,CreateVersionStringPluginEx(&pluginInfo, szVersion)); // TODO: fix this

	// initialize the netlib request
	nlhr.cbSize					= sizeof(nlhr);
	nlhr.requestType			= REQUEST_GET;
	nlhr.flags					= NLHRF_DUMPASTEXT;
	nlhr.szUrl					= (char*)szUrl;
    nlhr.headersCount			= 1;
	nlhr.headers=(NETLIBHTTPHEADER*)mir_alloc(sizeof(NETLIBHTTPHEADER)*nlhr.headersCount);
	nlhr.headers[0].szName		= "User-Agent";
    nlhr.headers[0].szValue		= szAgent;

	nlreply = (NETLIBHTTPREQUEST *) CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM) hNetlibUser, (LPARAM) &nlhr);
	if( nlreply && nlreply->resultCode >= 200 && nlreply->resultCode < 300 ) {
		nlreply->pData[nlreply->dataLength] = 0;// make sure its null terminated
		count = sscanf(nlreply->pData , RESPONSE_PATTERN, &ip1, &ip2, &ip3, &ip4);
		if (count != 4 || ip1 <= 0 || ip1 > 255 || ip2 < 0 || ip2 > 255 || ip3 < 0 || ip3 > 255 || ip4 < 0 || ip4 > 255 ){
			PrintError(3);
		}
		else {
			sprintf(ip_str, "%d.%d.%d.%d", ip1, ip2, ip3, ip4);
			result = TRUE;
		}
	}
	else {
		PrintError(2);
	}
	db_set_dw(NULL, PLUGNAME, MDYNDNS_KEY_LASTIPCHECK, (DWORD)time(0));
	mir_free(nlhr.headers);
	if (!result) free(ip_str);
	if (nlreply) CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM) nlreply);
	return result ? ip_str : 0;
}

void DoIPCheck()
{
	DBVARIANT dbv;
	char blok[3] = "";
	char *myIP = "";
	char *myExtIP = "";
	char *notf = "";
	char domain[128] = "";

	if (closing == TRUE){
		return ;
	}
	if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_DOMAIN, &dbv)) {
		strcpy(domain,dbv.pszVal);
		db_free(&dbv);
	}
	else {
		return ;
	}

	if (!db_get(NULL, PLUGNAME, MDYNDNS_KEY_BLOCKED, &dbv)) {
		strcpy(blok,dbv.pszVal);
		db_free(&dbv);
		if(blok == MDYNDNS_BLOCK_CODE){
			PrintError(13);
			return ;
		}
	}

	myIP = GetHostIP(domain);
	if(myIP && (blok != MDYNDNS_BLOCK_CODE) && (myIP != MDYNDNS_ERROR_CODE)){
		myExtIP = GetExternIP();
		if(myExtIP){
			if(strncmp(myIP,myExtIP,15) == 0 ){
				; //Do nothing
			}
			else {
				UpdateIP(myExtIP);
			}
		free(myExtIP);
		}
	}
	if(myIP) free(myIP);
}