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

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 "processapi.h"

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

DWORD GetProcessId (LPCTSTR name)
{
	DWORD id = 0;
	int name_len = lstrlen (name);
	CProcessApi papi;
	if (papi.Init (true)) {
		DWORD pl = papi.ProcessesGetList();
		if (pl) {
			CProcessApi::tProcessInfo pi = {0};
			while (papi.ProcessesWalk (pl, &pi)) {
				int len = lstrlen (pi.FileName);
				if (len >= name_len &&
					lstrcmpi (pi.FileName + (len - name_len), name) == 0) {
						id = pi.pid;
						break;
					}
			}
		}
		papi.ProcessesFreeList(pl);
	}
	return id;
}

/* ----------------------------------------------------------------------------- 
 * Copyright (c) 2003 Elias Bachaalany <elias_bachaalany@yahoo.com>
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ----------------------------------------------------------------------------- 
 */

#ifdef _UNICODE
	#define Modifier "W"
#else
	#define Modifier "A"
#endif

// custom macro to allow me to load functions dynamically
#define DynamicGetProcAddress(lib, prefix, mod_name, Mod) \
  { \
	PVOID p = GetProcAddress(lib, #mod_name Mod); \
	if (!p) { \
		FreeLibrary(lib); \
		return (LastError = paeNoEntryPoint, false); \
	} \
	##prefix##mod_name = (t_##prefix##mod_name)p; \
  }

//--------------------------------------------------------------------------------------------
// The constructor only initializes some internal variables
CProcessApi::CProcessApi() :
	m_hPsApi (NULL),
	m_hTlHlp (NULL),
	m_hNtApi (NULL),
	m_bPsApi (false),
	m_bToolHelp (false),
	m_bNtApi (false),
	LastError (paeSuccess)
{
}

//--------------------------------------------------------------------------------------------
// This is the destructor. It frees any process helper api that has been used
CProcessApi::~CProcessApi()
{
  if (m_hPsApi)
    FreeLibrary(m_hPsApi);
  if (m_hTlHlp)
    FreeLibrary(m_hTlHlp);
  if (m_hNtApi)
    FreeLibrary(m_hNtApi);
}

//--------------------------------------------------------------------------------------------
// Used to initialize the CProcessApi class
bool CProcessApi::Init (bool bNtApiFirst)
{
	bool loaded = m_bPsApi || m_bToolHelp || m_bNtApi;

	if (bNtApiFirst && !loaded) {
		loaded = Load_NtApi();
	}

	if (!loaded) {
		loaded = Load_PsApi();
	}

	if (!loaded) {
		loaded = Load_TlHlp();
	}

	if (!bNtApiFirst && !loaded) {
		loaded = Load_NtApi();
	}

	return (loaded ? (LastError = paeSuccess, true) : (LastError = paeNoApi, false));
}

//--------------------------------------------------------------------------------------------
// This function returns a list id (list id) that can be used w/ Walking functions
// in order to navigate through the process list
// This function decides what to use from the helper apis
DWORD CProcessApi::ModulesGetList(DWORD pid)
{
	tModulesData *md = new tModulesData;
	if ( ! md )
		return (LastError = paeNoMem, 0u);

	// create the list
	md->ml = new tModulesList;
	if ( ! md->ml )
	{
		delete md;
		return (LastError = paeNoMem, 0u);
	}

	// decide what to use
	if (m_bPsApi)
		LastError = ModulesPopulatePsApi(pid, md);
	else if (m_bToolHelp)
		LastError = ModulesPopulateToolHelp(pid, md);
	else if (m_bNtApi)
		LastError = ModulesPopulateNtApi(pid, md);

	return (DWORD) md;
}

//--------------------------------------------------------------------------------------------
// Populates the modules of a process using ToolHelp api
DWORD CProcessApi::ModulesPopulateToolHelp(DWORD pid, tModulesData *md)
{
  MODULEENTRY32 me32        = {sizeof(MODULEENTRY32), 0}; 
  tModuleInfo   mi = {0};

  // Take a snapshot of all modules in the specified process. 
  HANDLE hModuleSnap = tlhlp_CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); 

  if (hModuleSnap == INVALID_HANDLE_VALUE) 
    return paeNoSnap; 
 
  // Start walking
  BOOL bMore = tlhlp_Module32First(hModuleSnap, &me32);
  do
  {
    lstrcpy (mi.FileName, me32.szExePath);
    mi.ImageBase = me32.modBaseAddr;
    mi.ImageSize = me32.modBaseSize;

    // save item
    md->ml->Add (mi);

    // search next
    bMore = tlhlp_Module32Next(hModuleSnap, &me32);
  } while (bMore);

  CloseHandle (hModuleSnap); 
  md->Pos = 0;
  return paeSuccess;
} 

