4 Windows Registry access module for Python.
6 * Simple registry access written by Mark Hammond in win32api
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.
17 #include "structmember.h"
18 #include "malloc.h" /* for alloca */
20 static BOOL
PyHKEY_AsHKEY(PyObject
*ob
, HKEY
*pRes
, BOOL bNoneOK
);
21 static PyObject
*PyHKEY_FromHKEY(HKEY h
);
22 static BOOL
PyHKEY_Close(PyObject
*obHandle
);
24 static char errNotAHandle
[] = "Object is not a handle";
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...
31 #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
32 PyErr_SetFromWindowsErr(rc)
34 /* Forward declares */
37 PyDoc_STRVAR(module_doc
,
38 "This module provides access to the Windows registry API.\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"
66 "HKEYType -- type object for HKEY objects\n"
67 "error -- exception raised for Win32 errors\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.");
74 PyDoc_STRVAR(CloseKey_doc
,
75 "CloseKey(hkey) - Closes a previously opened registry key.\n"
77 "The hkey argument specifies a previously opened key.\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.");
82 PyDoc_STRVAR(ConnectRegistry_doc
,
83 "key = ConnectRegistry(computer_name, key) - "
84 "Establishes a connection to a predefined registry handle on another computer.\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"
90 "The return value is the handle of the opened key.\n"
91 "If the function fails, an EnvironmentError exception is raised.");
93 PyDoc_STRVAR(CreateKey_doc
,
94 "key = CreateKey(key, sub_key) - Creates or opens the specified key.\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"
101 "If the key already exists, this function opens the existing key\n"
103 "The return value is the handle of the opened key.\n"
104 "If the function fails, an exception is raised.");
106 PyDoc_STRVAR(DeleteKey_doc
,
107 "DeleteKey(key, sub_key) - Deletes the specified key.\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"
113 "This method can not delete keys with subkeys.\n"
115 "If the method succeeds, the entire key, including all of its values,\n"
116 "is removed. If the method fails, an EnvironmentError exception is raised.");
118 PyDoc_STRVAR(DeleteValue_doc
,
119 "DeleteValue(key, value) - Removes a named value from a registry key.\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.");
124 PyDoc_STRVAR(EnumKey_doc
,
125 "string = EnumKey(key, index) - Enumerates subkeys of an open registry key.\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"
130 "The function retrieves the name of one subkey each time it is called.\n"
131 "It is typically called repeatedly until an EnvironmentError exception is\n"
132 "raised, indicating no more values are available.");
134 PyDoc_STRVAR(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"
139 "The function retrieves the name of one subkey each time it is called.\n"
140 "It is typically called repeatedly, until an EnvironmentError exception\n"
141 "is raised, indicating no more values.\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.");
149 PyDoc_STRVAR(FlushKey_doc
,
150 "FlushKey(key) - Writes all the attributes of a key to the registry.\n"
152 "key is an already open key, or any one of the predefined HKEY_* constants.\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.");
162 PyDoc_STRVAR(LoadKey_doc
,
163 "LoadKey(key, sub_key, file_name) - Creates a subkey under the specified key\n"
164 "and stores registration information from a specified file into that subkey.\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"
173 "A call to LoadKey() fails if the calling process does not have the\n"
174 "SE_RESTORE_PRIVILEGE privilege.\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"
179 "The docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree");
181 PyDoc_STRVAR(OpenKey_doc
,
182 "key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key.\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"
190 "The result is a new handle to the specified key\n"
191 "If the function fails, an EnvironmentError exception is raised.");
193 PyDoc_STRVAR(OpenKeyEx_doc
, "See OpenKey()");
195 PyDoc_STRVAR(QueryInfoKey_doc
,
196 "tuple = QueryInfoKey(key) - Returns information about a key.\n"
198 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
200 "The result is a tuple of 3 items:"
201 "An integer that identifies the number of sub keys this key has.\n"
202 "An integer that identifies the number of values this key has.\n"
203 "A long integer that identifies when the key was last modified (if available)\n"
204 " as 100's of nanoseconds since Jan 1, 1600.");
206 PyDoc_STRVAR(QueryValue_doc
,
207 "string = QueryValue(key, sub_key) - retrieves the unnamed value for a key.\n"
209 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
210 "sub_key is a string that holds the name of the subkey with which the value\n"
211 " is associated. If this parameter is None or empty, the function retrieves\n"
212 " the value set by the SetValue() method for the key identified by key."
214 "Values in the registry have name, type, and data components. This method\n"
215 "retrieves the data for a key's first value that has a NULL name.\n"
216 "But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!");
218 PyDoc_STRVAR(QueryValueEx_doc
,
219 "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 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
222 "value_name is a string indicating the value to query");
224 PyDoc_STRVAR(SaveKey_doc
,
225 "SaveKey(key, file_name) - Saves the specified key, and all its subkeys to the specified file.\n"
227 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
228 "file_name is the name of the file to save registry data to.\n"
229 " This file cannot already exist. If this filename includes an extension,\n"
230 " it cannot be used on file allocation table (FAT) file systems by the\n"
231 " LoadKey(), ReplaceKey() or RestoreKey() methods.\n"
233 "If key represents a key on a remote computer, the path described by\n"
234 "file_name is relative to the remote computer.\n"
235 "The caller of this method must possess the SeBackupPrivilege security privilege.\n"
236 "This function passes NULL for security_attributes to the API.");
238 PyDoc_STRVAR(SetValue_doc
,
239 "SetValue(key, sub_key, type, value) - Associates a value with a specified key.\n"
241 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
242 "sub_key is a string that names the subkey with which the value is associated.\n"
243 "type is an integer that specifies the type of the data. Currently this\n"
244 " must be REG_SZ, meaning only strings are supported.\n"
245 "value is a string that specifies the new value.\n"
247 "If the key specified by the sub_key parameter does not exist, the SetValue\n"
248 "function creates it.\n"
250 "Value lengths are limited by available memory. Long values (more than\n"
251 "2048 bytes) should be stored as files with the filenames stored in \n"
252 "the configuration registry. This helps the registry perform efficiently.\n"
254 "The key identified by the key parameter must have been opened with\n"
255 "KEY_SET_VALUE access.");
257 PyDoc_STRVAR(SetValueEx_doc
,
258 "SetValueEx(key, value_name, reserved, type, value) - Stores data in the value field of an open registry key.\n"
260 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
261 "value_name is a string containing the name of the value to set, or None\n"
262 "type is an integer that specifies the type of the data. This should be one of:\n"
263 " REG_BINARY -- Binary data in any form.\n"
264 " REG_DWORD -- A 32-bit number.\n"
265 " REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format.\n"
266 " REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.\n"
267 " REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references\n"
268 " to environment variables (for example, %PATH%).\n"
269 " REG_LINK -- A Unicode symbolic link.\n"
270 " REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by\n"
271 " two null characters. Note that Python handles this\n"
272 " termination automatically.\n"
273 " REG_NONE -- No defined value type.\n"
274 " REG_RESOURCE_LIST -- A device-driver resource list.\n"
275 " REG_SZ -- A null-terminated string.\n"
276 "reserved can be anything - zero is always passed to the API.\n"
277 "value is a string that specifies the new value.\n"
279 "This method can also set additional value and type information for the\n"
280 "specified key. The key identified by the key parameter must have been\n"
281 "opened with KEY_SET_VALUE access.\n"
283 "To open the key, use the CreateKeyEx() or OpenKeyEx() methods.\n"
285 "Value lengths are limited by available memory. Long values (more than\n"
286 "2048 bytes) should be stored as files with the filenames stored in \n"
287 "the configuration registry. This helps the registry perform efficiently.");
289 /* PyHKEY docstrings */
290 PyDoc_STRVAR(PyHKEY_doc
,
291 "PyHKEY Object - A Python object, representing a win32 registry key.\n"
293 "This object wraps a Windows HKEY object, automatically closing it when\n"
294 "the object is destroyed. To guarantee cleanup, you can call either\n"
295 "the Close() method on the PyHKEY, or the CloseKey() method.\n"
297 "All functions which accept a handle object also accept an integer - \n"
298 "however, use of the handle object is encouraged.\n"
301 "Close() - Closes the underlying handle.\n"
302 "Detach() - Returns the integer Win32 handle, detaching it from the object\n"
305 "handle - The integer Win32 handle.\n"
308 "__nonzero__ - Handles with an open object return true, otherwise false.\n"
309 "__int__ - Converting a handle to an integer returns the Win32 handle.\n"
310 "__cmp__ - Handle objects are compared using the handle value.");
313 PyDoc_STRVAR(PyHKEY_Close_doc
,
314 "key.Close() - Closes the underlying Windows handle.\n"
316 "If the handle is already closed, no error is raised.");
318 PyDoc_STRVAR(PyHKEY_Detach_doc
,
319 "int = key.Detach() - Detaches the Windows handle from the handle object.\n"
321 "The result is the value of the handle before it is detached. If the\n"
322 "handle is already detached, this will return zero.\n"
324 "After calling this function, the handle is effectively invalidated,\n"
325 "but the handle is not closed. You would call this function when you\n"
326 "need the underlying win32 handle to exist beyond the lifetime of the\n"
328 "On 64 bit windows, the result of this function is a long integer");
331 /************************************************************************
333 The PyHKEY object definition
335 ************************************************************************/
341 #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
343 static char *failMsg
= "bad operand type";
346 PyHKEY_unaryFailureFunc(PyObject
*ob
)
348 PyErr_SetString(PyExc_TypeError
, failMsg
);
352 PyHKEY_binaryFailureFunc(PyObject
*ob1
, PyObject
*ob2
)
354 PyErr_SetString(PyExc_TypeError
, failMsg
);
358 PyHKEY_ternaryFailureFunc(PyObject
*ob1
, PyObject
*ob2
, PyObject
*ob3
)
360 PyErr_SetString(PyExc_TypeError
, failMsg
);
365 PyHKEY_deallocFunc(PyObject
*ob
)
367 /* Can not call PyHKEY_Close, as the ob->tp_type
368 has already been cleared, thus causing the type
371 PyHKEYObject
*obkey
= (PyHKEYObject
*)ob
;
373 RegCloseKey((HKEY
)obkey
->hkey
);
378 PyHKEY_nonzeroFunc(PyObject
*ob
)
380 return ((PyHKEYObject
*)ob
)->hkey
!= 0;
384 PyHKEY_intFunc(PyObject
*ob
)
386 PyHKEYObject
*pyhkey
= (PyHKEYObject
*)ob
;
387 return PyLong_FromVoidPtr(pyhkey
->hkey
);
391 PyHKEY_printFunc(PyObject
*ob
, FILE *fp
, int flags
)
393 PyHKEYObject
*pyhkey
= (PyHKEYObject
*)ob
;
395 wsprintf(resBuf
, "<PyHKEY at %p (%p)>",
402 PyHKEY_strFunc(PyObject
*ob
)
404 PyHKEYObject
*pyhkey
= (PyHKEYObject
*)ob
;
406 wsprintf(resBuf
, "<PyHKEY:%p>", pyhkey
->hkey
);
407 return PyString_FromString(resBuf
);
411 PyHKEY_compareFunc(PyObject
*ob1
, PyObject
*ob2
)
413 PyHKEYObject
*pyhkey1
= (PyHKEYObject
*)ob1
;
414 PyHKEYObject
*pyhkey2
= (PyHKEYObject
*)ob2
;
415 return pyhkey1
== pyhkey2
? 0 :
416 (pyhkey1
< pyhkey2
? -1 : 1);
420 PyHKEY_hashFunc(PyObject
*ob
)
422 /* Just use the address.
423 XXX - should we use the handle value?
425 return _Py_HashPointer(ob
);
429 static PyNumberMethods PyHKEY_NumberMethods
=
431 PyHKEY_binaryFailureFunc
, /* nb_add */
432 PyHKEY_binaryFailureFunc
, /* nb_subtract */
433 PyHKEY_binaryFailureFunc
, /* nb_multiply */
434 PyHKEY_binaryFailureFunc
, /* nb_divide */
435 PyHKEY_binaryFailureFunc
, /* nb_remainder */
436 PyHKEY_binaryFailureFunc
, /* nb_divmod */
437 PyHKEY_ternaryFailureFunc
, /* nb_power */
438 PyHKEY_unaryFailureFunc
, /* nb_negative */
439 PyHKEY_unaryFailureFunc
, /* nb_positive */
440 PyHKEY_unaryFailureFunc
, /* nb_absolute */
441 PyHKEY_nonzeroFunc
, /* nb_nonzero */
442 PyHKEY_unaryFailureFunc
, /* nb_invert */
443 PyHKEY_binaryFailureFunc
, /* nb_lshift */
444 PyHKEY_binaryFailureFunc
, /* nb_rshift */
445 PyHKEY_binaryFailureFunc
, /* nb_and */
446 PyHKEY_binaryFailureFunc
, /* nb_xor */
447 PyHKEY_binaryFailureFunc
, /* nb_or */
448 0, /* nb_coerce (allowed to be zero) */
449 PyHKEY_intFunc
, /* nb_int */
450 PyHKEY_unaryFailureFunc
, /* nb_long */
451 PyHKEY_unaryFailureFunc
, /* nb_float */
452 PyHKEY_unaryFailureFunc
, /* nb_oct */
453 PyHKEY_unaryFailureFunc
, /* nb_hex */
457 /* fwd declare __getattr__ */
458 static PyObject
*PyHKEY_getattr(PyObject
*self
, char *name
);
460 /* The type itself */
461 PyTypeObject PyHKEY_Type
=
463 PyObject_HEAD_INIT(0) /* fill in type at module init */
466 sizeof(PyHKEYObject
),
468 PyHKEY_deallocFunc
, /* tp_dealloc */
469 PyHKEY_printFunc
, /* tp_print */
470 PyHKEY_getattr
, /* tp_getattr */
472 PyHKEY_compareFunc
, /* tp_compare */
474 &PyHKEY_NumberMethods
, /* tp_as_number */
475 0, /* tp_as_sequence */
476 0, /* tp_as_mapping */
477 PyHKEY_hashFunc
, /* tp_hash */
479 PyHKEY_strFunc
, /* tp_str */
482 0, /* tp_as_buffer */
484 PyHKEY_doc
, /* tp_doc */
487 #define OFF(e) offsetof(PyHKEYObject, e)
489 static struct memberlist PyHKEY_memberlist
[] = {
490 {"handle", T_INT
, OFF(hkey
)},
491 {NULL
} /* Sentinel */
494 /************************************************************************
496 The PyHKEY object methods
498 ************************************************************************/
500 PyHKEY_CloseMethod(PyObject
*self
, PyObject
*args
)
502 if (!PyArg_ParseTuple(args
, ":Close"))
504 if (!PyHKEY_Close(self
))
511 PyHKEY_DetachMethod(PyObject
*self
, PyObject
*args
)
514 PyHKEYObject
*pThis
= (PyHKEYObject
*)self
;
515 if (!PyArg_ParseTuple(args
, ":Detach"))
517 ret
= (void*)pThis
->hkey
;
519 return PyLong_FromVoidPtr(ret
);
522 static struct PyMethodDef PyHKEY_methods
[] = {
523 {"Close", PyHKEY_CloseMethod
, METH_VARARGS
, PyHKEY_Close_doc
},
524 {"Detach", PyHKEY_DetachMethod
, METH_VARARGS
, PyHKEY_Detach_doc
},
528 /*static*/ PyObject
*
529 PyHKEY_getattr(PyObject
*self
, char *name
)
533 res
= Py_FindMethod(PyHKEY_methods
, self
, name
);
537 if (strcmp(name
, "handle") == 0)
538 return PyLong_FromVoidPtr(((PyHKEYObject
*)self
)->hkey
);
539 return PyMember_Get((char *)self
, PyHKEY_memberlist
, name
);
542 /************************************************************************
543 The public PyHKEY API (well, not public yet :-)
544 ************************************************************************/
546 PyHKEY_New(HKEY hInit
)
548 PyHKEYObject
*key
= PyObject_NEW(PyHKEYObject
, &PyHKEY_Type
);
551 return (PyObject
*)key
;
555 PyHKEY_Close(PyObject
*ob_handle
)
560 if (!PyHKEY_Check(ob_handle
)) {
561 PyErr_SetString(PyExc_TypeError
, "bad operand type");
564 key
= (PyHKEYObject
*)ob_handle
;
565 rc
= key
->hkey
? RegCloseKey((HKEY
)key
->hkey
) : ERROR_SUCCESS
;
567 if (rc
!= ERROR_SUCCESS
)
568 PyErr_SetFromWindowsErrWithFunction(rc
, "RegCloseKey");
569 return rc
== ERROR_SUCCESS
;
573 PyHKEY_AsHKEY(PyObject
*ob
, HKEY
*pHANDLE
, BOOL bNoneOK
)
579 "None is not a valid HKEY in this context");
584 else if (PyHKEY_Check(ob
)) {
585 PyHKEYObject
*pH
= (PyHKEYObject
*)ob
;
588 else if (PyInt_Check(ob
) || PyLong_Check(ob
)) {
589 /* We also support integers */
591 *pHANDLE
= (HKEY
)PyLong_AsVoidPtr(ob
);
592 if (PyErr_Occurred())
598 "The object is not a PyHKEY object");
605 PyHKEY_FromHKEY(HKEY h
)
609 /* Inline PyObject_New */
610 op
= (PyHKEYObject
*) PyObject_MALLOC(sizeof(PyHKEYObject
));
612 return PyErr_NoMemory();
613 PyObject_INIT(op
, &PyHKEY_Type
);
615 return (PyObject
*)op
;
619 /************************************************************************
621 ************************************************************************/
623 PyWinObject_CloseHKEY(PyObject
*obHandle
)
626 if (PyHKEY_Check(obHandle
)) {
627 ok
= PyHKEY_Close(obHandle
);
629 #if SIZEOF_LONG >= SIZEOF_HKEY
630 else if (PyInt_Check(obHandle
)) {
631 long rc
= RegCloseKey((HKEY
)PyInt_AsLong(obHandle
));
632 ok
= (rc
== ERROR_SUCCESS
);
634 PyErr_SetFromWindowsErrWithFunction(rc
, "RegCloseKey");
637 else if (PyLong_Check(obHandle
)) {
638 long rc
= RegCloseKey((HKEY
)PyLong_AsVoidPtr(obHandle
));
639 ok
= (rc
== ERROR_SUCCESS
);
641 PyErr_SetFromWindowsErrWithFunction(rc
, "RegCloseKey");
647 "A handle must be a HKEY object or an integer");
655 Private Helper functions for the registry interfaces
657 ** Note that fixupMultiSZ and countString have both had changes
658 ** made to support "incorrect strings". The registry specification
659 ** calls for strings to be terminated with 2 null bytes. It seems
660 ** some commercial packages install strings which dont conform,
661 ** causing this code to fail - however, "regedit" etc still work
662 ** with these strings (ie only we dont!).
665 fixupMultiSZ(char **str
, char *data
, int len
)
672 for (P
= data
, i
= 0; P
< Q
&& *P
!= '\0'; P
++, i
++) {
674 for(; *P
!= '\0'; P
++)
680 countStrings(char *data
, int len
)
684 char *Q
= data
+ len
;
686 for (P
= data
, strings
= 0; P
< Q
&& *P
!= '\0'; P
++, strings
++)
687 for (; P
< Q
&& *P
!= '\0'; P
++)
692 /* Convert PyObject into Registry data.
693 Allocates space as needed. */
695 Py2Reg(PyObject
*value
, DWORD typ
, BYTE
**retDataBuf
, DWORD
*retDataSize
)
700 if (value
!= Py_None
&& !PyInt_Check(value
))
702 *retDataBuf
= (BYTE
*)PyMem_NEW(DWORD
, sizeof(DWORD
));
703 if (*retDataBuf
==NULL
){
707 *retDataSize
= sizeof(DWORD
);
708 if (value
== Py_None
) {
710 memcpy(*retDataBuf
, &zero
, sizeof(DWORD
));
714 &PyInt_AS_LONG((PyIntObject
*)value
),
721 if (value
== Py_None
)
724 if (PyUnicode_Check(value
)) {
725 value
= PyUnicode_AsEncodedString(
733 if (!PyString_Check(value
))
735 *retDataSize
= 1 + strlen(
737 (PyStringObject
*)value
));
739 *retDataBuf
= (BYTE
*)PyMem_NEW(DWORD
, *retDataSize
);
740 if (*retDataBuf
==NULL
){
744 if (value
== Py_None
)
745 strcpy((char *)*retDataBuf
, "");
747 strcpy((char *)*retDataBuf
,
749 (PyStringObject
*)value
));
758 PyObject
**obs
= NULL
;
760 if (value
== Py_None
)
763 if (!PyList_Check(value
))
765 i
= PyList_Size(value
);
767 obs
= malloc(sizeof(PyObject
*) * i
);
768 memset(obs
, 0, sizeof(PyObject
*) * i
);
769 for (j
= 0; j
< i
; j
++)
773 (PyListObject
*)value
,j
);
774 if (PyString_Check(t
)) {
777 } else if (PyUnicode_Check(t
)) {
778 obs
[j
] = PyUnicode_AsEncodedString(
788 (PyStringObject
*)obs
[j
]));
791 *retDataSize
= size
+ 1;
792 *retDataBuf
= (BYTE
*)PyMem_NEW(char,
794 if (*retDataBuf
==NULL
){
798 P
= (char *)*retDataBuf
;
800 for (j
= 0; j
< i
; j
++)
806 (PyStringObject
*)t
));
809 (PyStringObject
*)t
));
812 /* And doubly-terminate the list... */
818 for (j
= 0; j
< i
; j
++)
826 /* ALSO handle ALL unknown data types here. Even if we can't
827 support it natively, we should handle the bits. */
829 if (value
== Py_None
)
833 PyBufferProcs
*pb
= value
->ob_type
->tp_as_buffer
;
835 PyErr_Format(PyExc_TypeError
,
836 "Objects of type '%s' can not "
837 "be used as binary registry values",
838 value
->ob_type
->tp_name
);
841 *retDataSize
= (*pb
->bf_getreadbuffer
)(value
, 0, &src_buf
);
842 *retDataBuf
= (BYTE
*)PyMem_NEW(char,
844 if (*retDataBuf
==NULL
){
848 memcpy(*retDataBuf
, src_buf
, *retDataSize
);
855 /* Convert Registry data into PyObject*/
857 Reg2Py(char *retDataBuf
, DWORD retDataSize
, DWORD typ
)
863 if (retDataSize
== 0)
864 obData
= Py_BuildValue("i", 0);
866 obData
= Py_BuildValue("i",
871 /* retDataBuf may or may not have a trailing NULL in
873 if (retDataSize
&& retDataBuf
[retDataSize
-1] == '\0')
877 obData
= PyUnicode_DecodeMBCS(retDataBuf
,
882 if (retDataSize
== 0)
883 obData
= PyList_New(0);
887 int s
= countStrings(retDataBuf
, retDataSize
);
888 char **str
= (char **)malloc(sizeof(char *)*s
);
890 return PyErr_NoMemory();
892 fixupMultiSZ(str
, retDataBuf
, retDataSize
);
893 obData
= PyList_New(s
);
896 for (index
= 0; index
< s
; index
++)
898 size_t len
= _mbstrlen(str
[index
]);
900 PyErr_SetString(PyExc_OverflowError
,
901 "registry string is too long for a Python string");
905 PyList_SetItem(obData
,
907 PyUnicode_DecodeMBCS(
908 (const char *)str
[index
],
918 /* ALSO handle ALL unknown data types here. Even if we can't
919 support it natively, we should handle the bits. */
921 if (retDataSize
== 0) {
926 obData
= Py_BuildValue("s#",
937 /* The Python methods */
940 PyCloseKey(PyObject
*self
, PyObject
*args
)
943 if (!PyArg_ParseTuple(args
, "O:CloseKey", &obKey
))
945 if (!PyHKEY_Close(obKey
))
952 PyConnectRegistry(PyObject
*self
, PyObject
*args
)
956 char *szCompName
= NULL
;
959 if (!PyArg_ParseTuple(args
, "zO:ConnectRegistry", &szCompName
, &obKey
))
961 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
963 rc
= RegConnectRegistry(szCompName
, hKey
, &retKey
);
964 if (rc
!= ERROR_SUCCESS
)
965 return PyErr_SetFromWindowsErrWithFunction(rc
,
967 return PyHKEY_FromHKEY(retKey
);
971 PyCreateKey(PyObject
*self
, PyObject
*args
)
978 if (!PyArg_ParseTuple(args
, "Oz:CreateKey", &obKey
, &subKey
))
980 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
982 rc
= RegCreateKey(hKey
, subKey
, &retKey
);
983 if (rc
!= ERROR_SUCCESS
)
984 return PyErr_SetFromWindowsErrWithFunction(rc
, "CreateKey");
985 return PyHKEY_FromHKEY(retKey
);
989 PyDeleteKey(PyObject
*self
, PyObject
*args
)
995 if (!PyArg_ParseTuple(args
, "Os:DeleteKey", &obKey
, &subKey
))
997 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
999 rc
= RegDeleteKey(hKey
, subKey
);
1000 if (rc
!= ERROR_SUCCESS
)
1001 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegDeleteKey");
1007 PyDeleteValue(PyObject
*self
, PyObject
*args
)
1013 if (!PyArg_ParseTuple(args
, "Oz:DeleteValue", &obKey
, &subKey
))
1015 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1017 Py_BEGIN_ALLOW_THREADS
1018 rc
= RegDeleteValue(hKey
, subKey
);
1019 Py_END_ALLOW_THREADS
1020 if (rc
!=ERROR_SUCCESS
)
1021 return PyErr_SetFromWindowsErrWithFunction(rc
,
1028 PyEnumKey(PyObject
*self
, PyObject
*args
)
1037 if (!PyArg_ParseTuple(args
, "Oi:EnumKey", &obKey
, &index
))
1039 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1042 if ((rc
= RegQueryInfoKey(hKey
, NULL
, NULL
, NULL
, NULL
, &len
,
1043 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
))
1045 return PyErr_SetFromWindowsErrWithFunction(rc
,
1047 ++len
; /* include null terminator */
1048 retBuf
= (char *)alloca(len
);
1050 if ((rc
= RegEnumKey(hKey
, index
, retBuf
, len
)) != ERROR_SUCCESS
)
1051 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegEnumKey");
1052 return Py_BuildValue("s", retBuf
);
1056 PyEnumValue(PyObject
*self
, PyObject
*args
)
1070 if (!PyArg_ParseTuple(args
, "Oi:EnumValue", &obKey
, &index
))
1072 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1075 if ((rc
= RegQueryInfoKey(hKey
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
1077 &retValueSize
, &retDataSize
, NULL
, NULL
))
1079 return PyErr_SetFromWindowsErrWithFunction(rc
,
1081 ++retValueSize
; /* include null terminators */
1083 retValueBuf
= (char *)alloca(retValueSize
);
1084 retDataBuf
= (char *)alloca(retDataSize
);
1086 Py_BEGIN_ALLOW_THREADS
1087 rc
= RegEnumValue(hKey
,
1095 Py_END_ALLOW_THREADS
1097 if (rc
!= ERROR_SUCCESS
)
1098 return PyErr_SetFromWindowsErrWithFunction(rc
,
1100 obData
= Reg2Py(retDataBuf
, retDataSize
, typ
);
1103 retVal
= Py_BuildValue("sOi", retValueBuf
, obData
, typ
);
1109 PyFlushKey(PyObject
*self
, PyObject
*args
)
1114 if (!PyArg_ParseTuple(args
, "O:FlushKey", &obKey
))
1116 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1118 Py_BEGIN_ALLOW_THREADS
1119 rc
= RegFlushKey(hKey
);
1120 Py_END_ALLOW_THREADS
1121 if (rc
!= ERROR_SUCCESS
)
1122 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegFlushKey");
1127 PyLoadKey(PyObject
*self
, PyObject
*args
)
1135 if (!PyArg_ParseTuple(args
, "Oss:LoadKey", &obKey
, &subKey
, &fileName
))
1137 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1139 Py_BEGIN_ALLOW_THREADS
1140 rc
= RegLoadKey(hKey
, subKey
, fileName
);
1141 Py_END_ALLOW_THREADS
1142 if (rc
!= ERROR_SUCCESS
)
1143 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegLoadKey");
1149 PyOpenKey(PyObject
*self
, PyObject
*args
)
1158 REGSAM sam
= KEY_READ
;
1159 if (!PyArg_ParseTuple(args
, "Oz|ii:OpenKey", &obKey
, &subKey
,
1162 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1165 Py_BEGIN_ALLOW_THREADS
1166 rc
= RegOpenKeyEx(hKey
, subKey
, res
, sam
, &retKey
);
1167 Py_END_ALLOW_THREADS
1168 if (rc
!= ERROR_SUCCESS
)
1169 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegOpenKeyEx");
1170 return PyHKEY_FromHKEY(retKey
);
1175 PyQueryInfoKey(PyObject
*self
, PyObject
*args
)
1180 DWORD nSubKeys
, nValues
;
1185 if (!PyArg_ParseTuple(args
, "O:QueryInfoKey", &obKey
))
1187 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1189 if ((rc
= RegQueryInfoKey(hKey
, NULL
, NULL
, 0, &nSubKeys
, NULL
, NULL
,
1190 &nValues
, NULL
, NULL
, NULL
, &ft
))
1192 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegQueryInfoKey");
1193 li
.LowPart
= ft
.dwLowDateTime
;
1194 li
.HighPart
= ft
.dwHighDateTime
;
1195 l
= PyLong_FromLongLong(li
.QuadPart
);
1198 ret
= Py_BuildValue("iiO", nSubKeys
, nValues
, l
);
1204 PyQueryValue(PyObject
*self
, PyObject
*args
)
1213 if (!PyArg_ParseTuple(args
, "Oz:QueryValue", &obKey
, &subKey
))
1216 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1218 if ((rc
= RegQueryValue(hKey
, subKey
, NULL
, &bufSize
))
1220 return PyErr_SetFromWindowsErrWithFunction(rc
,
1222 retBuf
= (char *)alloca(bufSize
);
1223 if ((rc
= RegQueryValue(hKey
, subKey
, retBuf
, &bufSize
))
1225 return PyErr_SetFromWindowsErrWithFunction(rc
,
1227 return Py_BuildValue("s", retBuf
);
1231 PyQueryValueEx(PyObject
*self
, PyObject
*args
)
1244 if (!PyArg_ParseTuple(args
, "Oz:QueryValueEx", &obKey
, &valueName
))
1247 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1249 if ((rc
= RegQueryValueEx(hKey
, valueName
,
1253 return PyErr_SetFromWindowsErrWithFunction(rc
,
1255 retBuf
= (char *)alloca(bufSize
);
1256 if ((rc
= RegQueryValueEx(hKey
, valueName
, NULL
,
1257 &typ
, (BYTE
*)retBuf
, &bufSize
))
1259 return PyErr_SetFromWindowsErrWithFunction(rc
,
1261 obData
= Reg2Py(retBuf
, bufSize
, typ
);
1264 result
= Py_BuildValue("Oi", obData
, typ
);
1271 PySaveKey(PyObject
*self
, PyObject
*args
)
1276 LPSECURITY_ATTRIBUTES pSA
= NULL
;
1279 if (!PyArg_ParseTuple(args
, "Os:SaveKey", &obKey
, &fileName
))
1281 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1283 /* One day we may get security into the core?
1284 if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
1287 Py_BEGIN_ALLOW_THREADS
1288 rc
= RegSaveKey(hKey
, fileName
, pSA
);
1289 Py_END_ALLOW_THREADS
1290 if (rc
!= ERROR_SUCCESS
)
1291 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegSaveKey");
1297 PySetValue(PyObject
*self
, PyObject
*args
)
1308 if (!PyArg_ParseTuple(args
, "OOiO:SetValue",
1314 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1316 if (typ
!= REG_SZ
) {
1317 PyErr_SetString(PyExc_TypeError
,
1318 "Type must be _winreg.REG_SZ");
1321 /* XXX - need Unicode support */
1322 str
= PyString_AsString(obStrVal
);
1325 len
= PyString_Size(obStrVal
);
1326 if (obSubKey
== Py_None
)
1329 subKey
= PyString_AsString(obSubKey
);
1333 Py_BEGIN_ALLOW_THREADS
1334 rc
= RegSetValue(hKey
, subKey
, REG_SZ
, str
, len
+1);
1335 Py_END_ALLOW_THREADS
1336 if (rc
!= ERROR_SUCCESS
)
1337 return PyErr_SetFromWindowsErrWithFunction(rc
, "RegSetValue");
1343 PySetValueEx(PyObject
*self
, PyObject
*args
)
1356 if (!PyArg_ParseTuple(args
, "OzOiO:SetValueEx",
1363 if (!PyHKEY_AsHKEY(obKey
, &hKey
, FALSE
))
1365 if (!Py2Reg(value
, typ
, &data
, &len
))
1367 if (!PyErr_Occurred())
1368 PyErr_SetString(PyExc_ValueError
,
1369 "Could not convert the data to the specified type.");
1372 Py_BEGIN_ALLOW_THREADS
1373 rc
= RegSetValueEx(hKey
, valueName
, 0, typ
, data
, len
);
1374 Py_END_ALLOW_THREADS
1376 if (rc
!= ERROR_SUCCESS
)
1377 return PyErr_SetFromWindowsErrWithFunction(rc
,
1383 static struct PyMethodDef winreg_methods
[] = {
1384 {"CloseKey", PyCloseKey
, METH_VARARGS
, CloseKey_doc
},
1385 {"ConnectRegistry", PyConnectRegistry
, METH_VARARGS
, ConnectRegistry_doc
},
1386 {"CreateKey", PyCreateKey
, METH_VARARGS
, CreateKey_doc
},
1387 {"DeleteKey", PyDeleteKey
, METH_VARARGS
, DeleteKey_doc
},
1388 {"DeleteValue", PyDeleteValue
, METH_VARARGS
, DeleteValue_doc
},
1389 {"EnumKey", PyEnumKey
, METH_VARARGS
, EnumKey_doc
},
1390 {"EnumValue", PyEnumValue
, METH_VARARGS
, EnumValue_doc
},
1391 {"FlushKey", PyFlushKey
, METH_VARARGS
, FlushKey_doc
},
1392 {"LoadKey", PyLoadKey
, METH_VARARGS
, LoadKey_doc
},
1393 {"OpenKey", PyOpenKey
, METH_VARARGS
, OpenKey_doc
},
1394 {"OpenKeyEx", PyOpenKey
, METH_VARARGS
, OpenKeyEx_doc
},
1395 {"QueryValue", PyQueryValue
, METH_VARARGS
, QueryValue_doc
},
1396 {"QueryValueEx", PyQueryValueEx
, METH_VARARGS
, QueryValueEx_doc
},
1397 {"QueryInfoKey", PyQueryInfoKey
, METH_VARARGS
, QueryInfoKey_doc
},
1398 {"SaveKey", PySaveKey
, METH_VARARGS
, SaveKey_doc
},
1399 {"SetValue", PySetValue
, METH_VARARGS
, SetValue_doc
},
1400 {"SetValueEx", PySetValueEx
, METH_VARARGS
, SetValueEx_doc
},
1405 insint(PyObject
* d
, char * name
, long value
)
1407 PyObject
*v
= PyInt_FromLong(value
);
1408 if (!v
|| PyDict_SetItemString(d
, name
, v
))
1413 #define ADD_INT(val) insint(d, #val, val)
1416 inskey(PyObject
* d
, char * name
, HKEY key
)
1418 PyObject
*v
= PyLong_FromVoidPtr(key
);
1419 if (!v
|| PyDict_SetItemString(d
, name
, v
))
1424 #define ADD_KEY(val) inskey(d, #val, val)
1426 PyMODINIT_FUNC
init_winreg(void)
1429 m
= Py_InitModule3("_winreg", winreg_methods
, module_doc
);
1430 d
= PyModule_GetDict(m
);
1431 PyHKEY_Type
.ob_type
= &PyType_Type
;
1432 PyHKEY_Type
.tp_doc
= PyHKEY_doc
;
1433 Py_INCREF(&PyHKEY_Type
);
1434 if (PyDict_SetItemString(d
, "HKEYType",
1435 (PyObject
*)&PyHKEY_Type
) != 0)
1437 Py_INCREF(PyExc_WindowsError
);
1438 if (PyDict_SetItemString(d
, "error",
1439 PyExc_WindowsError
) != 0)
1442 /* Add the relevant constants */
1443 ADD_KEY(HKEY_CLASSES_ROOT
);
1444 ADD_KEY(HKEY_CURRENT_USER
);
1445 ADD_KEY(HKEY_LOCAL_MACHINE
);
1446 ADD_KEY(HKEY_USERS
);
1447 ADD_KEY(HKEY_PERFORMANCE_DATA
);
1448 #ifdef HKEY_CURRENT_CONFIG
1449 ADD_KEY(HKEY_CURRENT_CONFIG
);
1451 #ifdef HKEY_DYN_DATA
1452 ADD_KEY(HKEY_DYN_DATA
);
1454 ADD_INT(KEY_QUERY_VALUE
);
1455 ADD_INT(KEY_SET_VALUE
);
1456 ADD_INT(KEY_CREATE_SUB_KEY
);
1457 ADD_INT(KEY_ENUMERATE_SUB_KEYS
);
1458 ADD_INT(KEY_NOTIFY
);
1459 ADD_INT(KEY_CREATE_LINK
);
1462 ADD_INT(KEY_EXECUTE
);
1463 ADD_INT(KEY_ALL_ACCESS
);
1464 ADD_INT(REG_OPTION_RESERVED
);
1465 ADD_INT(REG_OPTION_NON_VOLATILE
);
1466 ADD_INT(REG_OPTION_VOLATILE
);
1467 ADD_INT(REG_OPTION_CREATE_LINK
);
1468 ADD_INT(REG_OPTION_BACKUP_RESTORE
);
1469 ADD_INT(REG_OPTION_OPEN_LINK
);
1470 ADD_INT(REG_LEGAL_OPTION
);
1471 ADD_INT(REG_CREATED_NEW_KEY
);
1472 ADD_INT(REG_OPENED_EXISTING_KEY
);
1473 ADD_INT(REG_WHOLE_HIVE_VOLATILE
);
1474 ADD_INT(REG_REFRESH_HIVE
);
1475 ADD_INT(REG_NO_LAZY_FLUSH
);
1476 ADD_INT(REG_NOTIFY_CHANGE_NAME
);
1477 ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES
);
1478 ADD_INT(REG_NOTIFY_CHANGE_LAST_SET
);
1479 ADD_INT(REG_NOTIFY_CHANGE_SECURITY
);
1480 ADD_INT(REG_LEGAL_CHANGE_FILTER
);
1483 ADD_INT(REG_EXPAND_SZ
);
1484 ADD_INT(REG_BINARY
);
1486 ADD_INT(REG_DWORD_LITTLE_ENDIAN
);
1487 ADD_INT(REG_DWORD_BIG_ENDIAN
);
1489 ADD_INT(REG_MULTI_SZ
);
1490 ADD_INT(REG_RESOURCE_LIST
);
1491 ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR
);
1492 ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST
);