blob: 84bf3c48765c1d2f2c99892668cb563c9092a6ff [file] [log] [blame]
Guido van Rossum9f3712c2000-03-28 20:37:15 +00001/*
Fred Drake270e19b2000-06-29 16:14:14 +00002 _winreg.c
Guido van Rossum9f3712c2000-03-28 20:37:15 +00003
4 Windows Registry access module for Python.
5
6 * Simple registry access written by Mark Hammond in win32api
7 module circa 1995.
8 * Bill Tutt expanded the support significantly not long after.
9 * Numerous other people have submitted patches since then.
10 * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and
11 basic Unicode support added.
12
13*/
14
15#include "windows.h"
16#include "Python.h"
17#include "structmember.h"
18#include "malloc.h" /* for alloca */
19
20static BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pRes, BOOL bNoneOK);
21static PyObject *PyHKEY_FromHKEY(HKEY h);
22static BOOL PyHKEY_Close(PyObject *obHandle);
23
24static char errNotAHandle[] = "Object is not a handle";
25
26/* The win32api module reports the function name that failed,
27 but this concept is not in the Python core.
28 Hopefully it will one day, and in the meantime I dont
29 want to lose this info...
30*/
31#define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
32 PyErr_SetFromWindowsErr(rc)
33
34/* Forward declares */
35
36/* Doc strings */
37static char module_doc[] =
38"This module provides access to the Windows registry API.\n"
39"\n"
40"Functions:\n"
41"\n"
42"CloseKey() - Closes a registry key.\n"
43"ConnectRegistry() - Establishes a connection to a predefined registry handle\n"
44" on another computer.\n"
45"CreateKey() - Creates the specified key, or opens it if it already exists.\n"
46"DeleteKey() - Deletes the specified key.\n"
47"DeleteValue() - Removes a named value from the specified registry key.\n"
48"EnumKey() - Enumerates subkeys of the specified open registry key.\n"
49"EnumValue() - Enumerates values of the specified open registry key.\n"
50"FlushKey() - Writes all the attributes of the specified key to the registry.\n"
51"LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and stores\n"
52" registration information from a specified file into that subkey.\n"
53"OpenKey() - Alias for <om win32api.RegOpenKeyEx>\n"
54"OpenKeyEx() - Opens the specified key.\n"
55"QueryValue() - Retrieves the value associated with the unnamed value for a\n"
56" specified key in the registry.\n"
57"QueryValueEx() - Retrieves the type and data for a specified value name\n"
58" associated with an open registry key.\n"
59"QueryInfoKey() - Returns information about the specified key.\n"
60"SaveKey() - Saves the specified key, and all its subkeys a file.\n"
61"SetValue() - Associates a value with a specified key.\n"
62"SetValueEx() - Stores data in the value field of an open registry key.\n"
63"\n"
64"Special objects:\n"
65"\n"
66"HKEYType -- type object for HKEY objects\n"
67"error -- exception raised for Win32 errors\n"
68"\n"
69"Integer constants:\n"
70"Many constants are defined - see the documentation for each function\n"
71"to see what constants are used, and where.";
72
73
74static char CloseKey_doc[] =
75"CloseKey(hkey) - Closes a previously opened registry key.\n"
76"\n"
77"The hkey argument specifies a previously opened key.\n"
78"\n"
79"Note that if the key is not closed using this method, it will be\n"
80"closed when the hkey object is destroyed by Python.";
81
82static char ConnectRegistry_doc[] =
83"key = ConnectRegistry(computer_name, key) - "
84"Establishes a connection to a predefined registry handle on another computer.\n"
85"\n"
86"computer_name is the name of the remote computer, of the form \\\\computername.\n"
87" If None, the local computer is used.\n"
88"key is the predefined handle to connect to.\n"
89"\n"
90"The return value is the handle of the opened key.\n"
Mark Hammondb422f952000-06-09 06:01:47 +000091"If the function fails, an EnvironmentError exception is raised.";
Guido van Rossum9f3712c2000-03-28 20:37:15 +000092
93static char CreateKey_doc[] =
94"key = CreateKey(key, sub_key) - Creates or opens the specified key.\n"
95"\n"
96"key is an already open key, or one of the predefined HKEY_* constants\n"
97"sub_key is a string that names the key this method opens or creates.\n"
98" If key is one of the predefined keys, sub_key may be None. In that case,\n"
99" the handle returned is the same key handle passed in to the function.\n"
100"\n"
101"If the key already exists, this function opens the existing key\n"
102"\n"
103"The return value is the handle of the opened key.\n"
104"If the function fails, an exception is raised.";
105
106static char DeleteKey_doc[] =
107"DeleteKey(key, sub_key) - Deletes the specified key.\n"
108"\n"
109"key is an already open key, or any one of the predefined HKEY_* constants.\n"
110"sub_key is a string that must be a subkey of the key identified by the key parameter.\n"
111" This value must not be None, and the key may not have subkeys.\n"
112"\n"
113"This method can not delete keys with subkeys.\n"
114"\n"
115"If the method succeeds, the entire key, including all of its values,\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000116"is removed. If the method fails, an EnvironmentError exception is raised.";
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000117
118static char DeleteValue_doc[] =
119"DeleteValue(key, value) - Removes a named value from a registry key.\n"
120"\n"
121"key is an already open key, or any one of the predefined HKEY_* constants.\n"
122"value is a string that identifies the value to remove.";
123
124static char EnumKey_doc[] =
125"string = EnumKey(key, index) - Enumerates subkeys of an open registry key.\n"
126"\n"
127"key is an already open key, or any one of the predefined HKEY_* constants.\n"
128"index is an integer that identifies the index of the key to retrieve.\n"
129"\n"
130"The function retrieves the name of one subkey each time it is called.\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000131"It is typically called repeatedly until an EnvironmentError exception is\n"
132"raised, indicating no more values are available.\n";
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000133
134static char EnumValue_doc[] =
135"tuple = EnumValue(key, index) - Enumerates values of an open registry key.\n"
136"key is an already open key, or any one of the predefined HKEY_* constants.\n"
137"index is an integer that identifies the index of the value to retrieve.\n"
138"\n"
139"The function retrieves the name of one subkey each time it is called.\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000140"It is typically called repeatedly, until an EnvironmentError exception\n"
141"is raised, indicating no more values.\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000142"\n"
143"The result is a tuple of 3 items:\n"
144"value_name is a string that identifies the value.\n"
145"value_data is an object that holds the value data, and whose type depends\n"
146" on the underlying registry type.\n"
147"data_type is an integer that identifies the type of the value data.";
148
149static char FlushKey_doc[] =
150"FlushKey(key) - Writes all the attributes of a key to the registry.\n"
151"\n"
152"key is an already open key, or any one of the predefined HKEY_* constants.\n"
153"\n"
154"It is not necessary to call RegFlushKey to change a key.\n"
155"Registry changes are flushed to disk by the registry using its lazy flusher.\n"
156"Registry changes are also flushed to disk at system shutdown.\n"
157"Unlike CloseKey(), the FlushKey() method returns only when all the data has\n"
158"been written to the registry.\n"
159"An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk.\n"
160"If you don't know whether a FlushKey() call is required, it probably isn't.\n";
161
162static char LoadKey_doc[] =
Mark Hammondb422f952000-06-09 06:01:47 +0000163"LoadKey(key, sub_key, file_name) - Creates a subkey under the specified key\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000164"and stores registration information from a specified file into that subkey.\n"
165"\n"
166"key is an already open key, or any one of the predefined HKEY_* constants.\n"
167"sub_key is a string that identifies the sub_key to load\n"
168"file_name is the name of the file to load registry data from.\n"
169" This file must have been created with the SaveKey() function.\n"
170" Under the file allocation table (FAT) file system, the filename may not\n"
171"have an extension.\n"
172"\n"
173"A call to LoadKey() fails if the calling process does not have the\n"
174"SE_RESTORE_PRIVILEGE privilege.\n"
175"\n"
176"If key is a handle returned by ConnectRegistry(), then the path specified\n"
177"in fileName is relative to the remote computer.\n"
178"\n"
179"The docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree";
180
181static char OpenKey_doc[] =
182"key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key.\n"
183"\n"
184"key is an already open key, or any one of the predefined HKEY_* constants.\n"
185"sub_key is a string that identifies the sub_key to open\n"
186"res is a reserved integer, and must be zero. Default is zero.\n"
187"sam is an integer that specifies an access mask that describes the desired\n"
188" security access for the key. Default is KEY_READ\n"
189"\n"
190"The result is a new handle to the specified key\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000191"If the function fails, an EnvironmentError exception is raised.\n";
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000192
193static char OpenKeyEx_doc[] =
194"See OpenKey()";
195
196static char QueryInfoKey_doc[] =
197"tuple = QueryInfoKey(key) - Returns information about a key.\n"
198"\n"
199"key is an already open key, or any one of the predefined HKEY_* constants.\n"
200"\n"
201"The result is a tuple of 3 items:"
202"An integer that identifies the number of sub keys this key has.\n"
203"An integer that identifies the number of values this key has.\n"
204"A long integer that identifies when the key was last modified (if available)\n"
205" as 100's of nanoseconds since Jan 1, 1600.\n";
206
207static char QueryValue_doc[] =
208"string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.\n"
209"\n"
210"key is an already open key, or any one of the predefined HKEY_* constants.\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000211"sub_key is a string that holds the name of the subkey with which the value\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000212" is associated. If this parameter is None or empty, the function retrieves\n"
213" the value set by the SetValue() method for the key identified by key."
214"\n"
215"Values in the registry have name, type, and data components. This method\n"
216"retrieves the data for a key's first value that has a NULL name.\n"
217"But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!";
218
219static char QueryValueEx_doc[] =
220"value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.\n"
221"\n"
222"key is an already open key, or any one of the predefined HKEY_* constants.\n"
223"value_name is a string indicating the value to query";
224
225static char SaveKey_doc[] =
226"SaveKey(key, file_name) - Saves the specified key, and all its subkeys to the specified file.\n"
227"\n"
228"key is an already open key, or any one of the predefined HKEY_* constants.\n"
229"file_name is the name of the file to save registry data to.\n"
230" This file cannot already exist. If this filename includes an extension,\n"
231" it cannot be used on file allocation table (FAT) file systems by the\n"
232" LoadKey(), ReplaceKey() or RestoreKey() methods.\n"
233"\n"
234"If key represents a key on a remote computer, the path described by\n"
235"file_name is relative to the remote computer.\n"
236"The caller of this method must possess the SeBackupPrivilege security privilege.\n"
237"This function passes NULL for security_attributes to the API.";
238
239static char SetValue_doc[] =
240"SetValue(key, sub_key, type, value) - Associates a value with a specified key.\n"
241"\n"
242"key is an already open key, or any one of the predefined HKEY_* constants.\n"
243"sub_key is a string that names the subkey with which the value is associated.\n"
244"type is an integer that specifies the type of the data. Currently this\n"
245" must be REG_SZ, meaning only strings are supported.\n"
246"value is a string that specifies the new value.\n"
247"\n"
248"If the key specified by the sub_key parameter does not exist, the SetValue\n"
249"function creates it.\n"
250"\n"
251"Value lengths are limited by available memory. Long values (more than\n"
252"2048 bytes) should be stored as files with the filenames stored in \n"
253"the configuration registry. This helps the registry perform efficiently.\n"
254"\n"
255"The key identified by the key parameter must have been opened with\n"
256"KEY_SET_VALUE access.";
257
258static char SetValueEx_doc[] =
259"SetValueEx(key, value_name, reserved, type, value) - Stores data in the value field of an open registry key.\n"
260"\n"
261"key is an already open key, or any one of the predefined HKEY_* constants.\n"
262"sub_key is a string that names the subkey with which the value is associated.\n"
263"type is an integer that specifies the type of the data. This should be one of:\n"
264" REG_BINARY -- Binary data in any form.\n"
265" REG_DWORD -- A 32-bit number.\n"
266" REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format.\n"
267" REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.\n"
268" REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references\n"
269" to environment variables (for example, %PATH%).\n"
270" REG_LINK -- A Unicode symbolic link.\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000271" REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by\n"
272" two null characters. Note that Python handles this\n"
273" termination automatically.\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000274" REG_NONE -- No defined value type.\n"
275" REG_RESOURCE_LIST -- A device-driver resource list.\n"
276" REG_SZ -- A null-terminated string.\n"
277"reserved can be anything - zero is always passed to the API.\n"
278"value is a string that specifies the new value.\n"
279"\n"
280"This method can also set additional value and type information for the\n"
281"specified key. The key identified by the key parameter must have been\n"
282"opened with KEY_SET_VALUE access.\n"
283"\n"
284"To open the key, use the CreateKeyEx() or OpenKeyEx() methods.\n"
285"\n"
286"Value lengths are limited by available memory. Long values (more than\n"
287"2048 bytes) should be stored as files with the filenames stored in \n"
288"the configuration registry. This helps the registry perform efficiently.\n";
289
290/* PyHKEY docstrings */
291static char PyHKEY_doc[] =
292"PyHKEY Object - A Python object, representing a win32 registry key.\n"
293"\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000294"This object wraps a Windows HKEY object, automatically closing it when\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000295"the object is destroyed. To guarantee cleanup, you can call either\n"
296"the Close() method on the PyHKEY, or the CloseKey() method.\n"
297"\n"
298"All functions which accept a handle object also accept an integer - \n"
299"however, use of the handle object is encouraged.\n"
300"\n"
301"Functions:\n"
302"Close() - Closes the underlying handle.\n"
303"Detach() - Returns the integer Win32 handle, detaching it from the object\n"
304"\n"
305"Properties:\n"
306"handle - The integer Win32 handle.\n"
307"\n"
308"Operations:\n"
309"__nonzero__ - Handles with an open object return true, otherwise false.\n"
310"__int__ - Converting a handle to an integer returns the Win32 handle.\n"
311"__cmp__ - Handle objects are compared using the handle value.\n";
312
313
314static char PyHKEY_Close_doc[] =
Mark Hammondb422f952000-06-09 06:01:47 +0000315"key.Close() - Closes the underlying Windows handle.\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000316"\n"
317"If the handle is already closed, no error is raised.";
318
319static char PyHKEY_Detach_doc[] =
Mark Hammondb422f952000-06-09 06:01:47 +0000320"int = key.Detach() - Detaches the Windows handle from the handle object.\n"
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000321"\n"
322"The result is the value of the handle before it is detached. If the\n"
323"handle is already detached, this will return zero.\n"
324"\n"
325"After calling this function, the handle is effectively invalidated,\n"
326"but the handle is not closed. You would call this function when you\n"
327"need the underlying win32 handle to exist beyond the lifetime of the\n"
Mark Hammondb422f952000-06-09 06:01:47 +0000328"handle object.\n"
329"On 64 bit windows, the result of this function is a long integer\n";
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000330
331
332/************************************************************************
333
334 The PyHKEY object definition
335
336************************************************************************/
337typedef struct {
338 PyObject_VAR_HEAD
339 HKEY hkey;
340} PyHKEYObject;
341
342#define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
343
344static char *failMsg = "bad operand type";
345
346static PyObject *
347PyHKEY_unaryFailureFunc(PyObject *ob)
348{
349 PyErr_SetString(PyExc_TypeError, failMsg);
350 return NULL;
351}
352static PyObject *
353PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
354{
355 PyErr_SetString(PyExc_TypeError, failMsg);
356 return NULL;
357}
358static PyObject *
359PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
360{
361 PyErr_SetString(PyExc_TypeError, failMsg);
362 return NULL;
363}
364
365static void
366PyHKEY_deallocFunc(PyObject *ob)
367{
368 /* Can not call PyHKEY_Close, as the ob->tp_type
369 has already been cleared, thus causing the type
370 check to fail!
371 */
372 PyHKEYObject *obkey = (PyHKEYObject *)ob;
373 if (obkey->hkey)
374 RegCloseKey((HKEY)obkey->hkey);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000375 PyObject_DEL(ob);
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000376}
377
378static int
379PyHKEY_nonzeroFunc(PyObject *ob)
380{
381 return ((PyHKEYObject *)ob)->hkey != 0;
382}
383
384static PyObject *
385PyHKEY_intFunc(PyObject *ob)
386{
387 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
388 return PyLong_FromVoidPtr(pyhkey->hkey);
389}
390
391static int
392PyHKEY_printFunc(PyObject *ob, FILE *fp, int flags)
393{
394 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
395 char resBuf[160];
396 wsprintf(resBuf, "<PyHKEY at %p (%p)>",
397 ob, pyhkey->hkey);
398 fputs(resBuf, fp);
399 return 0;
400}
401
402static PyObject *
403PyHKEY_strFunc(PyObject *ob)
404{
405 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
406 char resBuf[160];
407 wsprintf(resBuf, "<PyHKEY:%p>", pyhkey->hkey);
408 return PyString_FromString(resBuf);
409}
410
411static int
412PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
413{
414 PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
415 PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
416 return pyhkey1 == pyhkey2 ? 0 :
417 (pyhkey1 < pyhkey2 ? -1 : 1);
418}
419
420static long
421PyHKEY_hashFunc(PyObject *ob)
422{
423 /* Just use the address.
424 XXX - should we use the handle value?
425 */
Fred Drake13634cf2000-06-29 19:17:04 +0000426 return _Py_HashPointer(ob);
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000427}
428
429
430static PyNumberMethods PyHKEY_NumberMethods =
431{
432 PyHKEY_binaryFailureFunc, /* nb_add */
433 PyHKEY_binaryFailureFunc, /* nb_subtract */
434 PyHKEY_binaryFailureFunc, /* nb_multiply */
435 PyHKEY_binaryFailureFunc, /* nb_divide */
436 PyHKEY_binaryFailureFunc, /* nb_remainder */
437 PyHKEY_binaryFailureFunc, /* nb_divmod */
438 PyHKEY_ternaryFailureFunc, /* nb_power */
439 PyHKEY_unaryFailureFunc, /* nb_negative */
440 PyHKEY_unaryFailureFunc, /* nb_positive */
441 PyHKEY_unaryFailureFunc, /* nb_absolute */
442 PyHKEY_nonzeroFunc, /* nb_nonzero */
443 PyHKEY_unaryFailureFunc, /* nb_invert */
444 PyHKEY_binaryFailureFunc, /* nb_lshift */
445 PyHKEY_binaryFailureFunc, /* nb_rshift */
446 PyHKEY_binaryFailureFunc, /* nb_and */
447 PyHKEY_binaryFailureFunc, /* nb_xor */
448 PyHKEY_binaryFailureFunc, /* nb_or */
449 0, /* nb_coerce (allowed to be zero) */
450 PyHKEY_intFunc, /* nb_int */
451 PyHKEY_unaryFailureFunc, /* nb_long */
452 PyHKEY_unaryFailureFunc, /* nb_float */
453 PyHKEY_unaryFailureFunc, /* nb_oct */
454 PyHKEY_unaryFailureFunc, /* nb_hex */
455};
456
457
458/* fwd declare __getattr__ */
459static PyObject *PyHKEY_getattr(PyObject *self, char *name);
460
461/* The type itself */
462PyTypeObject PyHKEY_Type =
463{
464 PyObject_HEAD_INIT(0) /* fill in type at module init */
465 0,
466 "PyHKEY",
467 sizeof(PyHKEYObject),
468 0,
469 PyHKEY_deallocFunc, /* tp_dealloc */
470 PyHKEY_printFunc, /* tp_print */
471 PyHKEY_getattr, /* tp_getattr */
472 0, /* tp_setattr */
473 PyHKEY_compareFunc, /* tp_compare */
474 0, /* tp_repr */
475 &PyHKEY_NumberMethods, /* tp_as_number */
476 0, /* tp_as_sequence */
477 0, /* tp_as_mapping */
478 PyHKEY_hashFunc, /* tp_hash */
479 0, /* tp_call */
480 PyHKEY_strFunc, /* tp_str */
481 0, /* tp_getattro */
482 0, /* tp_setattro */
483 0, /* tp_as_buffer */
484 0, /* tp_flags */
485 PyHKEY_doc, /* tp_doc */
486};
487
488#define OFF(e) offsetof(PyHKEYObject, e)
489
490static struct memberlist PyHKEY_memberlist[] = {
491 {"handle", T_INT, OFF(hkey)},
492 {NULL} /* Sentinel */
493};
494
495/************************************************************************
496
497 The PyHKEY object methods
498
499************************************************************************/
500static PyObject *
501PyHKEY_CloseMethod(PyObject *self, PyObject *args)
502{
503 if (!PyArg_ParseTuple(args, ":Close"))
504 return NULL;
505 if (!PyHKEY_Close(self))
506 return NULL;
507 Py_INCREF(Py_None);
508 return Py_None;
509}
510
511static PyObject *
512PyHKEY_DetachMethod(PyObject *self, PyObject *args)
513{
514 void* ret;
515 PyHKEYObject *pThis = (PyHKEYObject *)self;
516 if (!PyArg_ParseTuple(args, ":Detach"))
517 return NULL;
518 ret = (void*)pThis->hkey;
519 pThis->hkey = 0;
520 return PyLong_FromVoidPtr(ret);
521}
522
523static struct PyMethodDef PyHKEY_methods[] = {
524 {"Close", PyHKEY_CloseMethod, 1, PyHKEY_Close_doc},
525 {"Detach", PyHKEY_DetachMethod, 1, PyHKEY_Detach_doc},
526 {NULL}
527};
528
529/*static*/ PyObject *
530PyHKEY_getattr(PyObject *self, char *name)
531{
532 PyObject *res;
533
534 res = Py_FindMethod(PyHKEY_methods, self, name);
535 if (res != NULL)
536 return res;
537 PyErr_Clear();
538 if (strcmp(name, "handle") == 0)
539 return PyLong_FromVoidPtr(((PyHKEYObject *)self)->hkey);
540 return PyMember_Get((char *)self, PyHKEY_memberlist, name);
541}
542
543/************************************************************************
544 The public PyHKEY API (well, not public yet :-)
545************************************************************************/
546PyObject *
547PyHKEY_New(HKEY hInit)
548{
549 PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
550 if (key)
551 key->hkey = hInit;
552 return (PyObject *)key;
553}
554
555BOOL
556PyHKEY_Close(PyObject *ob_handle)
557{
558 LONG rc;
559 PyHKEYObject *key;
560
561 if (!PyHKEY_Check(ob_handle)) {
562 PyErr_SetString(PyExc_TypeError, "bad operand type");
563 return FALSE;
564 }
565 key = (PyHKEYObject *)ob_handle;
566 rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS;
567 key->hkey = 0;
568 if (rc != ERROR_SUCCESS)
569 PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
570 return rc == ERROR_SUCCESS;
571}
572
573BOOL
574PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
575{
576 if (ob == Py_None) {
577 if (!bNoneOK) {
578 PyErr_SetString(
579 PyExc_TypeError,
580 "None is not a valid HKEY in this context");
581 return FALSE;
582 }
583 *pHANDLE = (HKEY)0;
584 }
585 else if (PyHKEY_Check(ob)) {
586 PyHKEYObject *pH = (PyHKEYObject *)ob;
587 *pHANDLE = pH->hkey;
588 }
589 else if (PyInt_Check(ob) || PyLong_Check(ob)) {
590 /* We also support integers */
591 PyErr_Clear();
592 *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
593 if (PyErr_Occurred())
594 return FALSE;
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000595 }
596 else {
597 PyErr_SetString(
598 PyExc_TypeError,
599 "The object is not a PyHKEY object");
600 return FALSE;
601 }
602 return TRUE;
603}
604
605PyObject *
606PyHKEY_FromHKEY(HKEY h)
607{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000608 PyHKEYObject *op;
609
610 /* PyObject_New is inlined */
611 op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000612 if (op == NULL)
613 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000614 PyObject_INIT(op, &PyHKEY_Type);
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000615 op->hkey = h;
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000616 return (PyObject *)op;
617}
618
619
620/************************************************************************
621 The module methods
622************************************************************************/
623BOOL
624PyWinObject_CloseHKEY(PyObject *obHandle)
625{
626 BOOL ok;
627 if (PyHKEY_Check(obHandle)) {
628 ok = PyHKEY_Close(obHandle);
629 }
Fred Drake25e17262000-06-30 17:48:51 +0000630#if SIZEOF_LONG >= SIZEOF_HKEY
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000631 else if (PyInt_Check(obHandle)) {
632 long rc = RegCloseKey((HKEY)PyInt_AsLong(obHandle));
633 ok = (rc == ERROR_SUCCESS);
634 if (!ok)
635 PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
636 }
Fred Drake25e17262000-06-30 17:48:51 +0000637#else
638 else if (PyLong_Check(obHandle)) {
639 long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
640 ok = (rc == ERROR_SUCCESS);
641 if (!ok)
642 PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
643 }
644#endif
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000645 else {
646 PyErr_SetString(
647 PyExc_TypeError,
648 "A handle must be a HKEY object or an integer");
649 return FALSE;
650 }
651 return ok;
652}
653
654
655/*
656 Private Helper functions for the registry interfaces
657
658** Note that fixupMultiSZ and countString have both had changes
659** made to support "incorrect strings". The registry specification
660** calls for strings to be terminated with 2 null bytes. It seems
Thomas Wouters7e474022000-07-16 12:04:32 +0000661** some commercial packages install strings which dont conform,
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000662** causing this code to fail - however, "regedit" etc still work
663** with these strings (ie only we dont!).
664*/
665static void
666fixupMultiSZ(char **str, char *data, int len)
667{
668 char *P;
669 int i;
670 char *Q;
671
672 Q = data + len;
673 for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
674 str[i] = P;
675 for(; *P != '\0'; P++)
676 ;
677 }
678}
679
680static int
681countStrings(char *data, int len)
682{
683 int strings;
684 char *P;
685 char *Q = data + len;
686
687 for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
688 for (; P < Q && *P != '\0'; P++)
689 ;
690 return strings;
691}
692
693/* Convert PyObject into Registry data.
694 Allocates space as needed. */
695static BOOL
696Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
697{
698 int i,j;
699 switch (typ) {
700 case REG_DWORD:
701 if (value != Py_None && !PyInt_Check(value))
702 return FALSE;
703 *retDataBuf = (BYTE *)PyMem_NEW(DWORD, sizeof(DWORD));
704 if (*retDataBuf==NULL){
705 PyErr_NoMemory();
706 return FALSE;
707 }
708 *retDataSize = sizeof(DWORD);
709 if (value == Py_None) {
710 DWORD zero = 0;
711 memcpy(*retDataBuf, &zero, sizeof(DWORD));
712 }
713 else
714 memcpy(*retDataBuf,
715 &PyInt_AS_LONG((PyIntObject *)value),
716 sizeof(DWORD));
717 break;
718 case REG_SZ:
719 case REG_EXPAND_SZ:
720 {
721 int need_decref = 0;
722 if (value == Py_None)
723 *retDataSize = 1;
724 else {
725 if (PyUnicode_Check(value)) {
726 value = PyUnicode_AsEncodedString(
727 value,
728 "mbcs",
729 NULL);
730 if (value==NULL)
731 return FALSE;
732 need_decref = 1;
733 }
734 if (!PyString_Check(value))
735 return FALSE;
736 *retDataSize = 1 + strlen(
737 PyString_AS_STRING(
738 (PyStringObject *)value));
739 }
740 *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
741 if (*retDataBuf==NULL){
742 PyErr_NoMemory();
743 return FALSE;
744 }
745 if (value == Py_None)
746 strcpy((char *)*retDataBuf, "");
747 else
748 strcpy((char *)*retDataBuf,
749 PyString_AS_STRING(
750 (PyStringObject *)value));
751 if (need_decref)
752 Py_DECREF(value);
753 break;
754 }
755 case REG_MULTI_SZ:
756 {
757 DWORD size = 0;
758 char *P;
759 PyObject **obs = NULL;
760
761 if (value == Py_None)
762 i = 0;
763 else {
764 if (!PyList_Check(value))
765 return FALSE;
766 i = PyList_Size(value);
767 }
768 obs = malloc(sizeof(PyObject *) * i);
769 memset(obs, 0, sizeof(PyObject *) * i);
770 for (j = 0; j < i; j++)
771 {
772 PyObject *t;
773 t = PyList_GET_ITEM(
774 (PyListObject *)value,j);
775 if (PyString_Check(t)) {
776 obs[j] = t;
777 Py_INCREF(t);
778 } else if (PyUnicode_Check(t)) {
779 obs[j] = PyUnicode_AsEncodedString(
780 t,
781 "mbcs",
782 NULL);
783 if (obs[j]==NULL)
784 goto reg_multi_fail;
785 } else
786 goto reg_multi_fail;
787 size += 1 + strlen(
788 PyString_AS_STRING(
789 (PyStringObject *)obs[j]));
790 }
791
792 *retDataSize = size + 1;
793 *retDataBuf = (BYTE *)PyMem_NEW(char,
794 *retDataSize);
795 if (*retDataBuf==NULL){
796 PyErr_NoMemory();
797 goto reg_multi_fail;
798 }
799 P = (char *)*retDataBuf;
800
801 for (j = 0; j < i; j++)
802 {
803 PyObject *t;
804 t = obs[j];
805 strcpy(P,
806 PyString_AS_STRING(
807 (PyStringObject *)t));
808 P += 1 + strlen(
809 PyString_AS_STRING(
810 (PyStringObject *)t));
811 Py_DECREF(obs[j]);
812 }
813 /* And doubly-terminate the list... */
814 *P = '\0';
815 free(obs);
816 break;
817 reg_multi_fail:
818 if (obs) {
819 for (j = 0; j < i; j++)
820 Py_XDECREF(obs[j]);
821
822 free(obs);
823 }
824 return FALSE;
825 }
826 case REG_BINARY:
827 /* ALSO handle ALL unknown data types here. Even if we can't
828 support it natively, we should handle the bits. */
829 default:
830 if (value == Py_None)
831 *retDataSize = 0;
832 else {
833 if (!PyString_Check(value))
834 return 0;
835 *retDataSize = PyString_Size(value);
836 *retDataBuf = (BYTE *)PyMem_NEW(char,
837 *retDataSize);
838 if (*retDataBuf==NULL){
839 PyErr_NoMemory();
840 return FALSE;
841 }
842 memcpy(*retDataBuf,
843 PyString_AS_STRING(
844 (PyStringObject *)value),
845 *retDataSize);
846 }
847 break;
848 }
849 return TRUE;
850}
851
852/* Convert Registry data into PyObject*/
853static PyObject *
854Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ)
855{
856 PyObject *obData;
857
858 switch (typ) {
859 case REG_DWORD:
860 if (retDataSize == 0)
861 obData = Py_BuildValue("i", 0);
862 else
863 obData = Py_BuildValue("i",
864 *(int *)retDataBuf);
865 break;
866 case REG_SZ:
867 case REG_EXPAND_SZ:
868 /* retDataBuf may or may not have a trailing NULL in
869 the buffer. */
870 if (retDataSize && retDataBuf[retDataSize-1] == '\0')
871 --retDataSize;
872 if (retDataSize ==0)
873 retDataBuf = "";
874 obData = PyUnicode_DecodeMBCS(retDataBuf,
875 retDataSize,
876 NULL);
877 break;
878 case REG_MULTI_SZ:
879 if (retDataSize == 0)
880 obData = PyList_New(0);
881 else
882 {
883 int index = 0;
884 int s = countStrings(retDataBuf, retDataSize);
885 char **str = (char **)malloc(sizeof(char *)*s);
886 if (str == NULL)
887 return PyErr_NoMemory();
888
889 fixupMultiSZ(str, retDataBuf, retDataSize);
890 obData = PyList_New(s);
Fred Drake25e17262000-06-30 17:48:51 +0000891 if (obData == NULL)
892 return NULL;
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000893 for (index = 0; index < s; index++)
894 {
Fred Drake25e17262000-06-30 17:48:51 +0000895 size_t len = _mbstrlen(str[index]);
896 if (len > INT_MAX) {
897 PyErr_SetString(PyExc_OverflowError,
898 "registry string is too long for a Python string");
899 Py_DECREF(obData);
900 return NULL;
901 }
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000902 PyList_SetItem(obData,
903 index,
904 PyUnicode_DecodeMBCS(
905 (const char *)str[index],
Fred Drake25e17262000-06-30 17:48:51 +0000906 (int)len,
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000907 NULL)
908 );
909 }
910 free(str);
911
912 break;
913 }
914 case REG_BINARY:
915 /* ALSO handle ALL unknown data types here. Even if we can't
916 support it natively, we should handle the bits. */
917 default:
918 if (retDataSize == 0) {
919 Py_INCREF(Py_None);
920 obData = Py_None;
921 }
922 else
923 obData = Py_BuildValue("s#",
924 (char *)retDataBuf,
925 retDataSize);
926 break;
927 }
928 if (obData == NULL)
929 return NULL;
930 else
931 return obData;
932}
933
934/* The Python methods */
935
936static PyObject *
937PyCloseKey(PyObject *self, PyObject *args)
938{
939 PyObject *obKey;
940 if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey))
941 return NULL;
942 if (!PyHKEY_Close(obKey))
943 return NULL;
944 Py_INCREF(Py_None);
945 return Py_None;
946}
947
948static PyObject *
949PyConnectRegistry(PyObject *self, PyObject *args)
950{
951 HKEY hKey;
952 PyObject *obKey;
953 char *szCompName = NULL;
954 HKEY retKey;
955 long rc;
956 if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey))
957 return NULL;
958 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
959 return NULL;
960 rc = RegConnectRegistry(szCompName, hKey, &retKey);
961 if (rc != ERROR_SUCCESS)
962 return PyErr_SetFromWindowsErrWithFunction(rc,
963 "ConnectRegistry");
964 return PyHKEY_FromHKEY(retKey);
965}
966
967static PyObject *
968PyCreateKey(PyObject *self, PyObject *args)
969{
970 HKEY hKey;
971 PyObject *obKey;
972 char *subKey;
973 HKEY retKey;
974 long rc;
975 if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey))
976 return NULL;
977 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
978 return NULL;
979 rc = RegCreateKey(hKey, subKey, &retKey);
980 if (rc != ERROR_SUCCESS)
981 return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
982 return PyHKEY_FromHKEY(retKey);
983}
984
985static PyObject *
986PyDeleteKey(PyObject *self, PyObject *args)
987{
988 HKEY hKey;
989 PyObject *obKey;
990 char *subKey;
991 long rc;
992 if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey))
993 return NULL;
994 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
995 return NULL;
996 rc = RegDeleteKey(hKey, subKey );
997 if (rc != ERROR_SUCCESS)
998 return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
999 Py_INCREF(Py_None);
1000 return Py_None;
1001}
1002
1003static PyObject *
1004PyDeleteValue(PyObject *self, PyObject *args)
1005{
1006 HKEY hKey;
1007 PyObject *obKey;
1008 char *subKey;
1009 long rc;
1010 if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey))
1011 return NULL;
1012 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1013 return NULL;
1014 Py_BEGIN_ALLOW_THREADS
1015 rc = RegDeleteValue(hKey, subKey);
1016 Py_END_ALLOW_THREADS
1017 if (rc !=ERROR_SUCCESS)
1018 return PyErr_SetFromWindowsErrWithFunction(rc,
1019 "RegDeleteValue");
1020 Py_INCREF(Py_None);
1021 return Py_None;
1022}
1023
1024static PyObject *
1025PyEnumKey(PyObject *self, PyObject *args)
1026{
1027 HKEY hKey;
1028 PyObject *obKey;
1029 int index;
1030 long rc;
1031 char *retBuf;
1032 DWORD len;
1033
1034 if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index))
1035 return NULL;
1036 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1037 return NULL;
1038
1039 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, &len,
1040 NULL, NULL, NULL, NULL, NULL, NULL))
1041 != ERROR_SUCCESS)
1042 return PyErr_SetFromWindowsErrWithFunction(rc,
1043 "RegQueryInfoKey");
1044 ++len; /* include null terminator */
1045 retBuf = (char *)alloca(len);
1046
1047 if ((rc = RegEnumKey(hKey, index, retBuf, len)) != ERROR_SUCCESS)
1048 return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKey");
1049 return Py_BuildValue("s", retBuf);
1050}
1051
1052static PyObject *
1053PyEnumValue(PyObject *self, PyObject *args)
1054{
1055 HKEY hKey;
1056 PyObject *obKey;
1057 int index;
1058 long rc;
1059 char *retValueBuf;
1060 char *retDataBuf;
1061 DWORD retValueSize;
1062 DWORD retDataSize;
1063 DWORD typ;
1064 PyObject *obData;
1065 PyObject *retVal;
1066
1067 if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index))
1068 return NULL;
1069 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1070 return NULL;
1071
1072 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
1073 NULL,
1074 &retValueSize, &retDataSize, NULL, NULL))
1075 != ERROR_SUCCESS)
1076 return PyErr_SetFromWindowsErrWithFunction(rc,
1077 "RegQueryInfoKey");
1078 ++retValueSize; /* include null terminators */
1079 ++retDataSize;
1080 retValueBuf = (char *)alloca(retValueSize);
1081 retDataBuf = (char *)alloca(retDataSize);
1082
1083 Py_BEGIN_ALLOW_THREADS
1084 rc = RegEnumValue(hKey,
1085 index,
1086 retValueBuf,
1087 &retValueSize,
1088 NULL,
1089 &typ,
1090 (BYTE *)retDataBuf,
1091 &retDataSize);
1092 Py_END_ALLOW_THREADS
1093
1094 if (rc != ERROR_SUCCESS)
1095 return PyErr_SetFromWindowsErrWithFunction(rc,
1096 "PyRegEnumValue");
1097 obData = Reg2Py(retDataBuf, retDataSize, typ);
1098 if (obData == NULL)
1099 return NULL;
1100 retVal = Py_BuildValue("sOi", retValueBuf, obData, typ);
1101 Py_DECREF(obData);
1102 return retVal;
1103}
1104
1105static PyObject *
1106PyFlushKey(PyObject *self, PyObject *args)
1107{
1108 HKEY hKey;
1109 PyObject *obKey;
1110 long rc;
1111 if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey))
1112 return NULL;
1113 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1114 return NULL;
1115 Py_BEGIN_ALLOW_THREADS
1116 rc = RegFlushKey(hKey);
1117 Py_END_ALLOW_THREADS
1118 if (rc != ERROR_SUCCESS)
1119 return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
1120 Py_INCREF(Py_None);
1121 return Py_None;
1122}
1123static PyObject *
1124PyLoadKey(PyObject *self, PyObject *args)
1125{
1126 HKEY hKey;
1127 PyObject *obKey;
1128 char *subKey;
1129 char *fileName;
1130
1131 long rc;
1132 if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName))
1133 return NULL;
1134 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1135 return NULL;
1136 Py_BEGIN_ALLOW_THREADS
1137 rc = RegLoadKey(hKey, subKey, fileName );
1138 Py_END_ALLOW_THREADS
1139 if (rc != ERROR_SUCCESS)
1140 return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
1141 Py_INCREF(Py_None);
1142 return Py_None;
1143}
1144
1145static PyObject *
1146PyOpenKey(PyObject *self, PyObject *args)
1147{
1148 HKEY hKey;
1149 PyObject *obKey;
1150
1151 char *subKey;
1152 int res = 0;
1153 HKEY retKey;
1154 long rc;
1155 REGSAM sam = KEY_READ;
1156 if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey,
1157 &res, &sam))
1158 return NULL;
1159 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1160 return NULL;
1161
1162 Py_BEGIN_ALLOW_THREADS
1163 rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey);
1164 Py_END_ALLOW_THREADS
1165 if (rc != ERROR_SUCCESS)
1166 return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
1167 return PyHKEY_FromHKEY(retKey);
1168}
1169
1170
1171static PyObject *
1172PyQueryInfoKey(PyObject *self, PyObject *args)
1173{
1174 HKEY hKey;
1175 PyObject *obKey;
1176 long rc;
1177 DWORD nSubKeys, nValues;
1178 FILETIME ft;
1179 LARGE_INTEGER li;
1180 PyObject *l;
1181 PyObject *ret;
1182 if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey))
1183 return NULL;
1184 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1185 return NULL;
1186 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL,
1187 &nValues, NULL, NULL, NULL, &ft))
1188 != ERROR_SUCCESS)
1189 return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
1190 li.LowPart = ft.dwLowDateTime;
1191 li.HighPart = ft.dwHighDateTime;
1192 l = PyLong_FromLongLong(li.QuadPart);
1193 if (l == NULL)
1194 return NULL;
1195 ret = Py_BuildValue("iiO", nSubKeys, nValues, l);
1196 Py_DECREF(l);
1197 return ret;
1198}
1199
1200static PyObject *
1201PyQueryValue(PyObject *self, PyObject *args)
1202{
1203 HKEY hKey;
1204 PyObject *obKey;
1205 char *subKey;
1206
1207 long rc;
1208 char *retBuf;
1209 long bufSize = 0;
1210 if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey))
1211 return NULL;
1212
1213 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1214 return NULL;
1215 if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize))
1216 != ERROR_SUCCESS)
1217 return PyErr_SetFromWindowsErrWithFunction(rc,
1218 "RegQueryValue");
1219 retBuf = (char *)alloca(bufSize);
1220 if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize))
1221 != ERROR_SUCCESS)
1222 return PyErr_SetFromWindowsErrWithFunction(rc,
1223 "RegQueryValue");
1224 return Py_BuildValue("s", retBuf);
1225}
1226
1227static PyObject *
1228PyQueryValueEx(PyObject *self, PyObject *args)
1229{
1230 HKEY hKey;
1231 PyObject *obKey;
1232 char *valueName;
1233
1234 long rc;
1235 char *retBuf;
1236 DWORD bufSize = 0;
1237 DWORD typ;
1238 PyObject *obData;
1239 PyObject *result;
1240
1241 if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName))
1242 return NULL;
1243
1244 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1245 return NULL;
1246 if ((rc = RegQueryValueEx(hKey, valueName,
1247 NULL, NULL, NULL,
1248 &bufSize))
1249 != ERROR_SUCCESS)
1250 return PyErr_SetFromWindowsErrWithFunction(rc,
1251 "RegQueryValueEx");
1252 retBuf = (char *)alloca(bufSize);
1253 if ((rc = RegQueryValueEx(hKey, valueName, NULL,
1254 &typ, (BYTE *)retBuf, &bufSize))
1255 != ERROR_SUCCESS)
1256 return PyErr_SetFromWindowsErrWithFunction(rc,
1257 "RegQueryValueEx");
1258 obData = Reg2Py(retBuf, bufSize, typ);
1259 if (obData == NULL)
1260 return NULL;
1261 result = Py_BuildValue("Oi", obData, typ);
1262 Py_DECREF(obData);
1263 return result;
1264}
1265
1266
1267static PyObject *
1268PySaveKey(PyObject *self, PyObject *args)
1269{
1270 HKEY hKey;
1271 PyObject *obKey;
1272 char *fileName;
1273 LPSECURITY_ATTRIBUTES pSA = NULL;
1274
1275 long rc;
1276 if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName))
1277 return NULL;
1278 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1279 return NULL;
1280/* One day we may get security into the core?
1281 if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
1282 return NULL;
1283*/
1284 Py_BEGIN_ALLOW_THREADS
1285 rc = RegSaveKey(hKey, fileName, pSA );
1286 Py_END_ALLOW_THREADS
1287 if (rc != ERROR_SUCCESS)
1288 return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
1289 Py_INCREF(Py_None);
1290 return Py_None;
1291}
1292
1293static PyObject *
1294PySetValue(PyObject *self, PyObject *args)
1295{
1296 HKEY hKey;
1297 PyObject *obKey;
1298 char *subKey;
1299 char *str;
1300 DWORD typ;
1301 DWORD len;
1302 long rc;
1303 PyObject *obStrVal;
1304 PyObject *obSubKey;
1305 if (!PyArg_ParseTuple(args, "OOiO:SetValue",
1306 &obKey,
1307 &obSubKey,
1308 &typ,
1309 &obStrVal))
1310 return NULL;
1311 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1312 return NULL;
1313 if (typ != REG_SZ) {
1314 PyErr_SetString(PyExc_TypeError,
1315 "Type must be win32con.REG_SZ");
1316 return NULL;
1317 }
1318 /* XXX - need Unicode support */
1319 str = PyString_AsString(obStrVal);
1320 if (str == NULL)
1321 return NULL;
1322 len = PyString_Size(obStrVal);
1323 if (obSubKey == Py_None)
1324 subKey = NULL;
1325 else {
1326 subKey = PyString_AsString(obSubKey);
1327 if (subKey == NULL)
1328 return NULL;
1329 }
1330 Py_BEGIN_ALLOW_THREADS
1331 rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1);
1332 Py_END_ALLOW_THREADS
1333 if (rc != ERROR_SUCCESS)
1334 return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue");
1335 Py_INCREF(Py_None);
1336 return Py_None;
1337}
1338
1339static PyObject *
1340PySetValueEx(PyObject *self, PyObject *args)
1341{
1342 HKEY hKey;
1343 PyObject *obKey;
1344 char *valueName;
1345 PyObject *obRes;
1346 PyObject *value;
1347 BYTE *data;
1348 DWORD len;
1349 DWORD typ;
1350
1351 LONG rc;
1352
1353 if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx",
1354 &obKey,
1355 &valueName,
1356 &obRes,
1357 &typ,
1358 &value))
1359 return NULL;
1360 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1361 return NULL;
1362 if (!Py2Reg(value, typ, &data, &len))
1363 {
1364 if (!PyErr_Occurred())
1365 PyErr_SetString(PyExc_ValueError,
1366 "Could not convert the data to the specified type.");
1367 return NULL;
1368 }
1369 Py_BEGIN_ALLOW_THREADS
1370 rc = RegSetValueEx(hKey, valueName, 0, typ, data, len);
1371 Py_END_ALLOW_THREADS
Guido van Rossumb18618d2000-05-03 23:44:39 +00001372 PyMem_DEL(data);
Guido van Rossum9f3712c2000-03-28 20:37:15 +00001373 if (rc != ERROR_SUCCESS)
1374 return PyErr_SetFromWindowsErrWithFunction(rc,
1375 "RegSetValueEx");
1376 Py_INCREF(Py_None);
1377 return Py_None;
1378}
1379
1380static struct PyMethodDef winreg_methods[] = {
1381 {"CloseKey", PyCloseKey, 1, CloseKey_doc},
1382 {"ConnectRegistry", PyConnectRegistry, 1, ConnectRegistry_doc},
1383 {"CreateKey", PyCreateKey, 1, CreateKey_doc},
1384 {"DeleteKey", PyDeleteKey, 1, DeleteKey_doc},
1385 {"DeleteValue", PyDeleteValue, 1, DeleteValue_doc},
1386 {"EnumKey", PyEnumKey, 1, EnumKey_doc},
1387 {"EnumValue", PyEnumValue, 1, EnumValue_doc},
1388 {"FlushKey", PyFlushKey, 1, FlushKey_doc},
1389 {"LoadKey", PyLoadKey, 1, LoadKey_doc},
1390 {"OpenKey", PyOpenKey, 1, OpenKey_doc},
1391 {"OpenKeyEx", PyOpenKey, 1, OpenKeyEx_doc},
1392 {"QueryValue", PyQueryValue, 1, QueryValue_doc},
1393 {"QueryValueEx", PyQueryValueEx, 1, QueryValueEx_doc},
1394 {"QueryInfoKey", PyQueryInfoKey, 1, QueryInfoKey_doc},
1395 {"SaveKey", PySaveKey, 1, SaveKey_doc},
1396 {"SetValue", PySetValue, 1, SetValue_doc},
1397 {"SetValueEx", PySetValueEx, 1, SetValueEx_doc},
1398 NULL,
1399};
1400
1401static void
1402insint(PyObject * d, char * name, long value)
1403{
1404 PyObject *v = PyInt_FromLong(value);
1405 if (!v || PyDict_SetItemString(d, name, v))
1406 PyErr_Clear();
1407 Py_XDECREF(v);
1408}
1409
1410#define ADD_INT(val) insint(d, #val, val)
1411
1412static void
1413inskey(PyObject * d, char * name, HKEY key)
1414{
1415 PyObject *v = PyLong_FromVoidPtr(key);
1416 if (!v || PyDict_SetItemString(d, name, v))
1417 PyErr_Clear();
1418 Py_XDECREF(v);
1419}
1420
1421#define ADD_KEY(val) inskey(d, #val, val)
1422
Fred Drake270e19b2000-06-29 16:14:14 +00001423__declspec(dllexport) void init_winreg(void)
Guido van Rossum9f3712c2000-03-28 20:37:15 +00001424{
1425 PyObject *m, *d;
Fred Drake270e19b2000-06-29 16:14:14 +00001426 m = Py_InitModule3("_winreg", winreg_methods, module_doc);
Guido van Rossum9f3712c2000-03-28 20:37:15 +00001427 d = PyModule_GetDict(m);
1428 PyHKEY_Type.ob_type = &PyType_Type;
1429 PyHKEY_Type.tp_doc = PyHKEY_doc;
1430 Py_INCREF(&PyHKEY_Type);
1431 if (PyDict_SetItemString(d, "HKEYType",
1432 (PyObject *)&PyHKEY_Type) != 0)
1433 return;
1434 Py_INCREF(PyExc_WindowsError);
1435 if (PyDict_SetItemString(d, "error",
1436 PyExc_WindowsError) != 0)
1437 return;
1438
1439 /* Add the relevant constants */
1440 ADD_KEY(HKEY_CLASSES_ROOT);
1441 ADD_KEY(HKEY_CURRENT_USER);
1442 ADD_KEY(HKEY_LOCAL_MACHINE);
1443 ADD_KEY(HKEY_USERS);
1444 ADD_KEY(HKEY_PERFORMANCE_DATA);
1445#ifdef HKEY_CURRENT_CONFIG
1446 ADD_KEY(HKEY_CURRENT_CONFIG);
1447#endif
1448#ifdef HKEY_DYN_DATA
1449 ADD_KEY(HKEY_DYN_DATA);
1450#endif
1451 ADD_INT(KEY_QUERY_VALUE);
1452 ADD_INT(KEY_SET_VALUE);
1453 ADD_INT(KEY_CREATE_SUB_KEY);
1454 ADD_INT(KEY_ENUMERATE_SUB_KEYS);
1455 ADD_INT(KEY_NOTIFY);
1456 ADD_INT(KEY_CREATE_LINK);
1457 ADD_INT(KEY_READ);
1458 ADD_INT(KEY_WRITE);
1459 ADD_INT(KEY_EXECUTE);
1460 ADD_INT(KEY_ALL_ACCESS);
1461 ADD_INT(REG_OPTION_RESERVED);
1462 ADD_INT(REG_OPTION_NON_VOLATILE);
1463 ADD_INT(REG_OPTION_VOLATILE);
1464 ADD_INT(REG_OPTION_CREATE_LINK);
1465 ADD_INT(REG_OPTION_BACKUP_RESTORE);
1466 ADD_INT(REG_OPTION_OPEN_LINK);
1467 ADD_INT(REG_LEGAL_OPTION);
1468 ADD_INT(REG_CREATED_NEW_KEY);
1469 ADD_INT(REG_OPENED_EXISTING_KEY);
1470 ADD_INT(REG_WHOLE_HIVE_VOLATILE);
1471 ADD_INT(REG_REFRESH_HIVE);
1472 ADD_INT(REG_NO_LAZY_FLUSH);
1473 ADD_INT(REG_NOTIFY_CHANGE_NAME);
1474 ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
1475 ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
1476 ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
1477 ADD_INT(REG_LEGAL_CHANGE_FILTER);
1478 ADD_INT(REG_NONE);
1479 ADD_INT(REG_SZ);
1480 ADD_INT(REG_EXPAND_SZ);
1481 ADD_INT(REG_BINARY);
1482 ADD_INT(REG_DWORD);
1483 ADD_INT(REG_DWORD_LITTLE_ENDIAN);
1484 ADD_INT(REG_DWORD_BIG_ENDIAN);
1485 ADD_INT(REG_LINK);
1486 ADD_INT(REG_MULTI_SZ);
1487 ADD_INT(REG_RESOURCE_LIST);
1488 ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
1489 ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
1490}
1491