//--------------------------------------------------------------------------------------------
// Populates the modules of a process using PsApi api
DWORD CProcessApi::ModulesPopulatePsApi(DWORD pid, tModulesData *md)
{
  DWORD nModules, nCount = 4096;
  HANDLE hProcess;

  // allocate memory for modules
  HMODULE *modules   = new HMODULE[nCount];

  // open process for querying only
  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
  if (!hProcess)
    return paeNoSnap;
      
  // now try to enum all modules
  if (!psapi_EnumProcessModules(hProcess, modules, nCount * sizeof(DWORD), &nModules))    
  {
    CloseHandle(hProcess);
    return paeNoSnap;
  }

  // because nModules returned from EnumProcessModules() is in bytes, I divid by 4 to return n DWORDs
  nModules /= 4;

  tModuleInfo mi = {0};
  MODULEINFO psapiMi = {0};

  for (DWORD i=0; i < nModules; i++)
  {
    // get module name
    psapi_GetModuleFileNameEx(hProcess, modules[i], mi.FileName, sizeof(mi.FileName));    

    // get module information
    psapi_GetModuleInformation(hProcess, modules[i], &psapiMi, sizeof(MODULEINFO));

    // get relevant data
    mi.ImageBase = psapiMi.lpBaseOfDll;
    mi.ImageSize = psapiMi.SizeOfImage;

    // save item
    md->ml->Add (mi);
  }

  md->Pos = 0;
  CloseHandle(hProcess);
  delete [] modules;

  return paeSuccess;
}

//--------------------------------------------------------------------------------------------
// It frees a modules list by its ID
void CProcessApi::ModulesFreeList(DWORD_PTR lid)
{
  tModulesData *md = reinterpret_cast<tModulesData *>(lid);
  delete md->ml;
  delete md;
}

//--------------------------------------------------------------------------------------------
// This function allows you to retrieve information about a certain module in a process
// You can either use this function using the Pos parameter controlled by the ModulesCount()
// Or you can keep calling it till it returns false
bool CProcessApi::ModulesWalk(DWORD_PTR lid, tModuleInfo *mi, DWORD Pos)
{
  tModulesData *md = reinterpret_cast<tModulesData *>(lid);

  // auto position ?
  if (Pos == -1)
    Pos = md->Pos;

  // out of bounds?
  if (Pos > md->ml->GetCount())
    return (LastError = paeOutOfBounds, false);

  // end reached ?
  else if (Pos == md->ml->GetCount())
    return (LastError = paeNoMore, false);
    
  // copy information to user buffer
  *mi = md->ml->GetAt (Pos);

  // advance position to next item
  md->Pos++;

  return (LastError = paeSuccess, true);
}


//--------------------------------------------------------------------------------------------
// This function allows you to retrieve information about a certain process in the list
// You can either use this function using the Pos parameter controlled by the ProcessesCount()
// Or you can keep calling it till it returns false
bool CProcessApi::ProcessesWalk(DWORD_PTR lid, tProcessInfo *pi, DWORD Pos)
{
  tProcessesData *pd = reinterpret_cast<tProcessesData *>(lid);

  // auto position ?
  if (Pos == -1)
    Pos = pd->Pos;

  // out of bounds?
  if (Pos > pd->pl->GetCount())
    return (LastError = paeOutOfBounds, false);
  // end reached ?
  else if (Pos == pd->pl->GetCount())
    return (LastError = paeNoMore, false);
    
  // copy information to user buffer
  *pi = pd->pl->GetAt (Pos);

  // advance position to next item
  pd->Pos++;
  return (LastError = paeSuccess, true);
}


