Debian Codegraph @

psutil/arch/windows/disk.c

raw
1 /*
2 * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 #include <Python.h>
8 #include <windows.h>
9 #include <tchar.h>
10
11 #include "../../arch/all/init.h"
12
13
14 #ifndef _ARRAYSIZE
15 #define _ARRAYSIZE(a) (sizeof(a)/sizeof(a[0]))
16 #endif
17
18 static char *psutil_get_drive_type(int type) {
19 switch (type) {
20 case DRIVE_FIXED:
21 return "fixed";
22 case DRIVE_CDROM:
23 return "cdrom";
24 case DRIVE_REMOVABLE:
25 return "removable";
26 case DRIVE_UNKNOWN:
27 return "unknown";
28 case DRIVE_NO_ROOT_DIR:
29 return "unmounted";
30 case DRIVE_REMOTE:
31 return "remote";
32 case DRIVE_RAMDISK:
33 return "ramdisk";
34 default:
35 return "?";
36 }
37 }
38
39
40 /*
41 * Return path's disk total and free as a Python tuple.
42 */
43 PyObject *
44 psutil_disk_usage(PyObject *self, PyObject *args) {
45 BOOL retval;
46 ULARGE_INTEGER _, total, free;
47 PyObject *py_path;
48 wchar_t *path;
49
50 if (!PyArg_ParseTuple(args, "U", &py_path)) {
51 return NULL;
52 }
53
54 path = PyUnicode_AsWideCharString(py_path, NULL);
55 if (path == NULL) {
56 return NULL;
57 }
58
59 Py_BEGIN_ALLOW_THREADS
60 retval = GetDiskFreeSpaceExW(path, &_, &total, &free);
61 Py_END_ALLOW_THREADS
62
63 PyMem_Free(path);
64
65 if (retval == 0)
66 return PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, py_path);
67
68 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
69 }
70
71
72 /*
73 * Return a Python dict of tuples for disk I/O information. This may
74 * require running "diskperf -y" command first.
75 */
76 PyObject *
77 psutil_disk_io_counters(PyObject *self, PyObject *args) {
78 DISK_PERFORMANCE diskPerformance;
79 DWORD dwSize;
80 HANDLE hDevice = NULL;
81 char szDevice[MAX_PATH];
82 char szDeviceDisplay[MAX_PATH];
83 int devNum;
84 int i;
85 DWORD ioctrlSize;
86 BOOL ret;
87 PyObject *py_retdict = PyDict_New();
88 PyObject *py_tuple = NULL;
89
90 if (py_retdict == NULL)
91 return NULL;
92 // Apparently there's no way to figure out how many times we have
93 // to iterate in order to find valid drives.
94 // Let's assume 32, which is higher than 26, the number of letters
95 // in the alphabet (from A:\ to Z:\).
96 for (devNum = 0; devNum <= 32; ++devNum) {
97 py_tuple = NULL;
98 sprintf_s(szDevice, MAX_PATH, "\\\\.\\PhysicalDrive%d", devNum);
99 hDevice = CreateFile(szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
100 NULL, OPEN_EXISTING, 0, NULL);
101 if (hDevice == INVALID_HANDLE_VALUE)
102 continue;
103
104 // DeviceIoControl() sucks!
105 i = 0;
106 ioctrlSize = sizeof(diskPerformance);
107 while (1) {
108 i += 1;
109 ret = DeviceIoControl(
110 hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &diskPerformance,
111 ioctrlSize, &dwSize, NULL);
112 if (ret != 0)
113 break; // OK!
114 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
115 // Retry with a bigger buffer (+ limit for retries).
116 if (i <= 1024) {
117 ioctrlSize *= 2;
118 continue;
119 }
120 }
121 else if (GetLastError() == ERROR_INVALID_FUNCTION) {
122 // This happens on AppVeyor:
123 // https://ci.appveyor.com/project/giampaolo/psutil/build/
124 // 1364/job/ascpdi271b06jle3
125 // Assume it means we're dealing with some exotic disk
126 // and go on.
127 psutil_debug("DeviceIoControl -> ERROR_INVALID_FUNCTION; "
128 "ignore PhysicalDrive%i", devNum);
129 goto next;
130 }
131 else if (GetLastError() == ERROR_NOT_SUPPORTED) {
132 // Again, let's assume we're dealing with some exotic disk.
133 psutil_debug("DeviceIoControl -> ERROR_NOT_SUPPORTED; "
134 "ignore PhysicalDrive%i", devNum);
135 goto next;
136 }
137 // XXX: it seems we should also catch ERROR_INVALID_PARAMETER:
138 // https://sites.ualberta.ca/dept/aict/uts/software/openbsd/
139 // ports/4.1/i386/openafs/w-openafs-1.4.14-transarc/
140 // openafs-1.4.14/src/usd/usd_nt.c
141
142 // XXX: we can also bump into ERROR_MORE_DATA in which case
143 // (quoting doc) we're supposed to retry with a bigger buffer
144 // and specify a new "starting point", whatever it means.
145 PyErr_SetFromWindowsErr(0);
146 goto error;
147 }
148
149 sprintf_s(szDeviceDisplay, MAX_PATH, "PhysicalDrive%i", devNum);
150 py_tuple = Py_BuildValue(
151 "(IILLKK)",
152 diskPerformance.ReadCount,
153 diskPerformance.WriteCount,
154 diskPerformance.BytesRead,
155 diskPerformance.BytesWritten,
156 // convert to ms:
157 // https://github.com/giampaolo/psutil/issues/1012
158 (unsigned long long)
159 (diskPerformance.ReadTime.QuadPart) / 10000000,
160 (unsigned long long)
161 (diskPerformance.WriteTime.QuadPart) / 10000000);
162 if (!py_tuple)
163 goto error;
164 if (PyDict_SetItemString(py_retdict, szDeviceDisplay, py_tuple))
165 goto error;
166 Py_CLEAR(py_tuple);
167
168 next:
169 CloseHandle(hDevice);
170 }
171
172 return py_retdict;
173
174 error:
175 Py_XDECREF(py_tuple);
176 Py_DECREF(py_retdict);
177 if (hDevice != NULL)
178 CloseHandle(hDevice);
179 return NULL;
180 }
181
182
183 /*
184 * Return disk partitions as a list of tuples such as
185 * (drive_letter, drive_letter, type, "")
186 */
187 PyObject *
188 psutil_disk_partitions(PyObject *self, PyObject *args) {
189 DWORD num_bytes;
190 char drive_strings[255];
191 char *drive_letter = drive_strings;
192 char mp_buf[MAX_PATH];
193 char mp_path[MAX_PATH];
194 int all;
195 int type;
196 int ret;
197 unsigned int old_mode = 0;
198 char opts[50];
199 HANDLE mp_h;
200 BOOL mp_flag= TRUE;
201 LPTSTR fs_type[MAX_PATH + 1] = { 0 };
202 DWORD pflags = 0;
203 DWORD lpMaximumComponentLength = 0; // max file name
204 PyObject *py_all;
205 PyObject *py_retlist = PyList_New(0);
206 PyObject *py_tuple = NULL;
207
208 if (py_retlist == NULL) {
209 return NULL;
210 }
211
212 // avoid to visualize a message box in case something goes wrong
213 // see https://github.com/giampaolo/psutil/issues/264
214 old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
215
216 if (! PyArg_ParseTuple(args, "O", &py_all))
217 goto error;
218 all = PyObject_IsTrue(py_all);
219
220 Py_BEGIN_ALLOW_THREADS
221 num_bytes = GetLogicalDriveStrings(254, drive_letter);
222 Py_END_ALLOW_THREADS
223
224 if (num_bytes == 0) {
225 PyErr_SetFromWindowsErr(0);
226 goto error;
227 }
228
229 while (*drive_letter != 0) {
230 py_tuple = NULL;
231 opts[0] = 0;
232 fs_type[0] = 0;
233
234 Py_BEGIN_ALLOW_THREADS
235 type = GetDriveType(drive_letter);
236 Py_END_ALLOW_THREADS
237
238 // by default we only show hard drives and cd-roms
239 if (all == 0) {
240 if ((type == DRIVE_UNKNOWN) ||
241 (type == DRIVE_NO_ROOT_DIR) ||
242 (type == DRIVE_REMOTE) ||
243 (type == DRIVE_RAMDISK)) {
244 goto next;
245 }
246 // floppy disk: skip it by default as it introduces a
247 // considerable slowdown.
248 if ((type == DRIVE_REMOVABLE) &&
249 (strcmp(drive_letter, "A:\\") == 0)) {
250 goto next;
251 }
252 }
253
254 ret = GetVolumeInformation(
255 (LPCTSTR)drive_letter,
256 NULL,
257 _ARRAYSIZE(drive_letter),
258 NULL,
259 &lpMaximumComponentLength,
260 &pflags,
261 (LPTSTR)fs_type,
262 _ARRAYSIZE(fs_type));
263 if (ret == 0) {
264 // We might get here in case of a floppy hard drive, in
265 // which case the error is (21, "device not ready").
266 // Let's pretend it didn't happen as we already have
267 // the drive name and type ('removable').
268 strcat_s(opts, _countof(opts), "");
269 SetLastError(0);
270 }
271 else {
272 if (pflags & FILE_READ_ONLY_VOLUME)
273 strcat_s(opts, _countof(opts), "ro");
274 else
275 strcat_s(opts, _countof(opts), "rw");
276 if (pflags & FILE_VOLUME_IS_COMPRESSED)
277 strcat_s(opts, _countof(opts), ",compressed");
278 if (pflags & FILE_READ_ONLY_VOLUME)
279 strcat_s(opts, _countof(opts), ",readonly");
280
281 // Check for mount points on this volume and add/get info
282 // (checks first to know if we can even have mount points)
283 if (pflags & FILE_SUPPORTS_REPARSE_POINTS) {
284 mp_h = FindFirstVolumeMountPoint(
285 drive_letter, mp_buf, MAX_PATH);
286 if (mp_h != INVALID_HANDLE_VALUE) {
287 mp_flag = TRUE;
288 while (mp_flag) {
289 // Append full mount path with drive letter
290 strcpy_s(mp_path, _countof(mp_path), drive_letter);
291 strcat_s(mp_path, _countof(mp_path), mp_buf);
292
293 py_tuple = Py_BuildValue(
294 "(ssss)",
295 drive_letter,
296 mp_path,
297 fs_type, // typically "NTFS"
298 opts
299 );
300
301 if (!py_tuple ||
302 PyList_Append(py_retlist, py_tuple) == -1) {
303 FindVolumeMountPointClose(mp_h);
304 goto error;
305 }
306
307 Py_CLEAR(py_tuple);
308
309 // Continue looking for more mount points
310 mp_flag = FindNextVolumeMountPoint(
311 mp_h, mp_buf, MAX_PATH);
312 }
313 FindVolumeMountPointClose(mp_h);
314 }
315
316 }
317 }
318
319 if (strlen(opts) > 0)
320 strcat_s(opts, _countof(opts), ",");
321 strcat_s(opts, _countof(opts), psutil_get_drive_type(type));
322
323 py_tuple = Py_BuildValue(
324 "(ssss)",
325 drive_letter,
326 drive_letter,
327 fs_type, // either FAT, FAT32, NTFS, HPFS, CDFS, UDF or NWFS
328 opts
329 );
330 if (!py_tuple)
331 goto error;
332 if (PyList_Append(py_retlist, py_tuple))
333 goto error;
334 Py_CLEAR(py_tuple);
335 goto next;
336
337 next:
338 drive_letter = strchr(drive_letter, 0) + 1;
339 }
340
341 SetErrorMode(old_mode);
342 return py_retlist;
343
344 error:
345 SetErrorMode(old_mode);
346 Py_XDECREF(py_tuple);
347 Py_DECREF(py_retlist);
348 return NULL;
349 }
350
351
352 /*
353 Accept a filename's drive in native format like "\Device\HarddiskVolume1\"
354 and return the corresponding drive letter (e.g. "C:\\").
355 If no match is found return an empty string.
356 */
357 PyObject *
358 psutil_QueryDosDevice(PyObject *self, PyObject *args) {
359 LPCTSTR lpDevicePath;
360 TCHAR d = TEXT('A');
361 TCHAR szBuff[5];
362
363 if (!PyArg_ParseTuple(args, "s", &lpDevicePath))
364 return NULL;
365
366 while (d <= TEXT('Z')) {
367 TCHAR szDeviceName[3] = {d, TEXT(':'), TEXT('\0')};
368 TCHAR szTarget[512] = {0};
369 if (QueryDosDevice(szDeviceName, szTarget, 511) != 0) {
370 if (_tcscmp(lpDevicePath, szTarget) == 0) {
371 _stprintf_s(szBuff, _countof(szBuff), TEXT("%c:"), d);
372 return Py_BuildValue("s", szBuff);
373 }
374 }
375 d++;
376 }
377 return Py_BuildValue("s", "");
378 }