Change to flush and close logic to fix #1760556.
[python.git] / PC / _winreg.c
blob9ddbb236a99fa41175643199dc13456d45d78ea4
1 /*
2 _winreg.c
4 Windows Registry access module for Python.
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.
15 #include "Python.h"
16 #include "structmember.h"
17 #include "malloc.h" /* for alloca */
18 #include "windows.h"
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 */
36 /* Doc strings */
37 PyDoc_STRVAR(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.");
74 PyDoc_STRVAR(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.");
82 PyDoc_STRVAR(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"
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"
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.");
106 PyDoc_STRVAR(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"
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"
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.");
124 PyDoc_STRVAR(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"
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"
138 "\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"
142 "\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"
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.");
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"
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");
181 PyDoc_STRVAR(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"
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"
197 "\n"
198 "key is an already open key, or any one of the predefined HKEY_* constants.\n"
199 "\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"
208 "\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."
213 "\n"
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"
220 "\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"
226 "\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"
232 "\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"
240 "\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"
246 "\n"
247 "If the key specified by the sub_key parameter does not exist, the SetValue\n"
248 "function creates it.\n"
249 "\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"
253 "\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"
259 "\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"
278 "\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"
282 "\n"
283 "To open the key, use the CreateKeyEx() or OpenKeyEx() methods.\n"
284 "\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"
292 "\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"
296 "\n"
297 "All functions which accept a handle object also accept an integer - \n"
298 "however, use of the handle object is encouraged.\n"
299 "\n"
300 "Functions:\n"
301 "Close() - Closes the underlying handle.\n"
302 "Detach() - Returns the integer Win32 handle, detaching it from the object\n"
303 "\n"
304 "Properties:\n"
305 "handle - The integer Win32 handle.\n"
306 "\n"
307 "Operations:\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"
315 "\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"
320 "\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"
323 "\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"
327 "handle object.\n"
328 "On 64 bit windows, the result of this function is a long integer");
331 /************************************************************************
333 The PyHKEY object definition
335 ************************************************************************/
336 typedef struct {
337 PyObject_VAR_HEAD
338 HKEY hkey;
339 } PyHKEYObject;
341 #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
343 static char *failMsg = "bad operand type";
345 static PyObject *
346 PyHKEY_unaryFailureFunc(PyObject *ob)
348 PyErr_SetString(PyExc_TypeError, failMsg);
349 return NULL;
351 static PyObject *
352 PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
354 PyErr_SetString(PyExc_TypeError, failMsg);
355 return NULL;
357 static PyObject *
358 PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
360 PyErr_SetString(PyExc_TypeError, failMsg);
361 return NULL;
364 static void
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
369 check to fail!
371 PyHKEYObject *obkey = (PyHKEYObject *)ob;
372 if (obkey->hkey)
373 RegCloseKey((HKEY)obkey->hkey);
374 PyObject_DEL(ob);
377 static int
378 PyHKEY_nonzeroFunc(PyObject *ob)
380 return ((PyHKEYObject *)ob)->hkey != 0;
383 static PyObject *
384 PyHKEY_intFunc(PyObject *ob)
386 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
387 return PyLong_FromVoidPtr(pyhkey->hkey);
390 static int
391 PyHKEY_printFunc(PyObject *ob, FILE *fp, int flags)
393 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
394 char resBuf[160];
395 wsprintf(resBuf, "<PyHKEY at %p (%p)>",
396 ob, pyhkey->hkey);
397 fputs(resBuf, fp);
398 return 0;
401 static PyObject *
402 PyHKEY_strFunc(PyObject *ob)
404 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
405 char resBuf[160];
406 wsprintf(resBuf, "<PyHKEY:%p>", pyhkey->hkey);
407 return PyString_FromString(resBuf);
410 static int
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);
419 static long
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, const char *name);
460 /* The type itself */
461 PyTypeObject PyHKEY_Type =
463 PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */
464 "PyHKEY",
465 sizeof(PyHKEYObject),
467 PyHKEY_deallocFunc, /* tp_dealloc */
468 PyHKEY_printFunc, /* tp_print */
469 PyHKEY_getattr, /* tp_getattr */
470 0, /* tp_setattr */
471 PyHKEY_compareFunc, /* tp_compare */
472 0, /* tp_repr */
473 &PyHKEY_NumberMethods, /* tp_as_number */
474 0, /* tp_as_sequence */
475 0, /* tp_as_mapping */
476 PyHKEY_hashFunc, /* tp_hash */
477 0, /* tp_call */
478 PyHKEY_strFunc, /* tp_str */
479 0, /* tp_getattro */
480 0, /* tp_setattro */
481 0, /* tp_as_buffer */
482 0, /* tp_flags */
483 PyHKEY_doc, /* tp_doc */
486 #define OFF(e) offsetof(PyHKEYObject, e)
488 static struct memberlist PyHKEY_memberlist[] = {
489 {"handle", T_INT, OFF(hkey)},
490 {NULL} /* Sentinel */
493 /************************************************************************
495 The PyHKEY object methods
497 ************************************************************************/
498 static PyObject *
499 PyHKEY_CloseMethod(PyObject *self, PyObject *args)
501 if (!PyArg_ParseTuple(args, ":Close"))
502 return NULL;
503 if (!PyHKEY_Close(self))
504 return NULL;
505 Py_INCREF(Py_None);
506 return Py_None;
509 static PyObject *
510 PyHKEY_DetachMethod(PyObject *self, PyObject *args)
512 void* ret;
513 PyHKEYObject *pThis = (PyHKEYObject *)self;
514 if (!PyArg_ParseTuple(args, ":Detach"))
515 return NULL;
516 ret = (void*)pThis->hkey;
517 pThis->hkey = 0;
518 return PyLong_FromVoidPtr(ret);
521 static struct PyMethodDef PyHKEY_methods[] = {
522 {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc},
523 {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc},
524 {NULL}
527 /*static*/ PyObject *
528 PyHKEY_getattr(PyObject *self, const char *name)
530 PyObject *res;
532 res = Py_FindMethod(PyHKEY_methods, self, name);
533 if (res != NULL)
534 return res;
535 PyErr_Clear();
536 if (strcmp(name, "handle") == 0)
537 return PyLong_FromVoidPtr(((PyHKEYObject *)self)->hkey);
538 return PyMember_Get((char *)self, PyHKEY_memberlist, name);
541 /************************************************************************
542 The public PyHKEY API (well, not public yet :-)
543 ************************************************************************/
544 PyObject *
545 PyHKEY_New(HKEY hInit)
547 PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
548 if (key)
549 key->hkey = hInit;
550 return (PyObject *)key;
553 BOOL
554 PyHKEY_Close(PyObject *ob_handle)
556 LONG rc;
557 PyHKEYObject *key;
559 if (!PyHKEY_Check(ob_handle)) {
560 PyErr_SetString(PyExc_TypeError, "bad operand type");
561 return FALSE;
563 key = (PyHKEYObject *)ob_handle;
564 rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS;
565 key->hkey = 0;
566 if (rc != ERROR_SUCCESS)
567 PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
568 return rc == ERROR_SUCCESS;
571 BOOL
572 PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
574 if (ob == Py_None) {
575 if (!bNoneOK) {
576 PyErr_SetString(
577 PyExc_TypeError,
578 "None is not a valid HKEY in this context");
579 return FALSE;
581 *pHANDLE = (HKEY)0;
583 else if (PyHKEY_Check(ob)) {
584 PyHKEYObject *pH = (PyHKEYObject *)ob;
585 *pHANDLE = pH->hkey;
587 else if (PyInt_Check(ob) || PyLong_Check(ob)) {
588 /* We also support integers */
589 PyErr_Clear();
590 *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
591 if (PyErr_Occurred())
592 return FALSE;
594 else {
595 PyErr_SetString(
596 PyExc_TypeError,
597 "The object is not a PyHKEY object");
598 return FALSE;
600 return TRUE;
603 PyObject *
604 PyHKEY_FromHKEY(HKEY h)
606 PyHKEYObject *op;
608 /* Inline PyObject_New */
609 op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
610 if (op == NULL)
611 return PyErr_NoMemory();
612 PyObject_INIT(op, &PyHKEY_Type);
613 op->hkey = h;
614 return (PyObject *)op;
618 /************************************************************************
619 The module methods
620 ************************************************************************/
621 BOOL
622 PyWinObject_CloseHKEY(PyObject *obHandle)
624 BOOL ok;
625 if (PyHKEY_Check(obHandle)) {
626 ok = PyHKEY_Close(obHandle);
628 #if SIZEOF_LONG >= SIZEOF_HKEY
629 else if (PyInt_Check(obHandle)) {
630 long rc = RegCloseKey((HKEY)PyInt_AsLong(obHandle));
631 ok = (rc == ERROR_SUCCESS);
632 if (!ok)
633 PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
635 #else
636 else if (PyLong_Check(obHandle)) {
637 long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
638 ok = (rc == ERROR_SUCCESS);
639 if (!ok)
640 PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
642 #endif
643 else {
644 PyErr_SetString(
645 PyExc_TypeError,
646 "A handle must be a HKEY object or an integer");
647 return FALSE;
649 return ok;
654 Private Helper functions for the registry interfaces
656 ** Note that fixupMultiSZ and countString have both had changes
657 ** made to support "incorrect strings". The registry specification
658 ** calls for strings to be terminated with 2 null bytes. It seems
659 ** some commercial packages install strings which dont conform,
660 ** causing this code to fail - however, "regedit" etc still work
661 ** with these strings (ie only we dont!).
663 static void
664 fixupMultiSZ(char **str, char *data, int len)
666 char *P;
667 int i;
668 char *Q;
670 Q = data + len;
671 for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
672 str[i] = P;
673 for(; *P != '\0'; P++)
678 static int
679 countStrings(char *data, int len)
681 int strings;
682 char *P;
683 char *Q = data + len;
685 for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
686 for (; P < Q && *P != '\0'; P++)
688 return strings;
691 /* Convert PyObject into Registry data.
692 Allocates space as needed. */
693 static BOOL
694 Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
696 int i,j;
697 switch (typ) {
698 case REG_DWORD:
699 if (value != Py_None && !PyInt_Check(value))
700 return FALSE;
701 *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
702 if (*retDataBuf==NULL){
703 PyErr_NoMemory();
704 return FALSE;
706 *retDataSize = sizeof(DWORD);
707 if (value == Py_None) {
708 DWORD zero = 0;
709 memcpy(*retDataBuf, &zero, sizeof(DWORD));
711 else
712 memcpy(*retDataBuf,
713 &PyInt_AS_LONG((PyIntObject *)value),
714 sizeof(DWORD));
715 break;
716 case REG_SZ:
717 case REG_EXPAND_SZ:
719 int need_decref = 0;
720 if (value == Py_None)
721 *retDataSize = 1;
722 else {
723 if (PyUnicode_Check(value)) {
724 value = PyUnicode_AsEncodedString(
725 value,
726 "mbcs",
727 NULL);
728 if (value==NULL)
729 return FALSE;
730 need_decref = 1;
732 if (!PyString_Check(value))
733 return FALSE;
734 *retDataSize = 1 + strlen(
735 PyString_AS_STRING(
736 (PyStringObject *)value));
738 *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
739 if (*retDataBuf==NULL){
740 PyErr_NoMemory();
741 return FALSE;
743 if (value == Py_None)
744 strcpy((char *)*retDataBuf, "");
745 else
746 strcpy((char *)*retDataBuf,
747 PyString_AS_STRING(
748 (PyStringObject *)value));
749 if (need_decref)
750 Py_DECREF(value);
751 break;
753 case REG_MULTI_SZ:
755 DWORD size = 0;
756 char *P;
757 PyObject **obs = NULL;
759 if (value == Py_None)
760 i = 0;
761 else {
762 if (!PyList_Check(value))
763 return FALSE;
764 i = PyList_Size(value);
766 obs = malloc(sizeof(PyObject *) * i);
767 memset(obs, 0, sizeof(PyObject *) * i);
768 for (j = 0; j < i; j++)
770 PyObject *t;
771 t = PyList_GET_ITEM(
772 (PyListObject *)value,j);
773 if (PyString_Check(t)) {
774 obs[j] = t;
775 Py_INCREF(t);
776 } else if (PyUnicode_Check(t)) {
777 obs[j] = PyUnicode_AsEncodedString(
779 "mbcs",
780 NULL);
781 if (obs[j]==NULL)
782 goto reg_multi_fail;
783 } else
784 goto reg_multi_fail;
785 size += 1 + strlen(
786 PyString_AS_STRING(
787 (PyStringObject *)obs[j]));
790 *retDataSize = size + 1;
791 *retDataBuf = (BYTE *)PyMem_NEW(char,
792 *retDataSize);
793 if (*retDataBuf==NULL){
794 PyErr_NoMemory();
795 goto reg_multi_fail;
797 P = (char *)*retDataBuf;
799 for (j = 0; j < i; j++)
801 PyObject *t;
802 t = obs[j];
803 strcpy(P,
804 PyString_AS_STRING(
805 (PyStringObject *)t));
806 P += 1 + strlen(
807 PyString_AS_STRING(
808 (PyStringObject *)t));
809 Py_DECREF(obs[j]);
811 /* And doubly-terminate the list... */
812 *P = '\0';
813 free(obs);
814 break;
815 reg_multi_fail:
816 if (obs) {
817 for (j = 0; j < i; j++)
818 Py_XDECREF(obs[j]);
820 free(obs);
822 return FALSE;
824 case REG_BINARY:
825 /* ALSO handle ALL unknown data types here. Even if we can't
826 support it natively, we should handle the bits. */
827 default:
828 if (value == Py_None)
829 *retDataSize = 0;
830 else {
831 void *src_buf;
832 PyBufferProcs *pb = value->ob_type->tp_as_buffer;
833 if (pb==NULL) {
834 PyErr_Format(PyExc_TypeError,
835 "Objects of type '%s' can not "
836 "be used as binary registry values",
837 value->ob_type->tp_name);
838 return FALSE;
840 *retDataSize = (*pb->bf_getreadbuffer)(value, 0, &src_buf);
841 *retDataBuf = (BYTE *)PyMem_NEW(char,
842 *retDataSize);
843 if (*retDataBuf==NULL){
844 PyErr_NoMemory();
845 return FALSE;
847 memcpy(*retDataBuf, src_buf, *retDataSize);
849 break;
851 return TRUE;
854 /* Convert Registry data into PyObject*/
855 static PyObject *
856 Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ)
858 PyObject *obData;
860 switch (typ) {
861 case REG_DWORD:
862 if (retDataSize == 0)
863 obData = Py_BuildValue("i", 0);
864 else
865 obData = Py_BuildValue("i",
866 *(int *)retDataBuf);
867 break;
868 case REG_SZ:
869 case REG_EXPAND_SZ:
870 /* retDataBuf may or may not have a trailing NULL in
871 the buffer. */
872 if (retDataSize && retDataBuf[retDataSize-1] == '\0')
873 --retDataSize;
874 if (retDataSize ==0)
875 retDataBuf = "";
876 obData = PyUnicode_DecodeMBCS(retDataBuf,
877 retDataSize,
878 NULL);
879 break;
880 case REG_MULTI_SZ:
881 if (retDataSize == 0)
882 obData = PyList_New(0);
883 else
885 int index = 0;
886 int s = countStrings(retDataBuf, retDataSize);
887 char **str = (char **)malloc(sizeof(char *)*s);
888 if (str == NULL)
889 return PyErr_NoMemory();
891 fixupMultiSZ(str, retDataBuf, retDataSize);
892 obData = PyList_New(s);
893 if (obData == NULL)
894 return NULL;
895 for (index = 0; index < s; index++)
897 size_t len = _mbstrlen(str[index]);
898 if (len > INT_MAX) {
899 PyErr_SetString(PyExc_OverflowError,
900 "registry string is too long for a Python string");
901 Py_DECREF(obData);
902 return NULL;
904 PyList_SetItem(obData,
905 index,
906 PyUnicode_DecodeMBCS(
907 (const char *)str[index],
908 (int)len,
909 NULL)
912 free(str);
914 break;
916 case REG_BINARY:
917 /* ALSO handle ALL unknown data types here. Even if we can't
918 support it natively, we should handle the bits. */
919 default:
920 if (retDataSize == 0) {
921 Py_INCREF(Py_None);
922 obData = Py_None;
924 else
925 obData = Py_BuildValue("s#",
926 (char *)retDataBuf,
927 retDataSize);
928 break;
930 if (obData == NULL)
931 return NULL;
932 else
933 return obData;
936 /* The Python methods */
938 static PyObject *
939 PyCloseKey(PyObject *self, PyObject *args)
941 PyObject *obKey;
942 if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey))
943 return NULL;
944 if (!PyHKEY_Close(obKey))
945 return NULL;
946 Py_INCREF(Py_None);
947 return Py_None;
950 static PyObject *
951 PyConnectRegistry(PyObject *self, PyObject *args)
953 HKEY hKey;
954 PyObject *obKey;
955 char *szCompName = NULL;
956 HKEY retKey;
957 long rc;
958 if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey))
959 return NULL;
960 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
961 return NULL;
962 Py_BEGIN_ALLOW_THREADS
963 rc = RegConnectRegistry(szCompName, hKey, &retKey);
964 Py_END_ALLOW_THREADS
965 if (rc != ERROR_SUCCESS)
966 return PyErr_SetFromWindowsErrWithFunction(rc,
967 "ConnectRegistry");
968 return PyHKEY_FromHKEY(retKey);
971 static PyObject *
972 PyCreateKey(PyObject *self, PyObject *args)
974 HKEY hKey;
975 PyObject *obKey;
976 char *subKey;
977 HKEY retKey;
978 long rc;
979 if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey))
980 return NULL;
981 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
982 return NULL;
983 rc = RegCreateKey(hKey, subKey, &retKey);
984 if (rc != ERROR_SUCCESS)
985 return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
986 return PyHKEY_FromHKEY(retKey);
989 static PyObject *
990 PyDeleteKey(PyObject *self, PyObject *args)
992 HKEY hKey;
993 PyObject *obKey;
994 char *subKey;
995 long rc;
996 if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey))
997 return NULL;
998 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
999 return NULL;
1000 rc = RegDeleteKey(hKey, subKey );
1001 if (rc != ERROR_SUCCESS)
1002 return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
1003 Py_INCREF(Py_None);
1004 return Py_None;
1007 static PyObject *
1008 PyDeleteValue(PyObject *self, PyObject *args)
1010 HKEY hKey;
1011 PyObject *obKey;
1012 char *subKey;
1013 long rc;
1014 if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey))
1015 return NULL;
1016 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1017 return NULL;
1018 Py_BEGIN_ALLOW_THREADS
1019 rc = RegDeleteValue(hKey, subKey);
1020 Py_END_ALLOW_THREADS
1021 if (rc !=ERROR_SUCCESS)
1022 return PyErr_SetFromWindowsErrWithFunction(rc,
1023 "RegDeleteValue");
1024 Py_INCREF(Py_None);
1025 return Py_None;
1028 static PyObject *
1029 PyEnumKey(PyObject *self, PyObject *args)
1031 HKEY hKey;
1032 PyObject *obKey;
1033 int index;
1034 long rc;
1035 PyObject *retStr;
1036 char tmpbuf[256]; /* max key name length is 255 */
1037 DWORD len = sizeof(tmpbuf); /* includes NULL terminator */
1039 if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index))
1040 return NULL;
1041 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1042 return NULL;
1044 Py_BEGIN_ALLOW_THREADS
1045 rc = RegEnumKeyEx(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL);
1046 Py_END_ALLOW_THREADS
1047 if (rc != ERROR_SUCCESS)
1048 return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx");
1050 retStr = PyString_FromStringAndSize(tmpbuf, len);
1051 return retStr; /* can be NULL */
1054 static PyObject *
1055 PyEnumValue(PyObject *self, PyObject *args)
1057 HKEY hKey;
1058 PyObject *obKey;
1059 int index;
1060 long rc;
1061 char *retValueBuf;
1062 char *retDataBuf;
1063 DWORD retValueSize;
1064 DWORD retDataSize;
1065 DWORD typ;
1066 PyObject *obData;
1067 PyObject *retVal;
1069 if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index))
1070 return NULL;
1071 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1072 return NULL;
1074 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
1075 NULL,
1076 &retValueSize, &retDataSize, NULL, NULL))
1077 != ERROR_SUCCESS)
1078 return PyErr_SetFromWindowsErrWithFunction(rc,
1079 "RegQueryInfoKey");
1080 ++retValueSize; /* include null terminators */
1081 ++retDataSize;
1082 retValueBuf = (char *)PyMem_Malloc(retValueSize);
1083 if (retValueBuf == NULL)
1084 return PyErr_NoMemory();
1085 retDataBuf = (char *)PyMem_Malloc(retDataSize);
1086 if (retDataBuf == NULL) {
1087 PyMem_Free(retValueBuf);
1088 return PyErr_NoMemory();
1091 Py_BEGIN_ALLOW_THREADS
1092 rc = RegEnumValue(hKey,
1093 index,
1094 retValueBuf,
1095 &retValueSize,
1096 NULL,
1097 &typ,
1098 (BYTE *)retDataBuf,
1099 &retDataSize);
1100 Py_END_ALLOW_THREADS
1102 if (rc != ERROR_SUCCESS) {
1103 retVal = PyErr_SetFromWindowsErrWithFunction(rc,
1104 "PyRegEnumValue");
1105 goto fail;
1107 obData = Reg2Py(retDataBuf, retDataSize, typ);
1108 if (obData == NULL) {
1109 retVal = NULL;
1110 goto fail;
1112 retVal = Py_BuildValue("sOi", retValueBuf, obData, typ);
1113 Py_DECREF(obData);
1114 fail:
1115 PyMem_Free(retValueBuf);
1116 PyMem_Free(retDataBuf);
1117 return retVal;
1120 static PyObject *
1121 PyFlushKey(PyObject *self, PyObject *args)
1123 HKEY hKey;
1124 PyObject *obKey;
1125 long rc;
1126 if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey))
1127 return NULL;
1128 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1129 return NULL;
1130 Py_BEGIN_ALLOW_THREADS
1131 rc = RegFlushKey(hKey);
1132 Py_END_ALLOW_THREADS
1133 if (rc != ERROR_SUCCESS)
1134 return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
1135 Py_INCREF(Py_None);
1136 return Py_None;
1138 static PyObject *
1139 PyLoadKey(PyObject *self, PyObject *args)
1141 HKEY hKey;
1142 PyObject *obKey;
1143 char *subKey;
1144 char *fileName;
1146 long rc;
1147 if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName))
1148 return NULL;
1149 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1150 return NULL;
1151 Py_BEGIN_ALLOW_THREADS
1152 rc = RegLoadKey(hKey, subKey, fileName );
1153 Py_END_ALLOW_THREADS
1154 if (rc != ERROR_SUCCESS)
1155 return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
1156 Py_INCREF(Py_None);
1157 return Py_None;
1160 static PyObject *
1161 PyOpenKey(PyObject *self, PyObject *args)
1163 HKEY hKey;
1164 PyObject *obKey;
1166 char *subKey;
1167 int res = 0;
1168 HKEY retKey;
1169 long rc;
1170 REGSAM sam = KEY_READ;
1171 if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey,
1172 &res, &sam))
1173 return NULL;
1174 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1175 return NULL;
1177 Py_BEGIN_ALLOW_THREADS
1178 rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey);
1179 Py_END_ALLOW_THREADS
1180 if (rc != ERROR_SUCCESS)
1181 return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
1182 return PyHKEY_FromHKEY(retKey);
1186 static PyObject *
1187 PyQueryInfoKey(PyObject *self, PyObject *args)
1189 HKEY hKey;
1190 PyObject *obKey;
1191 long rc;
1192 DWORD nSubKeys, nValues;
1193 FILETIME ft;
1194 LARGE_INTEGER li;
1195 PyObject *l;
1196 PyObject *ret;
1197 if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey))
1198 return NULL;
1199 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1200 return NULL;
1201 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL,
1202 &nValues, NULL, NULL, NULL, &ft))
1203 != ERROR_SUCCESS)
1204 return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
1205 li.LowPart = ft.dwLowDateTime;
1206 li.HighPart = ft.dwHighDateTime;
1207 l = PyLong_FromLongLong(li.QuadPart);
1208 if (l == NULL)
1209 return NULL;
1210 ret = Py_BuildValue("iiO", nSubKeys, nValues, l);
1211 Py_DECREF(l);
1212 return ret;
1215 static PyObject *
1216 PyQueryValue(PyObject *self, PyObject *args)
1218 HKEY hKey;
1219 PyObject *obKey;
1220 char *subKey;
1221 long rc;
1222 PyObject *retStr;
1223 char *retBuf;
1224 long bufSize = 0;
1226 if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey))
1227 return NULL;
1229 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1230 return NULL;
1231 if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize))
1232 != ERROR_SUCCESS)
1233 return PyErr_SetFromWindowsErrWithFunction(rc,
1234 "RegQueryValue");
1235 retStr = PyString_FromStringAndSize(NULL, bufSize);
1236 if (retStr == NULL)
1237 return NULL;
1238 retBuf = PyString_AS_STRING(retStr);
1239 if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize))
1240 != ERROR_SUCCESS) {
1241 Py_DECREF(retStr);
1242 return PyErr_SetFromWindowsErrWithFunction(rc,
1243 "RegQueryValue");
1245 _PyString_Resize(&retStr, strlen(retBuf));
1246 return retStr;
1249 static PyObject *
1250 PyQueryValueEx(PyObject *self, PyObject *args)
1252 HKEY hKey;
1253 PyObject *obKey;
1254 char *valueName;
1256 long rc;
1257 char *retBuf;
1258 DWORD bufSize = 0;
1259 DWORD typ;
1260 PyObject *obData;
1261 PyObject *result;
1263 if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName))
1264 return NULL;
1266 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1267 return NULL;
1268 if ((rc = RegQueryValueEx(hKey, valueName,
1269 NULL, NULL, NULL,
1270 &bufSize))
1271 != ERROR_SUCCESS)
1272 return PyErr_SetFromWindowsErrWithFunction(rc,
1273 "RegQueryValueEx");
1274 retBuf = (char *)PyMem_Malloc(bufSize);
1275 if (retBuf == NULL)
1276 return PyErr_NoMemory();
1277 if ((rc = RegQueryValueEx(hKey, valueName, NULL,
1278 &typ, (BYTE *)retBuf, &bufSize))
1279 != ERROR_SUCCESS) {
1280 PyMem_Free(retBuf);
1281 return PyErr_SetFromWindowsErrWithFunction(rc,
1282 "RegQueryValueEx");
1284 obData = Reg2Py(retBuf, bufSize, typ);
1285 PyMem_Free((void *)retBuf);
1286 if (obData == NULL)
1287 return NULL;
1288 result = Py_BuildValue("Oi", obData, typ);
1289 Py_DECREF(obData);
1290 return result;
1294 static PyObject *
1295 PySaveKey(PyObject *self, PyObject *args)
1297 HKEY hKey;
1298 PyObject *obKey;
1299 char *fileName;
1300 LPSECURITY_ATTRIBUTES pSA = NULL;
1302 long rc;
1303 if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName))
1304 return NULL;
1305 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1306 return NULL;
1307 /* One day we may get security into the core?
1308 if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
1309 return NULL;
1311 Py_BEGIN_ALLOW_THREADS
1312 rc = RegSaveKey(hKey, fileName, pSA );
1313 Py_END_ALLOW_THREADS
1314 if (rc != ERROR_SUCCESS)
1315 return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
1316 Py_INCREF(Py_None);
1317 return Py_None;
1320 static PyObject *
1321 PySetValue(PyObject *self, PyObject *args)
1323 HKEY hKey;
1324 PyObject *obKey;
1325 char *subKey;
1326 char *str;
1327 DWORD typ;
1328 DWORD len;
1329 long rc;
1330 PyObject *obStrVal;
1331 PyObject *obSubKey;
1332 if (!PyArg_ParseTuple(args, "OOiO:SetValue",
1333 &obKey,
1334 &obSubKey,
1335 &typ,
1336 &obStrVal))
1337 return NULL;
1338 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1339 return NULL;
1340 if (typ != REG_SZ) {
1341 PyErr_SetString(PyExc_TypeError,
1342 "Type must be _winreg.REG_SZ");
1343 return NULL;
1345 /* XXX - need Unicode support */
1346 str = PyString_AsString(obStrVal);
1347 if (str == NULL)
1348 return NULL;
1349 len = PyString_Size(obStrVal);
1350 if (obSubKey == Py_None)
1351 subKey = NULL;
1352 else {
1353 subKey = PyString_AsString(obSubKey);
1354 if (subKey == NULL)
1355 return NULL;
1357 Py_BEGIN_ALLOW_THREADS
1358 rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1);
1359 Py_END_ALLOW_THREADS
1360 if (rc != ERROR_SUCCESS)
1361 return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue");
1362 Py_INCREF(Py_None);
1363 return Py_None;
1366 static PyObject *
1367 PySetValueEx(PyObject *self, PyObject *args)
1369 HKEY hKey;
1370 PyObject *obKey;
1371 char *valueName;
1372 PyObject *obRes;
1373 PyObject *value;
1374 BYTE *data;
1375 DWORD len;
1376 DWORD typ;
1378 LONG rc;
1380 if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx",
1381 &obKey,
1382 &valueName,
1383 &obRes,
1384 &typ,
1385 &value))
1386 return NULL;
1387 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1388 return NULL;
1389 if (!Py2Reg(value, typ, &data, &len))
1391 if (!PyErr_Occurred())
1392 PyErr_SetString(PyExc_ValueError,
1393 "Could not convert the data to the specified type.");
1394 return NULL;
1396 Py_BEGIN_ALLOW_THREADS
1397 rc = RegSetValueEx(hKey, valueName, 0, typ, data, len);
1398 Py_END_ALLOW_THREADS
1399 PyMem_DEL(data);
1400 if (rc != ERROR_SUCCESS)
1401 return PyErr_SetFromWindowsErrWithFunction(rc,
1402 "RegSetValueEx");
1403 Py_INCREF(Py_None);
1404 return Py_None;
1407 static struct PyMethodDef winreg_methods[] = {
1408 {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc},
1409 {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc},
1410 {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc},
1411 {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc},
1412 {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc},
1413 {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc},
1414 {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc},
1415 {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc},
1416 {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc},
1417 {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc},
1418 {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc},
1419 {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc},
1420 {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc},
1421 {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc},
1422 {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc},
1423 {"SetValue", PySetValue, METH_VARARGS, SetValue_doc},
1424 {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc},
1425 NULL,
1428 static void
1429 insint(PyObject * d, char * name, long value)
1431 PyObject *v = PyInt_FromLong(value);
1432 if (!v || PyDict_SetItemString(d, name, v))
1433 PyErr_Clear();
1434 Py_XDECREF(v);
1437 #define ADD_INT(val) insint(d, #val, val)
1439 static void
1440 inskey(PyObject * d, char * name, HKEY key)
1442 PyObject *v = PyLong_FromVoidPtr(key);
1443 if (!v || PyDict_SetItemString(d, name, v))
1444 PyErr_Clear();
1445 Py_XDECREF(v);
1448 #define ADD_KEY(val) inskey(d, #val, val)
1450 PyMODINIT_FUNC init_winreg(void)
1452 PyObject *m, *d;
1453 m = Py_InitModule3("_winreg", winreg_methods, module_doc);
1454 if (m == NULL)
1455 return;
1456 d = PyModule_GetDict(m);
1457 PyHKEY_Type.ob_type = &PyType_Type;
1458 PyHKEY_Type.tp_doc = PyHKEY_doc;
1459 Py_INCREF(&PyHKEY_Type);
1460 if (PyDict_SetItemString(d, "HKEYType",
1461 (PyObject *)&PyHKEY_Type) != 0)
1462 return;
1463 Py_INCREF(PyExc_WindowsError);
1464 if (PyDict_SetItemString(d, "error",
1465 PyExc_WindowsError) != 0)
1466 return;
1468 /* Add the relevant constants */
1469 ADD_KEY(HKEY_CLASSES_ROOT);
1470 ADD_KEY(HKEY_CURRENT_USER);
1471 ADD_KEY(HKEY_LOCAL_MACHINE);
1472 ADD_KEY(HKEY_USERS);
1473 ADD_KEY(HKEY_PERFORMANCE_DATA);
1474 #ifdef HKEY_CURRENT_CONFIG
1475 ADD_KEY(HKEY_CURRENT_CONFIG);
1476 #endif
1477 #ifdef HKEY_DYN_DATA
1478 ADD_KEY(HKEY_DYN_DATA);
1479 #endif
1480 ADD_INT(KEY_QUERY_VALUE);
1481 ADD_INT(KEY_SET_VALUE);
1482 ADD_INT(KEY_CREATE_SUB_KEY);
1483 ADD_INT(KEY_ENUMERATE_SUB_KEYS);
1484 ADD_INT(KEY_NOTIFY);
1485 ADD_INT(KEY_CREATE_LINK);
1486 ADD_INT(KEY_READ);
1487 ADD_INT(KEY_WRITE);
1488 ADD_INT(KEY_EXECUTE);
1489 ADD_INT(KEY_ALL_ACCESS);
1490 ADD_INT(REG_OPTION_RESERVED);
1491 ADD_INT(REG_OPTION_NON_VOLATILE);
1492 ADD_INT(REG_OPTION_VOLATILE);
1493 ADD_INT(REG_OPTION_CREATE_LINK);
1494 ADD_INT(REG_OPTION_BACKUP_RESTORE);
1495 ADD_INT(REG_OPTION_OPEN_LINK);
1496 ADD_INT(REG_LEGAL_OPTION);
1497 ADD_INT(REG_CREATED_NEW_KEY);
1498 ADD_INT(REG_OPENED_EXISTING_KEY);
1499 ADD_INT(REG_WHOLE_HIVE_VOLATILE);
1500 ADD_INT(REG_REFRESH_HIVE);
1501 ADD_INT(REG_NO_LAZY_FLUSH);
1502 ADD_INT(REG_NOTIFY_CHANGE_NAME);
1503 ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
1504 ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
1505 ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
1506 ADD_INT(REG_LEGAL_CHANGE_FILTER);
1507 ADD_INT(REG_NONE);
1508 ADD_INT(REG_SZ);
1509 ADD_INT(REG_EXPAND_SZ);
1510 ADD_INT(REG_BINARY);
1511 ADD_INT(REG_DWORD);
1512 ADD_INT(REG_DWORD_LITTLE_ENDIAN);
1513 ADD_INT(REG_DWORD_BIG_ENDIAN);
1514 ADD_INT(REG_LINK);
1515 ADD_INT(REG_MULTI_SZ);
1516 ADD_INT(REG_RESOURCE_LIST);
1517 ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
1518 ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);