//--------------------------------------------------------------------------------------------
// This function returns a list id (list id) that can be used w/ Walking functions
// in order to navigate through the process list
// This function decides what to use from the helper apis
DWORD CProcessApi::ProcessesGetList()
{
  tProcessesData *pd = new tProcessesData;
  if (!pd)
    return (LastError = paeNoMem, 0u);

  // create the list
  pd->pl = new tProcessesList;
  if (!pd->pl)
  {
    delete pd;
    return (LastError = paeNoMem, 0u);
  }

  // decide what to use
  if (m_bPsApi)
    LastError = ProcessesPopulatePsApi(pd);
  else if (m_bToolHelp)
    LastError = ProcessesPopulateToolHelp(pd);
  else if (m_bNtApi)
    LastError = ProcessesPopulateNtApi(pd);

  return (DWORD) pd;
}

//--------------------------------------------------------------------------------------------
// It frees a process list by its ID
void CProcessApi::ProcessesFreeList(DWORD_PTR lid)
{
  tProcessesData *pd = reinterpret_cast<tProcessesData *>(lid);
  delete pd->pl;
  delete pd;
}

//--------------------------------------------------------------------------------------------
// Dynamically loads the PsApi functions
bool CProcessApi::Load_PsApi()
{
	if (m_bPsApi)
		return true;
	if (!m_hPsApi)
		m_hPsApi = LoadLibrary (_T("psapi.dll"));
	if (!m_hPsApi)
		return false; 

	DynamicGetProcAddress(m_hPsApi, psapi_, GetModuleFileNameEx, Modifier);
	DynamicGetProcAddress(m_hPsApi, psapi_, EnumProcessModules, "");
	DynamicGetProcAddress(m_hPsApi, psapi_, EnumProcesses, "");
	DynamicGetProcAddress(m_hPsApi, psapi_, GetModuleInformation, "");

	m_bPsApi = true;
	return true;
}


//--------------------------------------------------------------------------------------------
// Dynamically loads the ToolHelp functions
bool CProcessApi::Load_TlHlp()
{
	if (m_bToolHelp)
		return true;
	if (!m_hTlHlp)
		m_hTlHlp = LoadLibrary (_T("kernel32.dll"));
	if (!m_hTlHlp)
		return false; 

	DynamicGetProcAddress(m_hTlHlp, tlhlp_, CreateToolhelp32Snapshot, "");
	DynamicGetProcAddress(m_hTlHlp, tlhlp_, Process32First, "");
	DynamicGetProcAddress(m_hTlHlp, tlhlp_, Process32Next, "");
	DynamicGetProcAddress(m_hTlHlp, tlhlp_, Module32First, "");
	DynamicGetProcAddress(m_hTlHlp, tlhlp_, Module32Next, "");

	m_bToolHelp = true;
	return true;
}

bool CProcessApi::Load_NtApi()
{
	if (m_bNtApi)
		return true;
	if (!m_hNtApi)
		m_hNtApi = LoadLibrary (_T("ntdll.dll"));
	if (!m_hNtApi)
		return false; 

	DynamicGetProcAddress(m_hNtApi, ntapi_, ZwQuerySystemInformation, "");

	m_bNtApi = true;
	return true;
}

//--------------------------------------------------------------------------------------------
// Populates a tProcessesList with the help of ToolHelp API
// Returns an error code paeXXXX
DWORD CProcessApi::ProcessesPopulateToolHelp(tProcessesData *pd)
{
  // create a process snapshot
  HANDLE hSnap = tlhlp_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (hSnap == INVALID_HANDLE_VALUE)
    return paeNoSnap;

  BOOL bMore;
  tProcessInfo pi = {0};

  PROCESSENTRY32 pe32 = {sizeof(PROCESSENTRY32), 0};

  // clear the list
  pd->pl->RemoveAll ();

  // initialize position
  pd->Pos = 0;

  bMore = tlhlp_Process32First(hSnap, &pe32);
  while (bMore)
  {
    // convert from PROCESSENTRY32 to my unified tProcessInfo struct
    pi.pid = pe32.th32ProcessID;
    lstrcpy (pi.FileName, pe32.szExeFile);

    pd->pl->Add(pi);
    bMore = tlhlp_Process32Next(hSnap, &pe32);
  }

  CloseHandle(hSnap);
  return paeSuccess;
}


