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 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
|
/*
* $Id: _psutil_mswindows.c 1399 2012-06-29 16:41:00Z g.rodola $
*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Windows platform-specific module methods for _psutil_mswindows
*/
// Fixes clash between winsock2.h and windows.h
#define WIN32_LEAN_AND_MEAN
#include <Python.h>
#include <windows.h>
#include <Psapi.h>
#include <time.h>
#include <lm.h>
#include <WinIoCtl.h>
#include <tchar.h>
#include <tlhelp32.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <wtsapi32.h>
// Link with Iphlpapi.lib
#pragma comment(lib, "IPHLPAPI.lib")
#include "_psutil_mswindows.h"
#include "_psutil_common.h"
#include "arch/mswindows/security.h"
#include "arch/mswindows/process_info.h"
#include "arch/mswindows/process_handles.h"
#include "arch/mswindows/ntextapi.h"
/*
* Return a Python float representing the system uptime expressed in seconds
* since the epoch.
*/
static PyObject*
get_system_uptime(PyObject* self, PyObject* args)
{
double uptime;
time_t pt;
FILETIME fileTime;
long long ll;
GetSystemTimeAsFileTime(&fileTime);
/*
HUGE thanks to:
http://johnstewien.spaces.live.com/blog/cns!E6885DB5CEBABBC8!831.entry
This function converts the FILETIME structure to the 32 bit
Unix time structure.
The time_t is a 32-bit value for the number of seconds since
January 1, 1970. A FILETIME is a 64-bit for the number of
100-nanosecond periods since January 1, 1601. Convert by
subtracting the number of 100-nanosecond period betwee 01-01-1970
and 01-01-1601, from time_t the divide by 1e+7 to get to the same
base granularity.
*/
ll = (((LONGLONG)(fileTime.dwHighDateTime)) << 32) + fileTime.dwLowDateTime;
pt = (time_t)((ll - 116444736000000000ull) / 10000000ull);
// XXX - By using GetTickCount() time will wrap around to zero if the
// system is run continuously for 49.7 days.
uptime = GetTickCount() / 1000.00f;
return Py_BuildValue("d", (double)pt - uptime);
}
/*
* Return 1 if PID exists in the current process list, else 0.
*/
static PyObject*
pid_exists(PyObject* self, PyObject* args)
{
long pid;
int status;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
status = pid_is_running(pid);
if (-1 == status) {
return NULL; // exception raised in pid_is_running()
}
return PyBool_FromLong(status);
}
/*
* Return a Python list of all the PIDs running on the system.
*/
static PyObject*
get_pid_list(PyObject* self, PyObject* args)
{
DWORD *proclist = NULL;
DWORD numberOfReturnedPIDs;
DWORD i;
PyObject* pid = NULL;
PyObject* retlist = PyList_New(0);
proclist = get_pids(&numberOfReturnedPIDs);
if (NULL == proclist) {
Py_DECREF(retlist);
return NULL;
}
for (i = 0; i < numberOfReturnedPIDs; i++) {
pid = Py_BuildValue("I", proclist[i]);
PyList_Append(retlist, pid);
Py_XDECREF(pid);
}
// free C array allocated for PIDs
free(proclist);
return retlist;
}
/*
* Kill a process given its PID.
*/
static PyObject*
kill_process(PyObject* self, PyObject* args)
{
HANDLE hProcess;
long pid;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (pid == 0) {
return AccessDenied();
}
hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
if (hProcess == NULL) {
if (GetLastError() == ERROR_INVALID_PARAMETER) {
// see http://code.google.com/p/psutil/issues/detail?id=24
NoSuchProcess();
}
else {
PyErr_SetFromWindowsErr(0);
}
return NULL;
}
// kill the process
if (! TerminateProcess(hProcess, 0)) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hProcess);
return NULL;
}
CloseHandle(hProcess);
Py_INCREF(Py_None);
return Py_None;
}
/*
* Wait for process to terminate and return its exit code.
*/
static PyObject*
process_wait(PyObject* self, PyObject* args)
{
HANDLE hProcess;
DWORD ExitCode;
DWORD retVal;
long pid;
long timeout;
if (! PyArg_ParseTuple(args, "ll", &pid, &timeout)) {
return NULL;
}
if (pid == 0) {
return AccessDenied();
}
hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (hProcess == NULL) {
if (GetLastError() == ERROR_INVALID_PARAMETER) {
// no such process; we do not want to raise NSP but
// return None instead.
Py_INCREF(Py_None);
return Py_None;
}
else {
PyErr_SetFromWindowsErr(0);
return NULL;
}
}
// wait until the process has terminated
Py_BEGIN_ALLOW_THREADS
retVal = WaitForSingleObject(hProcess, timeout);
Py_END_ALLOW_THREADS
if (retVal == WAIT_FAILED) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(GetLastError());
}
if (retVal == WAIT_TIMEOUT) {
CloseHandle(hProcess);
return Py_BuildValue("l", WAIT_TIMEOUT);
}
// get the exit code; note: subprocess module (erroneously?) uses
// what returned by WaitForSingleObject
if (GetExitCodeProcess(hProcess, &ExitCode) == 0) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(GetLastError());
}
CloseHandle(hProcess);
#if PY_MAJOR_VERSION >= 3
return PyLong_FromLong((long) ExitCode);
#else
return PyInt_FromLong((long) ExitCode);
#endif
}
/*
* Return a Python tuple (user_time, kernel_time)
*/
static PyObject*
get_process_cpu_times(PyObject* self, PyObject* args)
{
long pid;
HANDLE hProcess;
FILETIME ftCreate, ftExit, ftKernel, ftUser;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
// special case for PID 0
if (0 == pid){
return Py_BuildValue("(dd)", 0.0, 0.0);
}
hProcess = handle_from_pid(pid);
if (hProcess == NULL) {
return NULL;
}
if (! GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) {
CloseHandle(hProcess);
if (GetLastError() == ERROR_ACCESS_DENIED) {
// usually means the process has died so we throw a NoSuchProcess
// here
return NoSuchProcess();
}
else {
PyErr_SetFromWindowsErr(0);
return NULL;
}
}
CloseHandle(hProcess);
/*
user and kernel times are represented as a FILETIME structure wich contains
a 64-bit value representing the number of 100-nanosecond intervals since
January 1, 1601 (UTC).
http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx
To convert it into a float representing the seconds that the process has
executed in user/kernel mode I borrowed the code below from Python's
Modules/posixmodule.c
*/
return Py_BuildValue(
"(dd)",
(double)(ftUser.dwHighDateTime*429.4967296 + \
ftUser.dwLowDateTime*1e-7),
(double)(ftKernel.dwHighDateTime*429.4967296 + \
ftKernel.dwLowDateTime*1e-7)
);
}
/*
* Return a Python float indicating the process create time expressed in
* seconds since the epoch.
*/
static PyObject*
get_process_create_time(PyObject* self, PyObject* args)
{
long pid;
long long unix_time;
DWORD exitCode;
HANDLE hProcess;
BOOL WINAPI ret;
FILETIME ftCreate, ftExit, ftKernel, ftUser;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
// special case for PIDs 0 and 4
if ( (0 == pid) || (4 == pid) ){
return Py_BuildValue("d", 0.0);
}
hProcess = handle_from_pid(pid);
if (hProcess == NULL) {
return NULL;
}
if (! GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) {
CloseHandle(hProcess);
if (GetLastError() == ERROR_ACCESS_DENIED) {
// usually means the process has died so we throw a NoSuchProcess here
return NoSuchProcess();
}
else {
PyErr_SetFromWindowsErr(0);
return NULL;
}
}
// Make sure the process is not gone as OpenProcess alone seems to be
// unreliable in doing so (it seems a previous call to p.wait() makes
// it unreliable).
// This check is important as creation time is used to make sure the
// process is still running.
ret = GetExitCodeProcess(hProcess, &exitCode);
CloseHandle(hProcess);
if (ret != 0) {
if (exitCode != STILL_ACTIVE) {
return NoSuchProcess();
}
}
else {
// Ignore access denied as it means the process is still alive.
// For all other errors, we want an exception.
if (GetLastError() != ERROR_ACCESS_DENIED) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
}
/*
Convert the FILETIME structure to a Unix time.
It's the best I could find by googling and borrowing code here and there.
The time returned has a precision of 1 second.
*/
unix_time = ((LONGLONG)ftCreate.dwHighDateTime) << 32;
unix_time += ftCreate.dwLowDateTime - 116444736000000000LL;
unix_time /= 10000000;
return Py_BuildValue("d", (double)unix_time);
}
/*
* Return a Python integer indicating the number of CPUs on the system.
*/
static PyObject*
get_num_cpus(PyObject* self, PyObject* args)
{
SYSTEM_INFO system_info;
system_info.dwNumberOfProcessors = 0;
GetSystemInfo(&system_info);
if (system_info.dwNumberOfProcessors == 0){
// GetSystemInfo failed for some reason; return 1 as default
return Py_BuildValue("I", 1);
}
return Py_BuildValue("I", system_info.dwNumberOfProcessors);
}
/*
* Return process name as a Python string.
*/
static PyObject*
get_process_name(PyObject* self, PyObject* args) {
long pid;
int pid_return;
PyObject* name;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (pid == 0) {
return Py_BuildValue("s", "System Idle Process");
}
else if (pid == 4) {
return Py_BuildValue("s", "System");
}
pid_return = pid_is_running(pid);
if (pid_return == 0) {
return NoSuchProcess();
}
if (pid_return == -1) {
return NULL;
}
name = get_name(pid);
if (name == NULL) {
return NULL; // exception set in get_name()
}
return name;
}
/*
* Return process parent pid as a Python integer.
*/
static PyObject*
get_process_ppid(PyObject* self, PyObject* args) {
long pid;
int pid_return;
PyObject* ppid;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if ((pid == 0) || (pid == 4)) {
return Py_BuildValue("l", 0);
}
pid_return = pid_is_running(pid);
if (pid_return == 0) {
return NoSuchProcess();
}
if (pid_return == -1) {
return NULL;
}
ppid = get_ppid(pid);
if (ppid == NULL) {
return NULL; // exception set in get_ppid()
}
return ppid;
}
/*
* Return process cmdline as a Python list of cmdline arguments.
*/
static PyObject*
get_process_cmdline(PyObject* self, PyObject* args) {
long pid;
int pid_return;
PyObject* arglist;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if ((pid == 0) || (pid == 4)) {
return Py_BuildValue("[]");
}
pid_return = pid_is_running(pid);
if (pid_return == 0) {
return NoSuchProcess();
}
if (pid_return == -1) {
return NULL;
}
// May fail any of several ReadProcessMemory calls etc. and not indicate
// a real problem so we ignore any errors and just live without commandline
arglist = get_arg_list(pid);
if ( NULL == arglist ) {
// carry on anyway, clear any exceptions too
PyErr_Clear();
return Py_BuildValue("[]");
}
return arglist;
}
/*
* Return process executable path.
*/
static PyObject*
get_process_exe(PyObject* self, PyObject* args) {
long pid;
HANDLE hProcess;
wchar_t exe[MAX_PATH];
DWORD nSize = MAX_PATH;
DWORD WINAPI ret;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid_waccess(pid, PROCESS_QUERY_INFORMATION);
if (NULL == hProcess) {
return NULL;
}
if (GetProcessImageFileName(hProcess, &exe, nSize) == 0) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(hProcess);
return Py_BuildValue("s", exe);
}
/*
* Return the RSS and VMS as a Python tuple.
*/
static PyObject*
get_memory_info(PyObject* self, PyObject* args)
{
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS counters;
DWORD pid;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
return NULL;
}
if (! GetProcessMemoryInfo(hProcess, &counters, sizeof(counters)) ) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(hProcess);
// py 2.4
#if (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION <= 4)
return Py_BuildValue("(II)", (unsigned int)counters.WorkingSetSize,
(unsigned int)counters.PagefileUsage);
#else
// py >= 2.5
return Py_BuildValue("(nn)", counters.WorkingSetSize, counters.PagefileUsage);
#endif
}
/*
* Return a Python integer indicating the total amount of physical memory
* in bytes.
*/
static PyObject*
get_system_phymem(PyObject* self, PyObject* args)
{
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
if (! GlobalMemoryStatusEx(&memInfo) ) {
return PyErr_SetFromWindowsErr(0);
}
return Py_BuildValue("(LLLLLLk)",
memInfo.ullTotalPhys, // total
memInfo.ullAvailPhys, // avail
memInfo.ullTotalPageFile, // total page file
memInfo.ullAvailPageFile, // avail page file
memInfo.ullTotalVirtual, // total virtual
memInfo.ullAvailVirtual, // avail virtual
memInfo.dwMemoryLoad // percent
);
}
#define LO_T ((float)1e-7)
#define HI_T (LO_T*4294967296.0)
/*
* Return a Python list of tuples representing user, kernel and idle
* CPU times for every CPU on the system.
*/
static PyObject*
get_system_cpu_times(PyObject* self, PyObject* args)
{
float idle, kernel, user;
typedef DWORD (_stdcall *NTQSI_PROC) (int, PVOID, ULONG, PULONG);
NTQSI_PROC NtQuerySystemInformation;
HINSTANCE hNtDll;
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
SYSTEM_INFO si;
UINT i;
PyObject *arg = NULL;
PyObject *retlist = PyList_New(0);
// dynamic linking is mandatory to use NtQuerySystemInformation
hNtDll = LoadLibrary(TEXT("ntdll.dll"));
if (hNtDll != NULL) {
// gets NtQuerySystemInformation address
NtQuerySystemInformation = (NTQSI_PROC)GetProcAddress(
hNtDll, "NtQuerySystemInformation");
if (NtQuerySystemInformation != NULL)
{
// retrives number of processors
GetSystemInfo(&si);
// allocates an array of SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
// structures, one per processor
sppi = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \
malloc(si.dwNumberOfProcessors * \
sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION));
if (sppi != NULL)
{
// gets cpu time informations
if (0 == NtQuerySystemInformation(
SystemProcessorPerformanceInformation,
sppi,
si.dwNumberOfProcessors * sizeof
(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION),
NULL)
)
{
// computes system global times summing each processor value
idle = user = kernel = 0;
for (i=0; i<si.dwNumberOfProcessors; i++) {
user = (float)((HI_T * sppi[i].UserTime.HighPart) + \
(LO_T * sppi[i].UserTime.LowPart));
idle = (float)((HI_T * sppi[i].IdleTime.HighPart) + \
(LO_T * sppi[i].IdleTime.LowPart));
kernel = (float)((HI_T * sppi[i].KernelTime.HighPart) + \
(LO_T * sppi[i].KernelTime.LowPart));
// kernel time includes idle time on windows
// we return only busy kernel time subtracting
// idle time from kernel time
arg = Py_BuildValue("(ddd)", user,
kernel - idle,
idle);
PyList_Append(retlist, arg);
Py_XDECREF(arg);
}
free(sppi);
FreeLibrary(hNtDll);
return retlist;
} // END NtQuerySystemInformation
} // END malloc SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
} // END GetProcAddress
} // END LoadLibrary
if (sppi) {
free(sppi);
}
if (hNtDll) {
FreeLibrary(hNtDll);
}
PyErr_SetFromWindowsErr(0);
return NULL;
}
/*
* Return process current working directory as a Python string.
*/
static PyObject*
get_process_cwd(PyObject* self, PyObject* args)
{
long pid;
HANDLE processHandle;
PVOID pebAddress;
PVOID rtlUserProcParamsAddress;
UNICODE_STRING currentDirectory;
WCHAR *currentDirectoryContent;
PyObject *returnPyObj = NULL;
PyObject *cwd_from_wchar = NULL;
PyObject *cwd = NULL;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
processHandle = handle_from_pid(pid);
if (processHandle == NULL) {
return NULL;
}
pebAddress = GetPebAddress(processHandle);
// get the address of ProcessParameters
#ifdef _WIN64
if (!ReadProcessMemory(processHandle, (PCHAR)pebAddress + 32,
&rtlUserProcParamsAddress, sizeof(PVOID), NULL))
#else
if (!ReadProcessMemory(processHandle, (PCHAR)pebAddress + 0x10,
&rtlUserProcParamsAddress, sizeof(PVOID), NULL))
#endif
{
CloseHandle(processHandle);
if (GetLastError() == ERROR_PARTIAL_COPY) {
// this occurs quite often with system processes
return AccessDenied();
}
else {
return PyErr_SetFromWindowsErr(0);
}
}
// Read the currentDirectory UNICODE_STRING structure.
// 0x24 refers to "CurrentDirectoryPath" of RTL_USER_PROCESS_PARAMETERS
// structure, see:
// http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/
#ifdef _WIN64
if (!ReadProcessMemory(processHandle, (PCHAR)rtlUserProcParamsAddress + 56,
¤tDirectory, sizeof(currentDirectory), NULL))
#else
if (!ReadProcessMemory(processHandle, (PCHAR)rtlUserProcParamsAddress + 0x24,
¤tDirectory, sizeof(currentDirectory), NULL))
#endif
{
CloseHandle(processHandle);
if (GetLastError() == ERROR_PARTIAL_COPY) {
// this occurs quite often with system processes
return AccessDenied();
}
else {
return PyErr_SetFromWindowsErr(0);
}
}
// allocate memory to hold cwd
currentDirectoryContent = (WCHAR *)malloc(currentDirectory.Length+1);
// read cwd
if (!ReadProcessMemory(processHandle, currentDirectory.Buffer,
currentDirectoryContent, currentDirectory.Length, NULL))
{
CloseHandle(processHandle);
free(currentDirectoryContent);
if (GetLastError() == ERROR_PARTIAL_COPY) {
// this occurs quite often with system processes
return AccessDenied();
}
else {
return PyErr_SetFromWindowsErr(0);
}
}
// null-terminate the string to prevent wcslen from returning
// incorrect length the length specifier is in characters, but
// currentDirectory.Length is in bytes
currentDirectoryContent[(currentDirectory.Length/sizeof(WCHAR))] = '\0';
// convert wchar array to a Python unicode string, and then to UTF8
cwd_from_wchar = PyUnicode_FromWideChar(currentDirectoryContent,
wcslen(currentDirectoryContent));
#if PY_MAJOR_VERSION >= 3
cwd = PyUnicode_FromObject(cwd_from_wchar);
#else
cwd = PyUnicode_AsUTF8String(cwd_from_wchar);
#endif
// decrement the reference count on our temp unicode str to avoid
// mem leak
Py_XDECREF(cwd_from_wchar);
returnPyObj = Py_BuildValue("N", cwd);
CloseHandle(processHandle);
free(currentDirectoryContent);
return returnPyObj;
}
/*
* Resume or suspends a process
*/
int
suspend_resume_process(DWORD pid, int suspend)
{
// a huge thanks to http://www.codeproject.com/KB/threads/pausep.aspx
HANDLE hThreadSnap = NULL;
THREADENTRY32 te32 = {0};
if (pid == 0) {
AccessDenied();
return FALSE;
}
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE) {
PyErr_SetFromWindowsErr(0);
return FALSE;
}
// Fill in the size of the structure before using it
te32.dwSize = sizeof(THREADENTRY32);
if (! Thread32First(hThreadSnap, &te32)) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hThreadSnap);
return FALSE;
}
// Walk the thread snapshot to find all threads of the process.
// If the thread belongs to the process, add its information
// to the display list.
do
{
if (te32.th32OwnerProcessID == pid)
{
HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE,
te32.th32ThreadID);
if (hThread == NULL) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hThread);
CloseHandle(hThreadSnap);
return FALSE;
}
if (suspend == 1)
{
if (SuspendThread(hThread) == (DWORD)-1) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hThread);
CloseHandle(hThreadSnap);
return FALSE;
}
}
else
{
if (ResumeThread(hThread) == (DWORD)-1) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hThread);
CloseHandle(hThreadSnap);
return FALSE;
}
}
CloseHandle(hThread);
}
} while (Thread32Next(hThreadSnap, &te32));
CloseHandle(hThreadSnap);
return TRUE;
}
static PyObject*
suspend_process(PyObject* self, PyObject* args)
{
long pid;
int suspend = 1;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (! suspend_resume_process(pid, suspend)) {
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
resume_process(PyObject* self, PyObject* args)
{
long pid;
int suspend = 0;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (! suspend_resume_process(pid, suspend)) {
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
get_process_num_threads(PyObject* self, PyObject* args)
{
DWORD pid;
PSYSTEM_PROCESS_INFORMATION process;
PVOID buffer;
int num;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_process_info(pid, &process, &buffer) != 1) {
free(buffer);
return NULL;
}
if (pid_is_running(pid) == 0) {
free(buffer);
return NoSuchProcess();
}
num = (int)process->NumberOfThreads;
free(buffer);
return Py_BuildValue("i", num);
}
static PyObject*
get_process_threads(PyObject* self, PyObject* args)
{
PyObject* retList = PyList_New(0);
PyObject* pyTuple = NULL;
HANDLE hThreadSnap = NULL;
THREADENTRY32 te32 = {0};
long pid;
int pid_return;
int rc;
FILETIME ftDummy, ftKernel, ftUser;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (pid == 0) {
// raise AD instead of returning 0 as procexp is able to
// retrieve useful information somehow
return AccessDenied();
}
pid_return = pid_is_running(pid);
if (pid_return == 0) {
return NoSuchProcess();
}
if (pid_return == -1) {
return NULL;
}
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
// Fill in the size of the structure before using it
te32.dwSize = sizeof(THREADENTRY32);
if (! Thread32First(hThreadSnap, &te32)) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hThreadSnap);
return NULL;
}
// Walk the thread snapshot to find all threads of the process.
// If the thread belongs to the process, increase the counter.
do
{
if (te32.th32OwnerProcessID == pid)
{
HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION,
FALSE, te32.th32ThreadID);
if (hThread == NULL) {
// thread has disappeared on us
continue;
}
rc = GetThreadTimes(hThread, &ftDummy, &ftDummy, &ftKernel, &ftUser);
if (rc == 0) {
PyErr_SetFromWindowsErr(0);
CloseHandle(hThread);
CloseHandle(hThreadSnap);
return NULL;
}
/*
user and kernel times are represented as a FILETIME structure
wich contains a 64-bit value representing the number of
100-nanosecond intervals since January 1, 1601 (UTC).
http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx
To convert it into a float representing the seconds that the
process has executed in user/kernel mode I borrowed the code
below from Python's Modules/posixmodule.c
*/
pyTuple = Py_BuildValue("kdd",
te32.th32ThreadID,
(double)(ftUser.dwHighDateTime*429.4967296 + \
ftUser.dwLowDateTime*1e-7),
(double)(ftKernel.dwHighDateTime*429.4967296 + \
ftKernel.dwLowDateTime*1e-7)
);
PyList_Append(retList, pyTuple);
Py_XDECREF(pyTuple);
CloseHandle(hThread);
}
} while (Thread32Next(hThreadSnap, &te32));
CloseHandle(hThreadSnap);
return retList;
}
static PyObject*
get_process_open_files(PyObject* self, PyObject* args)
{
long pid;
HANDLE processHandle;
DWORD access = PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION;
PyObject* filesList;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
processHandle = handle_from_pid_waccess(pid, access);
if (processHandle == NULL) {
return NULL;
}
filesList = get_open_files(pid, processHandle);
CloseHandle(processHandle);
if (filesList == NULL) {
return PyErr_SetFromWindowsErr(0);
}
return filesList;
}
/*
Accept a filename's drive in native format like "\Device\HarddiskVolume1\"
and return the corresponding drive letter (e.g. "C:\\").
If no match is found return an empty string.
*/
static PyObject*
win32_QueryDosDevice(PyObject* self, PyObject* args)
{
LPCTSTR lpDevicePath;
TCHAR d = TEXT('A');
TCHAR szBuff[5];
if (!PyArg_ParseTuple(args, "s", &lpDevicePath)) {
return NULL;
}
while(d <= TEXT('Z'))
{
TCHAR szDeviceName[3] = {d,TEXT(':'),TEXT('\0')};
TCHAR szTarget[512] = {0};
if (QueryDosDevice(szDeviceName, szTarget, 511) != 0){
//_tprintf (TEXT("%c:\\ => %s\n"), d, szTarget);
if(_tcscmp(lpDevicePath, szTarget) == 0) {
_stprintf(szBuff, TEXT("%c:"), d);
return Py_BuildValue("s", szBuff);
}
}
d++;
}
return Py_BuildValue("s", "");
}
/*
* Return process username as a "DOMAIN//USERNAME" string.
*/
static PyObject*
get_process_username(PyObject* self, PyObject* args)
{
long pid;
HANDLE processHandle;
HANDLE tokenHandle;
PTOKEN_USER user;
ULONG bufferSize;
PTSTR name;
ULONG nameSize;
PTSTR domainName;
ULONG domainNameSize;
SID_NAME_USE nameUse;
PTSTR fullName;
PyObject* returnObject;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
processHandle = handle_from_pid_waccess(pid, PROCESS_QUERY_INFORMATION);
if (processHandle == NULL) {
return NULL;
}
if (!OpenProcessToken(processHandle, TOKEN_QUERY, &tokenHandle)) {
CloseHandle(processHandle);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(processHandle);
/* Get the user SID. */
bufferSize = 0x100;
user = malloc(bufferSize);
if (!GetTokenInformation(tokenHandle,
TokenUser,
user,
bufferSize,
&bufferSize))
{
free(user);
user = malloc(bufferSize);
if (!GetTokenInformation(tokenHandle,
TokenUser,
user,
bufferSize,
&bufferSize))
{
free(user);
CloseHandle(tokenHandle);
return PyErr_SetFromWindowsErr(0);
}
}
CloseHandle(tokenHandle);
/* Resolve the SID to a name. */
nameSize = 0x100;
domainNameSize = 0x100;
name = malloc(nameSize * sizeof(TCHAR));
domainName = malloc(domainNameSize * sizeof(TCHAR));
if (!LookupAccountSid(NULL, user->User.Sid, name, &nameSize, domainName,
&domainNameSize, &nameUse))
{
free(name);
free(domainName);
name = malloc(nameSize * sizeof(TCHAR));
domainName = malloc(domainNameSize * sizeof(TCHAR));
if (!LookupAccountSid(NULL, user->User.Sid, name, &nameSize, domainName,
&domainNameSize, &nameUse))
{
free(name);
free(domainName);
free(user);
return PyErr_SetFromWindowsErr(0);
}
}
nameSize = _tcslen(name);
domainNameSize = _tcslen(domainName);
/* Build the full username string. */
fullName = malloc((domainNameSize + 1 + nameSize + 1) * sizeof(TCHAR));
memcpy(fullName, domainName, domainNameSize);
fullName[domainNameSize] = '\\';
memcpy(&fullName[domainNameSize + 1], name, nameSize);
fullName[domainNameSize + 1 + nameSize] = '\0';
returnObject = Py_BuildValue("s", fullName);
free(fullName);
free(name);
free(domainName);
free(user);
return returnObject;
}
#define BYTESWAP_USHORT(x) ((((USHORT)(x) << 8) | ((USHORT)(x) >> 8)) & 0xffff)
#ifndef AF_INET6
#define AF_INET6 23
#endif
static char *state_to_string(ULONG state)
{
switch (state)
{
case MIB_TCP_STATE_CLOSED:
return "CLOSE";
case MIB_TCP_STATE_LISTEN:
return "LISTEN";
case MIB_TCP_STATE_SYN_SENT:
return "SYN_SENT";
case MIB_TCP_STATE_SYN_RCVD:
return "SYN_RECV";
case MIB_TCP_STATE_ESTAB:
return "ESTABLISHED";
case MIB_TCP_STATE_FIN_WAIT1:
return "FIN_WAIT1";
case MIB_TCP_STATE_FIN_WAIT2:
return "FIN_WAIT2";
case MIB_TCP_STATE_CLOSE_WAIT:
return "CLOSE_WAIT";
case MIB_TCP_STATE_CLOSING:
return "CLOSING";
case MIB_TCP_STATE_LAST_ACK:
return "LAST_ACK";
case MIB_TCP_STATE_TIME_WAIT:
return "TIME_WAIT";
case MIB_TCP_STATE_DELETE_TCB:
return "DELETE_TCB";
default:
return "";
}
}
/* mingw support */
#ifndef _IPRTRMIB_H
typedef struct _MIB_TCP6ROW_OWNER_PID
{
UCHAR ucLocalAddr[16];
DWORD dwLocalScopeId;
DWORD dwLocalPort;
UCHAR ucRemoteAddr[16];
DWORD dwRemoteScopeId;
DWORD dwRemotePort;
DWORD dwState;
DWORD dwOwningPid;
} MIB_TCP6ROW_OWNER_PID, *PMIB_TCP6ROW_OWNER_PID;
typedef struct _MIB_TCP6TABLE_OWNER_PID
{
DWORD dwNumEntries;
MIB_TCP6ROW_OWNER_PID table[ANY_SIZE];
} MIB_TCP6TABLE_OWNER_PID, *PMIB_TCP6TABLE_OWNER_PID;
#endif
#ifndef __IPHLPAPI_H__
typedef struct in6_addr {
union {
UCHAR Byte[16];
USHORT Word[8];
} u;
} IN6_ADDR, *PIN6_ADDR, FAR *LPIN6_ADDR;
typedef enum _UDP_TABLE_CLASS {
UDP_TABLE_BASIC,
UDP_TABLE_OWNER_PID,
UDP_TABLE_OWNER_MODULE
} UDP_TABLE_CLASS, *PUDP_TABLE_CLASS;
typedef struct _MIB_UDPROW_OWNER_PID {
DWORD dwLocalAddr;
DWORD dwLocalPort;
DWORD dwOwningPid;
} MIB_UDPROW_OWNER_PID, *PMIB_UDPROW_OWNER_PID;
typedef struct _MIB_UDPTABLE_OWNER_PID
{
DWORD dwNumEntries;
MIB_UDPROW_OWNER_PID table[ANY_SIZE];
} MIB_UDPTABLE_OWNER_PID, *PMIB_UDPTABLE_OWNER_PID;
#endif
/* end of mingw support */
typedef struct _MIB_UDP6ROW_OWNER_PID {
UCHAR ucLocalAddr[16];
DWORD dwLocalScopeId;
DWORD dwLocalPort;
DWORD dwOwningPid;
} MIB_UDP6ROW_OWNER_PID, *PMIB_UDP6ROW_OWNER_PID;
typedef struct _MIB_UDP6TABLE_OWNER_PID
{
DWORD dwNumEntries;
MIB_UDP6ROW_OWNER_PID table[ANY_SIZE];
} MIB_UDP6TABLE_OWNER_PID, *PMIB_UDP6TABLE_OWNER_PID;
#define ConnDecrefPyObjs() Py_DECREF(_AF_INET); \
Py_DECREF(_AF_INET6);\
Py_DECREF(_SOCK_STREAM);\
Py_DECREF(_SOCK_DGRAM);
/*
* Return a list of network connections opened by a process
*/
static PyObject*
get_process_connections(PyObject* self, PyObject* args)
{
static long null_address[4] = { 0, 0, 0, 0 };
unsigned long pid;
PyObject* connectionsList;
PyObject* connectionTuple;
PyObject *af_filter = NULL;
PyObject *type_filter = NULL;
PyObject *_AF_INET = PyLong_FromLong((long)AF_INET);
PyObject *_AF_INET6 = PyLong_FromLong((long)AF_INET6);
PyObject *_SOCK_STREAM = PyLong_FromLong((long)SOCK_STREAM);
PyObject *_SOCK_DGRAM = PyLong_FromLong((long)SOCK_DGRAM);
typedef PSTR (NTAPI *_RtlIpv4AddressToStringA)(struct in_addr *,
PSTR /* __out_ecount(16) */);
_RtlIpv4AddressToStringA rtlIpv4AddressToStringA;
typedef PSTR (NTAPI *_RtlIpv6AddressToStringA)(struct in6_addr *,
PSTR /* __out_ecount(65) */);
_RtlIpv6AddressToStringA rtlIpv6AddressToStringA;
typedef DWORD (WINAPI *_GetExtendedTcpTable)(PVOID, PDWORD, BOOL, ULONG,
TCP_TABLE_CLASS, ULONG);
_GetExtendedTcpTable getExtendedTcpTable;
typedef DWORD (WINAPI *_GetExtendedUdpTable)(PVOID, PDWORD, BOOL, ULONG,
UDP_TABLE_CLASS, ULONG);
_GetExtendedUdpTable getExtendedUdpTable;
PVOID table;
DWORD tableSize;
PMIB_TCPTABLE_OWNER_PID tcp4Table;
PMIB_UDPTABLE_OWNER_PID udp4Table;
PMIB_TCP6TABLE_OWNER_PID tcp6Table;
PMIB_UDP6TABLE_OWNER_PID udp6Table;
ULONG i;
CHAR addressBufferLocal[65];
PyObject* addressTupleLocal;
CHAR addressBufferRemote[65];
PyObject* addressTupleRemote;
if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter)) {
ConnDecrefPyObjs();
return NULL;
}
if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) {
ConnDecrefPyObjs();
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
return NULL;
}
if (pid_is_running(pid) == 0) {
ConnDecrefPyObjs();
return NoSuchProcess();
}
/* Import some functions. */
{
HMODULE ntdll;
HMODULE iphlpapi;
ntdll = LoadLibrary(TEXT("ntdll.dll"));
rtlIpv4AddressToStringA = (_RtlIpv4AddressToStringA)GetProcAddress(ntdll,
"RtlIpv4AddressToStringA");
rtlIpv6AddressToStringA = (_RtlIpv6AddressToStringA)GetProcAddress(ntdll,
"RtlIpv6AddressToStringA");
/* TODO: Check these two function pointers */
iphlpapi = LoadLibrary(TEXT("iphlpapi.dll"));
getExtendedTcpTable = (_GetExtendedTcpTable)GetProcAddress(iphlpapi,
"GetExtendedTcpTable");
getExtendedUdpTable = (_GetExtendedUdpTable)GetProcAddress(iphlpapi,
"GetExtendedUdpTable");
FreeLibrary(ntdll);
FreeLibrary(iphlpapi);
}
if ((getExtendedTcpTable == NULL) || (getExtendedUdpTable == NULL)) {
PyErr_SetString(PyExc_NotImplementedError,
"feature not supported on this Windows version");
ConnDecrefPyObjs();
return NULL;
}
connectionsList = PyList_New(0);
/* TCP IPv4 */
if ((PySequence_Contains(af_filter, _AF_INET) == 1) &&
(PySequence_Contains(type_filter, _SOCK_STREAM) == 1))
{
tableSize = 0;
getExtendedTcpTable(NULL, &tableSize, FALSE, AF_INET,
TCP_TABLE_OWNER_PID_ALL, 0);
table = malloc(tableSize);
if (getExtendedTcpTable(table, &tableSize, FALSE, AF_INET,
TCP_TABLE_OWNER_PID_ALL, 0) == 0)
{
tcp4Table = table;
for (i = 0; i < tcp4Table->dwNumEntries; i++)
{
if (tcp4Table->table[i].dwOwningPid != pid) {
continue;
}
if (tcp4Table->table[i].dwLocalAddr != 0 ||
tcp4Table->table[i].dwLocalPort != 0)
{
struct in_addr addr;
addr.S_un.S_addr = tcp4Table->table[i].dwLocalAddr;
rtlIpv4AddressToStringA(&addr, addressBufferLocal);
addressTupleLocal = Py_BuildValue("(si)", addressBufferLocal,
BYTESWAP_USHORT(tcp4Table->table[i].dwLocalPort));
}
else
{
addressTupleLocal = PyTuple_New(0);
}
// On Windows <= XP, remote addr is filled even if socket
// is in LISTEN mode in which case we just ignore it.
if ((tcp4Table->table[i].dwRemoteAddr != 0 ||
tcp4Table->table[i].dwRemotePort != 0) &&
(tcp4Table->table[i].dwState != MIB_TCP_STATE_LISTEN))
{
struct in_addr addr;
addr.S_un.S_addr = tcp4Table->table[i].dwRemoteAddr;
rtlIpv4AddressToStringA(&addr, addressBufferRemote);
addressTupleRemote = Py_BuildValue("(si)", addressBufferRemote,
BYTESWAP_USHORT(tcp4Table->table[i].dwRemotePort));
}
else
{
addressTupleRemote = PyTuple_New(0);
}
connectionTuple = Py_BuildValue("(iiiNNs)",
-1,
AF_INET,
SOCK_STREAM,
addressTupleLocal,
addressTupleRemote,
state_to_string(tcp4Table->table[i].dwState)
);
PyList_Append(connectionsList, connectionTuple);
Py_DECREF(connectionTuple);
}
}
free(table);
}
/* TCP IPv6 */
if ((PySequence_Contains(af_filter, _AF_INET6) == 1) &&
(PySequence_Contains(type_filter, _SOCK_STREAM) == 1))
{
tableSize = 0;
getExtendedTcpTable(NULL, &tableSize, FALSE, AF_INET6,
TCP_TABLE_OWNER_PID_ALL, 0);
table = malloc(tableSize);
if (getExtendedTcpTable(table, &tableSize, FALSE, AF_INET6,
TCP_TABLE_OWNER_PID_ALL, 0) == 0)
{
tcp6Table = table;
for (i = 0; i < tcp6Table->dwNumEntries; i++)
{
if (tcp6Table->table[i].dwOwningPid != pid) {
continue;
}
if (memcmp(tcp6Table->table[i].ucLocalAddr, null_address, 16) != 0 ||
tcp6Table->table[i].dwLocalPort != 0)
{
struct in6_addr addr;
memcpy(&addr, tcp6Table->table[i].ucLocalAddr, 16);
rtlIpv6AddressToStringA(&addr, addressBufferLocal);
addressTupleLocal = Py_BuildValue("(si)", addressBufferLocal,
BYTESWAP_USHORT(tcp6Table->table[i].dwLocalPort));
}
else
{
addressTupleLocal = PyTuple_New(0);
}
// On Windows <= XP, remote addr is filled even if socket
// is in LISTEN mode in which case we just ignore it.
if ((memcmp(tcp6Table->table[i].ucRemoteAddr, null_address, 16) != 0 ||
tcp6Table->table[i].dwRemotePort != 0) &&
(tcp6Table->table[i].dwState != MIB_TCP_STATE_LISTEN))
{
struct in6_addr addr;
memcpy(&addr, tcp6Table->table[i].ucRemoteAddr, 16);
rtlIpv6AddressToStringA(&addr, addressBufferRemote);
addressTupleRemote = Py_BuildValue("(si)", addressBufferRemote,
BYTESWAP_USHORT(tcp6Table->table[i].dwRemotePort));
}
else
{
addressTupleRemote = PyTuple_New(0);
}
connectionTuple = Py_BuildValue("(iiiNNs)",
-1,
AF_INET6,
SOCK_STREAM,
addressTupleLocal,
addressTupleRemote,
state_to_string(tcp6Table->table[i].dwState)
);
PyList_Append(connectionsList, connectionTuple);
Py_DECREF(connectionTuple);
}
}
free(table);
}
/* UDP IPv4 */
if ((PySequence_Contains(af_filter, _AF_INET) == 1) &&
(PySequence_Contains(type_filter, _SOCK_DGRAM) == 1))
{
tableSize = 0;
getExtendedUdpTable(NULL, &tableSize, FALSE, AF_INET,
UDP_TABLE_OWNER_PID, 0);
table = malloc(tableSize);
if (getExtendedUdpTable(table, &tableSize, FALSE, AF_INET,
UDP_TABLE_OWNER_PID, 0) == 0)
{
udp4Table = table;
for (i = 0; i < udp4Table->dwNumEntries; i++)
{
if (udp4Table->table[i].dwOwningPid != pid) {
continue;
}
if (udp4Table->table[i].dwLocalAddr != 0 ||
udp4Table->table[i].dwLocalPort != 0)
{
struct in_addr addr;
addr.S_un.S_addr = udp4Table->table[i].dwLocalAddr;
rtlIpv4AddressToStringA(&addr, addressBufferLocal);
addressTupleLocal = Py_BuildValue("(si)", addressBufferLocal,
BYTESWAP_USHORT(udp4Table->table[i].dwLocalPort));
}
else
{
addressTupleLocal = PyTuple_New(0);
}
connectionTuple = Py_BuildValue("(iiiNNs)",
-1,
AF_INET,
SOCK_DGRAM,
addressTupleLocal,
PyTuple_New(0),
""
);
PyList_Append(connectionsList, connectionTuple);
Py_DECREF(connectionTuple);
}
}
free(table);
}
/* UDP IPv6 */
if ((PySequence_Contains(af_filter, _AF_INET6) == 1) &&
(PySequence_Contains(type_filter, _SOCK_DGRAM) == 1))
{
tableSize = 0;
getExtendedUdpTable(NULL, &tableSize, FALSE,
AF_INET6, UDP_TABLE_OWNER_PID, 0);
table = malloc(tableSize);
if (getExtendedUdpTable(table, &tableSize, FALSE, AF_INET6,
UDP_TABLE_OWNER_PID, 0) == 0)
{
udp6Table = table;
for (i = 0; i < udp6Table->dwNumEntries; i++)
{
if (udp6Table->table[i].dwOwningPid != pid) {
continue;
}
if (memcmp(udp6Table->table[i].ucLocalAddr, null_address, 16) != 0 ||
udp6Table->table[i].dwLocalPort != 0)
{
struct in6_addr addr;
memcpy(&addr, udp6Table->table[i].ucLocalAddr, 16);
rtlIpv6AddressToStringA(&addr, addressBufferLocal);
addressTupleLocal = Py_BuildValue("(si)", addressBufferLocal,
BYTESWAP_USHORT(udp6Table->table[i].dwLocalPort));
}
else
{
addressTupleLocal = PyTuple_New(0);
}
connectionTuple = Py_BuildValue("(iiiNNs)",
-1,
AF_INET6,
SOCK_DGRAM,
addressTupleLocal,
PyTuple_New(0),
""
);
PyList_Append(connectionsList, connectionTuple);
Py_DECREF(connectionTuple);
}
}
free(table);
}
ConnDecrefPyObjs();
return connectionsList;
}
/*
* Get process priority as a Python integer.
*/
static PyObject*
get_process_priority(PyObject* self, PyObject* args)
{
long pid;
DWORD priority;
HANDLE hProcess;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid(pid);
if (hProcess == NULL) {
return NULL;
}
priority = GetPriorityClass(hProcess);
CloseHandle(hProcess);
if (priority == 0) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
return Py_BuildValue("i", priority);
}
/*
* Set process priority.
*/
static PyObject*
set_process_priority(PyObject* self, PyObject* args)
{
long pid;
int priority;
int retval;
HANDLE hProcess;
DWORD dwDesiredAccess = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION;
if (! PyArg_ParseTuple(args, "li", &pid, &priority)) {
return NULL;
}
hProcess = handle_from_pid_waccess(pid, dwDesiredAccess);
if (hProcess == NULL) {
return NULL;
}
retval = SetPriorityClass(hProcess, priority);
CloseHandle(hProcess);
if (retval == 0) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
/*
* Return a Python tuple referencing process I/O counters.
*/
static PyObject*
get_process_io_counters(PyObject* self, PyObject* args)
{
DWORD pid;
HANDLE hProcess;
IO_COUNTERS IoCounters;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
return NULL;
}
if (! GetProcessIoCounters(hProcess, &IoCounters)) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(hProcess);
return Py_BuildValue("(KKKK)", IoCounters.ReadOperationCount,
IoCounters.WriteOperationCount,
IoCounters.ReadTransferCount,
IoCounters.WriteTransferCount);
}
/*
* Return process CPU affinity as a bitmask
*/
static PyObject*
get_process_cpu_affinity(PyObject* self, PyObject* args)
{
DWORD pid;
HANDLE hProcess;
PDWORD_PTR proc_mask;
PDWORD_PTR system_mask;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid(pid);
if (hProcess == NULL) {
return NULL;
}
if (GetProcessAffinityMask(hProcess, &proc_mask, &system_mask) == 0) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(hProcess);
return Py_BuildValue("k", (unsigned long)proc_mask);
}
/*
* Set process CPU affinity
*/
static PyObject*
set_process_cpu_affinity(PyObject* self, PyObject* args)
{
DWORD pid;
HANDLE hProcess;
DWORD dwDesiredAccess = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION;
DWORD_PTR mask;
if (! PyArg_ParseTuple(args, "lk", &pid, &mask)) {
return NULL;
}
hProcess = handle_from_pid_waccess(pid, dwDesiredAccess);
if (hProcess == NULL) {
return NULL;
}
if (SetProcessAffinityMask(hProcess, mask) == 0) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(hProcess);
Py_INCREF(Py_None);
return Py_None;
}
/*
* Return True if one of the process threads is in a waiting or
* suspended status.
*/
static PyObject*
is_process_suspended(PyObject* self, PyObject* args)
{
DWORD pid;
ULONG i;
PSYSTEM_PROCESS_INFORMATION process;
PVOID buffer;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_process_info(pid, &process, &buffer) != 1) {
free(buffer);
return NULL;
}
if (pid_is_running(pid) == 0) {
free(buffer);
return NoSuchProcess();
}
for (i = 0; i < process->NumberOfThreads; i++) {
if (process->Threads[i].ThreadState != Waiting ||
process->Threads[i].WaitReason != Suspended)
{
free(buffer);
Py_RETURN_FALSE;
}
}
free(buffer);
Py_RETURN_TRUE;
}
/*
* Return path's disk total and free as a Python tuple.
*/
static PyObject*
get_disk_usage(PyObject* self, PyObject* args)
{
BOOL retval;
ULARGE_INTEGER _, total, free;
LPCTSTR path;
if (! PyArg_ParseTuple(args, "s", &path)) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS
retval = GetDiskFreeSpaceEx(path, &_, &total, &free);
Py_END_ALLOW_THREADS
if (retval == 0) {
return PyErr_SetFromWindowsErr(0);
}
return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
}
/*
* Return a Python list of named tuples with overall network I/O information
*/
static PyObject*
get_network_io_counters(PyObject* self, PyObject* args)
{
PyObject* py_retdict = PyDict_New();
PyObject* py_nic_info = NULL;
PyObject* py_pre_nic_name = NULL;
PyObject* py_nic_name = NULL;
int attempts = 0;
int outBufLen = 15000;
DWORD dwRetVal = 0;
MIB_IFROW *pIfRow;
ULONG flags = 0;
ULONG family = AF_UNSPEC;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
do {
pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(outBufLen);
if (pAddresses == NULL) {
Py_DECREF(py_retdict);
PyErr_SetString(PyExc_RuntimeError,
"memory allocation failed for IP_ADAPTER_ADDRESSES struct.");
return NULL;
}
dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses,
&outBufLen);
if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
free(pAddresses);
pAddresses = NULL;
}
else {
break;
}
attempts++;
} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (attempts < 3));
if (dwRetVal != NO_ERROR) {
Py_DECREF(py_retdict);
PyErr_SetString(PyExc_RuntimeError, "GetAdaptersAddresses() failed.");
return NULL;
}
pCurrAddresses = pAddresses;
while (pCurrAddresses) {
pIfRow = (MIB_IFROW *) malloc(sizeof(MIB_IFROW));
if (pIfRow == NULL) {
Py_DECREF(py_retdict);
Py_XDECREF(py_pre_nic_name);
Py_XDECREF(py_nic_name);
Py_XDECREF(py_nic_info);
PyErr_SetString(PyExc_RuntimeError,
"memory allocation failed for MIB_IFROW struct.");
return NULL;
}
pIfRow->dwIndex = pCurrAddresses->IfIndex;
dwRetVal = GetIfEntry(pIfRow);
if (dwRetVal != NO_ERROR) {
Py_DECREF(py_retdict);
Py_XDECREF(py_pre_nic_name);
Py_XDECREF(py_nic_name);
Py_XDECREF(py_nic_info);
PyErr_SetString(PyExc_RuntimeError,
"GetIfEntry() failed.");
return NULL;
}
py_nic_info = Py_BuildValue("(IIII)",
pIfRow->dwOutOctets,
pIfRow->dwInOctets,
pIfRow->dwOutUcastPkts,
pIfRow->dwInUcastPkts);
py_pre_nic_name = PyUnicode_FromWideChar(
pCurrAddresses->FriendlyName,
wcslen(pCurrAddresses->FriendlyName));
py_nic_name = PyUnicode_FromObject(py_pre_nic_name);
PyDict_SetItem(py_retdict, py_nic_name, py_nic_info);
Py_XDECREF(py_pre_nic_name);
Py_XDECREF(py_nic_name);
Py_XDECREF(py_nic_info);
free(pIfRow);
pCurrAddresses = pCurrAddresses->Next;
}
free(pAddresses);
return py_retdict;
}
/*
* Return a Python dict of tuples for disk I/O information
*/
static PyObject*
get_disk_io_counters(PyObject* self, PyObject* args)
{
PyObject* py_retdict = PyDict_New();
PyObject* py_disk_info;
DISK_PERFORMANCE diskPerformance;
DWORD dwSize;
HANDLE hDevice = NULL;
char szDevice[MAX_PATH];
char szDeviceDisplay[MAX_PATH];
int devNum;
for (devNum = 0;; devNum++) {
sprintf (szDevice, "\\\\.\\PhysicalDrive%d", devNum);
hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE) {
// what happens if we get an invalid handle on the first disk?
// we might end up with an empty dict incorrectly in some cases
break;
}
if (DeviceIoControl(hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
&diskPerformance, sizeof(DISK_PERFORMANCE),
&dwSize, NULL))
{
sprintf (szDeviceDisplay, "PhysicalDrive%d", devNum);
py_disk_info = Py_BuildValue("(IILLLL)",
diskPerformance.ReadCount,
diskPerformance.WriteCount,
diskPerformance.BytesRead,
diskPerformance.BytesWritten,
(diskPerformance.ReadTime.QuadPart
* 10) / 1000,
(diskPerformance.WriteTime.QuadPart
* 10) / 1000);
PyDict_SetItemString(py_retdict,
szDeviceDisplay,
py_disk_info);
Py_XDECREF(py_disk_info);
}
else {
// XXX we might get here with ERROR_INSUFFICIENT_BUFFER when
// compiling with mingw32; not sure what to do.
//return PyErr_SetFromWindowsErr(0);
;;
}
CloseHandle(hDevice);
}
return py_retdict;
}
static char *get_drive_type(int type)
{
switch (type) {
case DRIVE_FIXED:
return "fixed";
case DRIVE_CDROM:
return "cdrom";
case DRIVE_REMOVABLE:
return "removable";
case DRIVE_UNKNOWN:
return "unknown";
case DRIVE_NO_ROOT_DIR:
return "unmounted";
case DRIVE_REMOTE:
return "remote";
case DRIVE_RAMDISK:
return "ramdisk";
default:
return "?";
}
}
#define _ARRAYSIZE(a) (sizeof(a)/sizeof(a[0]))
/*
* Return disk partitions as a list of tuples such as
* (drive_letter, drive_letter, type, "")
*/
static PyObject*
get_disk_partitions(PyObject* self, PyObject* args)
{
DWORD num_bytes;
char drive_strings[255];
char* drive_letter = drive_strings;
int all;
int type;
int ret;
char opts[20];
LPTSTR fs_type[MAX_PATH + 1] = { 0 };
DWORD pflags = 0;
PyObject* py_all;
PyObject* py_retlist = PyList_New(0);
PyObject* py_tuple = NULL;
if (! PyArg_ParseTuple(args, "O", &py_all)) {
return NULL;
}
all = PyObject_IsTrue(py_all);
Py_BEGIN_ALLOW_THREADS
num_bytes = GetLogicalDriveStrings(254, drive_letter);
Py_END_ALLOW_THREADS
if (num_bytes == 0) {
return PyErr_SetFromWindowsErr(0);
}
while (*drive_letter != 0) {
opts[0] = 0;
fs_type[0] = 0;
Py_BEGIN_ALLOW_THREADS
type = GetDriveType(drive_letter);
Py_END_ALLOW_THREADS
// by default we only show hard drives and cd-roms
if (all == 0) {
if ((type == DRIVE_UNKNOWN) ||
(type == DRIVE_NO_ROOT_DIR) ||
(type == DRIVE_REMOTE) ||
(type == DRIVE_RAMDISK)) {
goto next;
}
// floppy disk: skip it by default as it introduces a
// considerable slowdown.
if ((type == DRIVE_REMOVABLE) && (strcmp(drive_letter, "A:\\") == 0)) {
goto next;
}
}
ret = GetVolumeInformation(drive_letter, NULL, _ARRAYSIZE(drive_letter),
NULL, NULL, &pflags, fs_type,
_ARRAYSIZE(fs_type));
if (ret == 0) {
// We might get here in case of a floppy hard drive, in
// which case the error is (21, "device not ready").
// Let's pretend it didn't happen as we already have
// the drive name and type ('removable').
strcat(opts, "");
SetLastError(0);
}
else {
if (pflags & FILE_READ_ONLY_VOLUME) {
strcat(opts, "ro");
}
else {
strcat(opts, "rw");
}
if (pflags & FILE_VOLUME_IS_COMPRESSED) {
strcat(opts, ",compressed");
}
}
if (strlen(opts) > 0) {
strcat(opts, ",");
}
strcat(opts, get_drive_type(type));
py_tuple = Py_BuildValue("(ssss)",
drive_letter,
drive_letter,
fs_type, // either FAT, FAT32, NTFS, HPFS, CDFS, UDF or NWFS
opts);
PyList_Append(py_retlist, py_tuple);
Py_DECREF(py_tuple);
goto next;
next:
drive_letter = strchr(drive_letter, 0) + 1;
}
return py_retlist;
}
#ifdef UNICODE
#define WTSOpenServer WTSOpenServerW
#else
#define WTSOpenServer WTSOpenServerA
#endif
/*
* Return a Python dict of tuples for disk I/O information
*/
static PyObject*
get_system_users(PyObject* self, PyObject* args)
{
PyObject* py_retlist = PyList_New(0);
PyObject* py_tuple = NULL;
PyObject* py_address = NULL;
HANDLE hServer = NULL;
LPTSTR buffer_user = NULL;
LPTSTR buffer_addr = NULL;
PWTS_SESSION_INFO sessions = NULL;
DWORD count;
DWORD i;
DWORD sessionId;
DWORD bytes;
PWTS_CLIENT_ADDRESS address;
char address_str[50];
long long unix_time;
PWINSTATIONQUERYINFORMATIONW WinStationQueryInformationW;
WINSTATION_INFO station_info;
HINSTANCE hInstWinSta = NULL;
ULONG returnLen;
hInstWinSta = LoadLibraryA("winsta.dll");
WinStationQueryInformationW = (PWINSTATIONQUERYINFORMATIONW)
GetProcAddress(hInstWinSta, "WinStationQueryInformationW");
hServer = WTSOpenServer('\0');
if (hServer == NULL) {
goto error;
}
if (WTSEnumerateSessions(hServer, 0, 1, &sessions, &count) == 0) {
goto error;
}
for (i=0; i<count; i++) {
sessionId = sessions[i].SessionId;
if (buffer_user != NULL) {
WTSFreeMemory(buffer_user);
}
if (buffer_addr != NULL) {
WTSFreeMemory(buffer_addr);
}
buffer_user = NULL;
buffer_addr = NULL;
// username
bytes = 0;
if (WTSQuerySessionInformation(hServer, sessionId, WTSUserName,
&buffer_user, &bytes) == 0) {
goto error;
}
if (bytes == 1) {
continue;
}
// address
bytes = 0;
if (WTSQuerySessionInformation(hServer, sessionId, WTSClientAddress,
&buffer_addr, &bytes) == 0) {
goto error;
}
address = (PWTS_CLIENT_ADDRESS)buffer_addr;
if (address->AddressFamily == 0) { // AF_INET
sprintf(address_str, "%u.%u.%u.%u", address->Address[0],
address->Address[1],
address->Address[2],
address->Address[3]);
py_address = Py_BuildValue("s", address_str);
}
else {
py_address = Py_None;
}
// login time
if (!WinStationQueryInformationW(hServer,
sessionId,
WinStationInformation,
&station_info,
sizeof(station_info),
&returnLen))
{
goto error;
}
unix_time = ((LONGLONG)station_info.ConnectTime.dwHighDateTime) << 32;
unix_time += station_info.ConnectTime.dwLowDateTime - 116444736000000000LL;
unix_time /= 10000000;
py_tuple = Py_BuildValue("sOd", buffer_user,
py_address,
(double)unix_time);
PyList_Append(py_retlist, py_tuple);
Py_XDECREF(py_address);
Py_XDECREF(py_tuple);
}
WTSCloseServer(hServer);
WTSFreeMemory(sessions);
WTSFreeMemory(buffer_user);
WTSFreeMemory(buffer_addr);
FreeLibrary(hInstWinSta);
return py_retlist;
error:
if (hInstWinSta != NULL) {
FreeLibrary(hInstWinSta);
}
if (hServer != NULL) {
WTSCloseServer(hServer);
}
if (sessions != NULL) {
WTSFreeMemory(sessions);
}
if (buffer_user != NULL) {
WTSFreeMemory(buffer_user);
}
if (buffer_addr != NULL) {
WTSFreeMemory(buffer_addr);
}
return PyErr_SetFromWindowsErr(0);
}
/*
* Return the number of handles opened by process.
*/
static PyObject*
get_process_num_handles(PyObject* self, PyObject* args)
{
DWORD pid;
HANDLE hProcess;
DWORD handleCount;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
return NULL;
}
if (! GetProcessHandleCount(hProcess, &handleCount)) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
}
CloseHandle(hProcess);
return Py_BuildValue("k", handleCount);
}
static char *get_region_protection_string(ULONG protection)
{
switch (protection & 0xff) {
case PAGE_NOACCESS:
return "";
case PAGE_READONLY:
return "r";
case PAGE_READWRITE:
return "rw";
case PAGE_WRITECOPY:
return "wc";
case PAGE_EXECUTE:
return "x";
case PAGE_EXECUTE_READ:
return "xr";
case PAGE_EXECUTE_READWRITE:
return "xrw";
case PAGE_EXECUTE_WRITECOPY:
return "xwc";
default:
return "?";
}
}
/*
* Return a list of process's memory mappings.
*/
static PyObject*
get_process_memory_maps(PyObject* self, PyObject* args)
{
DWORD pid;
HANDLE hProcess;
MEMORY_BASIC_INFORMATION basicInfo;
PVOID baseAddress;
PVOID previousAllocationBase;
CHAR mappedFileName[MAX_PATH];
SYSTEM_INFO system_info;
LPVOID maxAddr;
PyObject* py_list = PyList_New(0);
PyObject* py_tuple;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
return NULL;
}
GetSystemInfo(&system_info);
maxAddr = system_info.lpMaximumApplicationAddress;
baseAddress = NULL;
previousAllocationBase = NULL;
while (VirtualQueryEx(hProcess, baseAddress, &basicInfo,
sizeof(MEMORY_BASIC_INFORMATION)))
{
if (baseAddress > maxAddr) {
break;
}
if (GetMappedFileNameA(hProcess, baseAddress, mappedFileName,
sizeof(mappedFileName)))
{
py_tuple = Py_BuildValue("(nssI)",
(ULONG_PTR)baseAddress,
get_region_protection_string(basicInfo.Protect),
mappedFileName,
basicInfo.RegionSize
);
PyList_Append(py_list, py_tuple);
Py_DECREF(py_tuple);
}
previousAllocationBase = basicInfo.AllocationBase;
baseAddress = (PCHAR)baseAddress + basicInfo.RegionSize;
}
CloseHandle(hProcess);
return py_list;
}
// ------------------------ Python init ---------------------------
static PyMethodDef
PsutilMethods[] =
{
// --- per-process functions
{"get_process_name", get_process_name, METH_VARARGS,
"Return process name"},
{"get_process_cmdline", get_process_cmdline, METH_VARARGS,
"Return process cmdline as a list of cmdline arguments"},
{"get_process_exe", get_process_exe, METH_VARARGS,
"Return path of the process executable"},
{"get_process_ppid", get_process_ppid, METH_VARARGS,
"Return process ppid as an integer"},
{"kill_process", kill_process, METH_VARARGS,
"Kill the process identified by the given PID"},
{"get_process_cpu_times", get_process_cpu_times, METH_VARARGS,
"Return tuple of user/kern time for the given PID"},
{"get_process_create_time", get_process_create_time, METH_VARARGS,
"Return a float indicating the process create time expressed in "
"seconds since the epoch"},
{"get_memory_info", get_memory_info, METH_VARARGS,
"Return a tuple of RSS/VMS memory information"},
{"get_process_cwd", get_process_cwd, METH_VARARGS,
"Return process current working directory"},
{"suspend_process", suspend_process, METH_VARARGS,
"Suspend a process"},
{"resume_process", resume_process, METH_VARARGS,
"Resume a process"},
{"get_process_open_files", get_process_open_files, METH_VARARGS,
"Return files opened by process"},
{"get_process_username", get_process_username, METH_VARARGS,
"Return the username of a process"},
{"get_process_connections", get_process_connections, METH_VARARGS,
"Return the network connections of a process"},
{"get_process_num_threads", get_process_num_threads, METH_VARARGS,
"Return the network connections of a process"},
{"get_process_threads", get_process_threads, METH_VARARGS,
"Return process threads information as a list of tuple"},
{"process_wait", process_wait, METH_VARARGS,
"Wait for process to terminate and return its exit code."},
{"get_process_priority", get_process_priority, METH_VARARGS,
"Return process priority."},
{"set_process_priority", set_process_priority, METH_VARARGS,
"Set process priority."},
{"get_process_cpu_affinity", get_process_cpu_affinity, METH_VARARGS,
"Return process CPU affinity as a bitmask."},
{"set_process_cpu_affinity", set_process_cpu_affinity, METH_VARARGS,
"Set process CPU affinity."},
{"get_process_io_counters", get_process_io_counters, METH_VARARGS,
"Get process I/O counters."},
{"is_process_suspended", is_process_suspended, METH_VARARGS,
"Return True if one of the process threads is in a suspended state"},
{"get_process_num_handles", get_process_num_handles, METH_VARARGS,
"Return the number of handles opened by process."},
{"get_process_memory_maps", get_process_memory_maps, METH_VARARGS,
"Return a list of process's memory mappings"},
// --- system-related functions
{"get_pid_list", get_pid_list, METH_VARARGS,
"Returns a list of PIDs currently running on the system"},
{"pid_exists", pid_exists, METH_VARARGS,
"Determine if the process exists in the current process list."},
{"get_num_cpus", get_num_cpus, METH_VARARGS,
"Returns the number of CPUs on the system"},
{"get_system_uptime", get_system_uptime, METH_VARARGS,
"Return system uptime"},
{"get_system_phymem", get_system_phymem, METH_VARARGS,
"Return the total amount of physical memory, in bytes"},
{"get_system_cpu_times", get_system_cpu_times, METH_VARARGS,
"Return system per-cpu times as a list of tuples"},
{"get_disk_usage", get_disk_usage, METH_VARARGS,
"Return path's disk total and free as a Python tuple."},
{"get_network_io_counters", get_network_io_counters, METH_VARARGS,
"Return dict of tuples of networks I/O information."},
{"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
"Return dict of tuples of disks I/O information."},
{"get_system_users", get_system_users, METH_VARARGS,
"Return a list of currently connected users."},
{"get_disk_partitions", get_disk_partitions, METH_VARARGS,
"Return disk partitions."},
// --- windows API bindings
{"win32_QueryDosDevice", win32_QueryDosDevice, METH_VARARGS,
"QueryDosDevice binding"},
{NULL, NULL, 0, NULL}
};
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
#if PY_MAJOR_VERSION >= 3
static int psutil_mswindows_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int psutil_mswindows_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"psutil_mswindows",
NULL,
sizeof(struct module_state),
PsutilMethods,
NULL,
psutil_mswindows_traverse,
psutil_mswindows_clear,
NULL
};
#define INITERROR return NULL
PyObject* PyInit__psutil_mswindows(void)
#else
#define INITERROR return
void init_psutil_mswindows(void)
#endif
{
struct module_state *st = NULL;
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("_psutil_mswindows", PsutilMethods);
#endif
if (module == NULL) {
INITERROR;
}
st = GETSTATE(module);
st->error = PyErr_NewException("_psutil_mswindow.Error", NULL, NULL);
if (st->error == NULL) {
Py_DECREF(module);
INITERROR;
}
// Public constants
// http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx
PyModule_AddIntConstant(module, "ABOVE_NORMAL_PRIORITY_CLASS",
ABOVE_NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(module, "BELOW_NORMAL_PRIORITY_CLASS",
BELOW_NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(module, "HIGH_PRIORITY_CLASS",
HIGH_PRIORITY_CLASS);
PyModule_AddIntConstant(module, "IDLE_PRIORITY_CLASS",
IDLE_PRIORITY_CLASS);
PyModule_AddIntConstant(module, "NORMAL_PRIORITY_CLASS",
NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(module, "REALTIME_PRIORITY_CLASS",
REALTIME_PRIORITY_CLASS);
// private constants
PyModule_AddIntConstant(module, "INFINITE", INFINITE);
SetSeDebug();
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
|