summaryrefslogtreecommitdiff
path: root/plugins/!NotAdopted/WinPopup/messenger.cpp
blob: b73bd4b23ab1e78826b04fb14ec4edd2b6c4c5d9 (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
/*

WinPopup Protocol plugin for Miranda IM.

Copyright (C) 2004-2010 Nikolay Raspopov

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "stdafx.h"
#include "winpopup_proto.h"
#include "services.h"
#include "messenger.h"
#include "processapi.h"
#include "messagebox.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

static bool IsMessengerRunning()
{
	bool found = false;
	HANDLE h = CreateMailslot (_T("\\\\.\\mailslot\\") MESSENGER_MAIL, 0, 0, NULL);
	if (h == INVALID_HANDLE_VALUE) {
		if (GetLastError () == ERROR_ALREADY_EXISTS)
			found = true;
		else
			LOG ("IsMessengerRunning() error 0x%08x", GetLastError ());
	} else
		CloseHandle (h);		
	return found;
}

messenger pluginMessenger;			// Ïðèåì/îòïðàâêà ñîîáùåíèé ÷åðåç Messenger

messenger::messenger () :
	m_MonitorTerm (NULL),
	m_Monitor (NULL),
	m_ID (0),
	m_bMSMessengerStopped (false)
{
}

messenger::~messenger ()
{
	Destroy ();
}

bool messenger::Create(BOOL start)
{
	if ( pluginOS.dwPlatformId != VER_PLATFORM_WIN32_NT )
		return false;

	// Êîñâåííàÿ ïðîâåðêà, ÷òî Messenger çàïóùåí
	bool messngr = IsMessengerRunning();
	if ( start )
	{
		if ( ! messngr )
			Start ();
	}
	else
	{
		if ( messngr )
			Stop ();
	}

	m_ID = GetProcessId (_T("csrss.exe"));
	LOG ( ( m_ID ? "Messenger host process CSRSS.EXE found : PID %u(%08x)" :
		"Messenger host process CSRSS.EXE not found" ), m_ID, m_ID );

	// Çàïóñê ñêàíåðà êîíòàêòîâ
	if (m_MonitorTerm)
		ResetEvent (m_MonitorTerm);
	else
		m_MonitorTerm = CreateEvent (NULL, TRUE, FALSE, NULL);

	if (!m_Monitor)
		m_Monitor = (HANDLE)mir_forkthread( MonitorThread, this );

	return (m_Monitor != NULL);
}

void messenger::AskForDestroy()
{
	if (m_MonitorTerm)
		SetEvent (m_MonitorTerm);
}

void messenger::Destroy ()
{
	if (pluginOS.dwPlatformId != VER_PLATFORM_WIN32_NT)
		return;

	AskForDestroy();

	if (m_Monitor)
	{
		if (WaitForSingleObject (m_Monitor, ALMOST_INFINITE) == WAIT_TIMEOUT)
		{
			LOG("Terminate Messenger monitor!");
			TerminateThread (m_Monitor, 0);
		}
		m_Monitor = NULL;
	}

	if (m_MonitorTerm)
	{
		CloseHandle (m_MonitorTerm);
		m_MonitorTerm = NULL;
	}

	// Çàïóñê "Ñëóæáû Ñîîáùåíèé", åñëè åå îñòàíàâëèâàëè
	if (m_bMSMessengerStopped)
		Start ();
}

messenger::operator bool () const
{
	return (m_Monitor != NULL);
}

BOOL CALLBACK messenger::EnumWindowsProc (HWND hWnd, LPARAM lParam)
{
	DWORD dwTargetId = reinterpret_cast <messenger*> (lParam)->m_ID;
	DWORD dwProcessId = 0;
	GetWindowThreadProcessId (hWnd, &dwProcessId);
	if (dwTargetId && dwTargetId != dwProcessId)
		return TRUE;

	const LONG req_style = WS_VISIBLE | WS_POPUP | WS_CAPTION | WS_SYSMENU;
	const LONG req_style_ex = WS_EX_TOPMOST;
	HWND hButton, hText;
	TCHAR ClassName[ 8 ] = {};
	if ((GetWindowLongPtr(hWnd, GWL_STYLE) & req_style) != req_style ||
		(GetWindowLongPtr(hWnd, GWL_EXSTYLE) & req_style_ex) != req_style_ex ||
		GetParent (hWnd) != NULL ||
		GetWindow (hWnd, GW_OWNER) != NULL ||
		// child 1 = Button, child 2 = STATIC, child 3 = NULL
		(hButton = GetWindow (hWnd, GW_CHILD)) == NULL ||
		GetClassName( hButton, ClassName, _countof( ClassName ) ) == 0 ||
		lstrcmpi (_T("button"), ClassName) != 0 ||
		(hText = GetNextWindow (hButton, GW_HWNDNEXT)) == NULL ||
		GetClassName( hText, ClassName, _countof( ClassName ) ) == 0 ||
		lstrcmpi( _T("static"), ClassName ) != 0 ||
		GetNextWindow (hText, GW_HWNDNEXT) != NULL)
		// ×óæîå îêíî
		return TRUE;

	CString buf;
	int buf_size = GetWindowTextLength (hText);
	if (buf_size) {
		GetWindowText (hText, buf.GetBuffer (buf_size + 1), buf_size + 1);
		buf.ReleaseBuffer ();
	}

	if (!buf.IsEmpty ()) {
		CString tok, from, to, msg;
		int curPos = 0;
		for (int i = 0; (tok = buf.Tokenize( _T(" "), curPos)), !tok.IsEmpty (); i++) {
			switch (i) {
				case 2:
					from = tok;
					break;
				case 4:
					to = tok;
					break;
			}
		}
		int n = buf.Find ( _T("\n") );
		msg = buf.Mid (n + 3);
		if (!from.IsEmpty () && !to.IsEmpty () && !msg.IsEmpty ()) {
			// Çàêðûòèå îêíà
			DWORD_PTR res = 0;
			SendMessageTimeout (hWnd, WM_COMMAND, (WPARAM) GetDlgCtrlID (hButton),
				(LPARAM) hButton, SMTO_ABORTIFHUNG | SMTO_NORMAL, 10000, &res);

			// Îê
			ReceiveContactMessage(from, to, msg, msg.GetLength ());
		}
	}

	return FALSE;
}

void messenger::Monitor ()
{
	while (WaitForSingleObject (m_MonitorTerm, 250) == WAIT_TIMEOUT)
	{
		EnumWindows (EnumWindowsProc, reinterpret_cast <LPARAM> (this));
	}
	m_Monitor = NULL;
}

void messenger::MonitorThread(LPVOID lpParameter)
{
	reinterpret_cast< messenger* >( lpParameter )->Monitor();
}

// Çàïóñê "Ñëóæáû Ñîîáùåíèé"
bool messenger::Start ()
{
	if (pluginOS.dwPlatformId != VER_PLATFORM_WIN32_NT)
		return false;
	
	bool ret = m_bMSMessengerStopped = false;

	// Îòêðûòèå ìåíåäæåðà ñåðâèñîâ
	SC_HANDLE manager = fnOpenSCManager (NULL, NULL,
		STANDARD_RIGHTS_READ | SC_MANAGER_CONNECT);
	if (manager) {
		// Îòêðûòèå ñåðâèñà
		SC_HANDLE service = fnOpenService (manager, MESSENGER,
			SERVICE_START | SERVICE_QUERY_STATUS); 
		if (service) {
			for(;;)
			{
				// Ïðîâåðêà ñîñòîÿíèÿ ñåðâèñà
				SERVICE_STATUS ss = { 0 };
				if (fnQueryServiceStatus (service, &ss)) {
					if (ss.dwCurrentState == SERVICE_RUNNING) {
						// Óæå ðàáîòàåò
						LOG ("Messenger service already running");
						ret = true;
					} else {
						// Çàïóñê ñåðâèñà
						if (fnStartService (service, 0, NULL))
							// Îæèäàíèå çàïóñêà ñåðâèñà
							ret = WaitForService (T_START_ERROR, service, SERVICE_START_PENDING, SERVICE_RUNNING);
						else {
							DWORD err = GetLastError ();
							if ( err == ERROR_SERVICE_DISABLED )
							{
								// Ïîïûòêà ðàçðåøåíèÿ ñåðâèñà
								if ( Enable() )
									// Ïîâòîð
									continue;
							} else
								WarningBox (NULL, err, T_START_ERROR);
						}
					}
				} else
					WarningBox (NULL, GetLastError (), T_START_ERROR);
				break;
			}
			fnCloseServiceHandle (service);
		} else
			WarningBox (NULL, GetLastError (), T_START_ERROR);
		fnCloseServiceHandle (manager);
	} else
		WarningBox (NULL, GetLastError (), T_START_ERROR);
	return ret;
}

// Îñòàíîâ "Ñëóæáû Ñîîáùåíèé"
bool messenger::Stop ()
{
	if (pluginOS.dwPlatformId != VER_PLATFORM_WIN32_NT)
		return false;

	bool ret = m_bMSMessengerStopped = false;

	// Îòêðûòèå ìåíåäæåðà ñåðâèñîâ
	SC_HANDLE manager = fnOpenSCManager (NULL, NULL,
		STANDARD_RIGHTS_READ | SC_MANAGER_CONNECT);
	if (manager)
	{
		// Îòêðûòèå ñåðâèñà
		SC_HANDLE service = fnOpenService (manager, MESSENGER,
			SERVICE_STOP | SERVICE_QUERY_STATUS); 
		if (service)
		{
			// Ïðîâåðêà ñîñòîÿíèÿ ñåðâèñà
			SERVICE_STATUS ss = {};
			if (fnQueryServiceStatus (service, &ss))
			{
				if (ss.dwCurrentState == SERVICE_STOPPED)
				{
					// Óæå îñòàíîâëåí
					LOG ("Messenger service already stopped");
					ret = true; // m_bMSMessengerStopped = false
				}
				else
				{
					// Îñòàíîâ ñåðâèñà
					ZeroMemory (&ss, sizeof (SERVICE_STATUS));
					if (fnControlService (service, SERVICE_CONTROL_STOP, &ss))
					{
						// Îæèäàíèå îñòàíîâà
						ret = m_bMSMessengerStopped = WaitForService (
							T_STOP_ERROR, service,
							SERVICE_STOP_PENDING, SERVICE_STOPPED);						
					}
					else
					{
						if (GetLastError () == ERROR_SERVICE_NOT_ACTIVE)
							// Óæå îñòàíîâëåí
							ret = true; // m_bMSMessengerStopped = false
						else
							WarningBox (NULL, GetLastError (), T_STOP_ERROR);
					}
				}
			}
			else
				WarningBox (NULL, GetLastError (), T_STOP_ERROR);
			fnCloseServiceHandle (service);
		}
		else
		{
			if (GetLastError () == ERROR_SERVICE_DOES_NOT_EXIST)
				// Òàêîãî ñåðâèñà íåò - îê
				ret = true; // m_bMSMessengerStopped = false
			else
				WarningBox (NULL, GetLastError (), T_STOP_ERROR);
		}
		fnCloseServiceHandle (manager);
	}
	else
		WarningBox (NULL, GetLastError (), T_STOP_ERROR);

	return ret;
}

// Ðàçðåøåíèå çàïóñêà  "Ñëóæáû Ñîîáùåíèé"
bool messenger::Enable ()
{
	bool ret = false;

	// Îòêðûòèå ìåíåäæåðà ñåðâèñîâ
	SC_HANDLE manager = fnOpenSCManager (NULL, NULL,
		STANDARD_RIGHTS_READ | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG |
		SC_MANAGER_CONNECT | SC_MANAGER_LOCK);
	if (manager)
	{
		// Áëîêèðîâêà ìåíåäæåðà
		SC_LOCK lock = fnLockServiceDatabase( manager );
		if (lock)
		{
			// Îòêðûòèå ñåðâèñà
			SC_HANDLE service = fnOpenService ( manager, MESSENGER,
				SERVICE_CHANGE_CONFIG );
			if (service)
			{
				// Óñòàíîâêà àâòîçàïóñêà ñåðâèñà
				if ( fnChangeServiceConfig( service, SERVICE_NO_CHANGE,
					SERVICE_AUTO_START, SERVICE_NO_CHANGE,
					NULL, NULL, NULL, NULL, NULL, NULL, NULL ) )
					ret = true;
				else
					WarningBox (NULL, GetLastError (), T_ENABLE_ERROR);

				fnCloseServiceHandle (service);
			}
			else
				WarningBox (NULL, GetLastError (), T_ENABLE_ERROR);
			
			fnUnlockServiceDatabase( lock );
		}
		else
			WarningBox (NULL, GetLastError (), T_ENABLE_ERROR);
		
		fnCloseServiceHandle ( manager );
	}
	else
		WarningBox (NULL, GetLastError (), T_ENABLE_ERROR);
	return ret;
}

bool messenger::WaitForService (LPCTSTR reason, SC_HANDLE service, DWORD process, DWORD end)
{
	SERVICE_STATUS ss = { 0 };
	if (fnQueryServiceStatus (service, &ss))
	{
		DWORD dwStartTickCount = GetTickCount();
		DWORD dwOldCheckPoint = ss.dwCheckPoint;
		while (ss.dwCurrentState == process) { 
			// Do not wait longer than the wait hint. A good interval is 
			// one tenth the wait hint, but no less than 1 second and no 
			// more than 10 seconds.
			DWORD dwWaitTime = ss.dwWaitHint / 10;
			if (dwWaitTime < 1000)
				dwWaitTime = 1000;
			else
				if (dwWaitTime > 10000)
					dwWaitTime = 10000;
			Sleep (dwWaitTime);
			// Check the status again. 
			if (!fnQueryServiceStatus (service, &ss))
			{
				WarningBox (NULL, GetLastError (), reason);
				return false; 
			}
			if (ss.dwCurrentState == end)
				break;
			if (ss.dwCheckPoint > dwOldCheckPoint)
			{
				// The service is making progress.
				dwStartTickCount = GetTickCount();
				dwOldCheckPoint = ss.dwCheckPoint;
			} else
			{
				if (GetTickCount() - dwStartTickCount > ss.dwWaitHint)
				{
					WarningBox (NULL, 0, _T("%s\r\n%s"), TranslateT ("No progress"), reason);
					return false;
				}
			}
		}
		if (ss.dwCurrentState == end)
			return true;					
		WarningBox (NULL, 0, _T("%s\r\n%s"), TranslateT ("Unexpected service status change"), reason);
	}
	else
		WarningBox (NULL, GetLastError (), reason);
	return false;
}

bool messenger::SendMessengerMessage(HANDLE hContact, LPCTSTR msg, DWORD& err)
{
	if ( pluginOS.dwPlatformId != VER_PLATFORM_WIN32_NT || ! fnNetMessageBufferSend )
	{
		err = ERROR_NOT_SUPPORTED;
		return false;
	}

	// Ïîëó÷åíèå àäðåñàòà
	CString sTo = GetNick( hContact );
	if ( sTo.IsEmpty() )
	{
		err = NERR_NameNotFound;
		return false;
	}

	// Ïîëó÷åíèå ñâîåãî èìåíè
	CString sFrom = GetNick( NULL );
	if ( sFrom.IsEmpty() )
	{
		err = NERR_NameNotFound;
		return false;
	}

	// Íåò ðàçíèöû ãðóïïà ýòî èëè êîìïüþòåð
	// bool bGroup = IsGroup( hContact );

	LPWSTR wto = mir_t2u( sTo );
	LPWSTR wfrom = mir_t2u( sFrom );
	LPWSTR wmsg = mir_t2u( msg );
	err = fnNetMessageBufferSend( NULL, wto, wfrom, (LPBYTE)wmsg,
		lstrlen( msg ) * sizeof( WCHAR ) );
	mir_free( wto );
	mir_free( wfrom );
	mir_free( wmsg );

	return ( err == NERR_Success );
}