//--------------------------------------------------------------------------------------------
// Populates the list using PsApi functions
DWORD CProcessApi::ProcessesPopulatePsApi(tProcessesData *pd)
{
  DWORD nProcess, // number of processes returned
        nCount(4096); // maximum number of processes (defined by me)

  // Dynamic array for storing returned processes IDs
  DWORD *processes = new DWORD[nCount];

  // enum all processes
  if (!psapi_EnumProcesses(processes, nCount * sizeof(DWORD), &nProcess))
  {
    delete [] processes;
    return paeNoSnap;
  }

  // convert fron bytes count to items count
  nProcess /= 4;

  // walk in process list
  for (DWORD i = 0; i < nProcess; i++) {

	  if (processes[i] == 0)
		  // Idle
		  continue;

	// open process for querying only
	HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processes[i]);
	if (!hProcess)
		continue;

    // get the process's image name by getting first module
    DWORD nmod;
    HMODULE mod1;

	tProcessInfo pi = {0};
	pi.pid = processes [i];
	if (!psapi_EnumProcessModules (hProcess, &mod1, sizeof(mod1), &nmod))
		lstrcpy (pi.FileName, _T("-"));
	else
		psapi_GetModuleFileNameEx (hProcess, mod1, pi.FileName, sizeof(pi.FileName));
	pd->pl->Add (pi);
	    
	CloseHandle(hProcess);
  }

  // reposition list to 0
  pd->Pos = 0;
  delete [] processes;

  return paeSuccess;
}

DWORD CProcessApi::ProcessesPopulateNtApi (tProcessesData *pd)
{
	ULONG cbBuffer = 0x10000;
	char* pBuffer;
	NTSTATUS Status;
	do {
		pBuffer = new char [cbBuffer];
		if (pBuffer == NULL)
			return paeNoMem;
		Status = ntapi_ZwQuerySystemInformation (SystemProcessesAndThreadsInformation,
			pBuffer, cbBuffer, NULL);
		if (Status == STATUS_INFO_LENGTH_MISMATCH) {
			delete [] pBuffer;
			cbBuffer *= 2;
		} else
			if (!NT_SUCCESS(Status)) {
				delete [] pBuffer;
				return paeNoSnap;
			}
	} while (Status == STATUS_INFO_LENGTH_MISMATCH);

	PSYSTEM_PROCESSES pProcesses = (PSYSTEM_PROCESSES) pBuffer;
	for (;;) {
		if (pProcesses->ProcessName.Buffer != NULL) {
			tProcessInfo pi;
			pi.pid = pProcesses->ProcessId;
#ifdef UNICODE
			lstrcpy (pi.FileName, pProcesses->ProcessName.Buffer);
#else
			WideCharToMultiByte (CP_ACP, 0, pProcesses->ProcessName.Buffer, -1,
				pi.FileName, MAX_PATH, NULL, NULL);
#endif
			pd->pl->Add (pi);
		} // else
			// Idle

		if (pProcesses->NextEntryDelta == 0)
			break;

		// find the address of the next process structure
		pProcesses = (PSYSTEM_PROCESSES)(((LPBYTE)pProcesses) + pProcesses->NextEntryDelta);
	}
	pd->Pos = 0;
	delete [] pBuffer;
	return paeSuccess;
}

DWORD CProcessApi::ModulesPopulateNtApi(DWORD /* pid */, tModulesData* /* md */)
{
	return paeSuccess;
}	

//--------------------------------------------------------------------------------------------
// Returns the count in the processes list
DWORD CProcessApi::ProcessesCount(DWORD_PTR lid) const
{
  return (DWORD)(reinterpret_cast<tProcessesData *>(lid))->pl->GetCount();
}

//--------------------------------------------------------------------------------------------
// Returns the count in the modules list
DWORD CProcessApi::ModulesCount(DWORD_PTR lid) const
{
  return (DWORD)(reinterpret_cast<tModulesData *>(lid))->ml->GetCount();
}