blob: bba9bc29835ec21c9d61cab8d40c9d7bf6948655 [file] [log] [blame]
Guido van Rossum9f3712c2000-03-28 20:37:15 +00001/*
2 winreg.c
3
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"
91"If the function fails, an exception is raised.";
92
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"
116"is removed. If the method fails, and exception is raised.";
117
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"
131"It is typically called repeatedly until an exception is raised, indicating\n"
132"no more values are available.\n";
133
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"
140"It is typically called repeatedly, until an exception is raised,\n"
141"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.";
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[] =
163"RegLoadKey(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";
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"
191"If the function fails, an exception is raised.\n";
192
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"
211"sub_key is a string that holds The name of the subkey with which the value\n"
212" 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"
271" REG_MULTI_SZ -- An array of null-terminated strings, terminated by\n"
272" two null characters.\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.\n";
288
289/* PyHKEY docstrings */
290static char PyHKEY_doc[] =
291"PyHKEY Object - A Python object, representing a win32 registry key.\n"
292"\n"
293"This object wraps a win32 HANDLE 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.\n";
311
312
313static char PyHKEY_Close_doc[] =
314"key.Close() - Closes the underlying Win32 handle.\n"
315"\n"
316"If the handle is already closed, no error is raised.";
317
318static char PyHKEY_Detach_doc[] =
319"int = key.Detach() - Detaches the Win32 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.";
328
329
330/************************************************************************
331
332 The PyHKEY object definition
333
334************************************************************************/
335typedef struct {
336 PyObject_VAR_HEAD
337 HKEY hkey;
338} PyHKEYObject;
339
340#define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
341
342static char *failMsg = "bad operand type";
343
344static PyObject *
345PyHKEY_unaryFailureFunc(PyObject *ob)
346{
347 PyErr_SetString(PyExc_TypeError, failMsg);
348 return NULL;
349}
350static PyObject *
351PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
352{
353 PyErr_SetString(PyExc_TypeError, failMsg);
354 return NULL;
355}
356static PyObject *
357PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
358{
359 PyErr_SetString(PyExc_TypeError, failMsg);
360 return NULL;
361}
362
363static void
364PyHKEY_deallocFunc(PyObject *ob)
365{
366 /* Can not call PyHKEY_Close, as the ob->tp_type
367 has already been cleared, thus causing the type
368 check to fail!
369 */
370 PyHKEYObject *obkey = (PyHKEYObject *)ob;
371 if (obkey->hkey)
372 RegCloseKey((HKEY)obkey->hkey);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000373 PyObject_DEL(ob);
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000374}
375
376static int
377PyHKEY_nonzeroFunc(PyObject *ob)
378{
379 return ((PyHKEYObject *)ob)->hkey != 0;
380}
381
382static PyObject *
383PyHKEY_intFunc(PyObject *ob)
384{
385 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
386 return PyLong_FromVoidPtr(pyhkey->hkey);
387}
388
389static int
390PyHKEY_printFunc(PyObject *ob, FILE *fp, int flags)
391{
392 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
393 char resBuf[160];
394 wsprintf(resBuf, "<PyHKEY at %p (%p)>",
395 ob, pyhkey->hkey);
396 fputs(resBuf, fp);
397 return 0;
398}
399
400static PyObject *
401PyHKEY_strFunc(PyObject *ob)
402{
403 PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
404 char resBuf[160];
405 wsprintf(resBuf, "<PyHKEY:%p>", pyhkey->hkey);
406 return PyString_FromString(resBuf);
407}
408
409static int
410PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
411{
412 PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
413 PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
414 return pyhkey1 == pyhkey2 ? 0 :
415 (pyhkey1 < pyhkey2 ? -1 : 1);
416}
417
418static long
419PyHKEY_hashFunc(PyObject *ob)
420{
421 /* Just use the address.
422 XXX - should we use the handle value?
423 */
424 return (long)ob;
425}
426
427
428static PyNumberMethods PyHKEY_NumberMethods =
429{
430 PyHKEY_binaryFailureFunc, /* nb_add */
431 PyHKEY_binaryFailureFunc, /* nb_subtract */
432 PyHKEY_binaryFailureFunc, /* nb_multiply */
433 PyHKEY_binaryFailureFunc, /* nb_divide */
434 PyHKEY_binaryFailureFunc, /* nb_remainder */
435 PyHKEY_binaryFailureFunc, /* nb_divmod */
436 PyHKEY_ternaryFailureFunc, /* nb_power */
437 PyHKEY_unaryFailureFunc, /* nb_negative */
438 PyHKEY_unaryFailureFunc, /* nb_positive */
439 PyHKEY_unaryFailureFunc, /* nb_absolute */
440 PyHKEY_nonzeroFunc, /* nb_nonzero */
441 PyHKEY_unaryFailureFunc, /* nb_invert */
442 PyHKEY_binaryFailureFunc, /* nb_lshift */
443 PyHKEY_binaryFailureFunc, /* nb_rshift */
444 PyHKEY_binaryFailureFunc, /* nb_and */
445 PyHKEY_binaryFailureFunc, /* nb_xor */
446 PyHKEY_binaryFailureFunc, /* nb_or */
447 0, /* nb_coerce (allowed to be zero) */
448 PyHKEY_intFunc, /* nb_int */
449 PyHKEY_unaryFailureFunc, /* nb_long */
450 PyHKEY_unaryFailureFunc, /* nb_float */
451 PyHKEY_unaryFailureFunc, /* nb_oct */
452 PyHKEY_unaryFailureFunc, /* nb_hex */
453};
454
455
456/* fwd declare __getattr__ */
457static PyObject *PyHKEY_getattr(PyObject *self, char *name);
458
459/* The type itself */
460PyTypeObject PyHKEY_Type =
461{
462 PyObject_HEAD_INIT(0) /* fill in type at module init */
463 0,
464 "PyHKEY",
465 sizeof(PyHKEYObject),
466 0,
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 */
484};
485
486#define OFF(e) offsetof(PyHKEYObject, e)
487
488static struct memberlist PyHKEY_memberlist[] = {
489 {"handle", T_INT, OFF(hkey)},
490 {NULL} /* Sentinel */
491};
492
493/************************************************************************
494
495 The PyHKEY object methods
496
497************************************************************************/
498static PyObject *
499PyHKEY_CloseMethod(PyObject *self, PyObject *args)
500{
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;
507}
508
509static PyObject *
510PyHKEY_DetachMethod(PyObject *self, PyObject *args)
511{
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);
519}
520
521static struct PyMethodDef PyHKEY_methods[] = {
522 {"Close", PyHKEY_CloseMethod, 1, PyHKEY_Close_doc},
523 {"Detach", PyHKEY_DetachMethod, 1, PyHKEY_Detach_doc},
524 {NULL}
525};
526
527/*static*/ PyObject *
528PyHKEY_getattr(PyObject *self, char *name)
529{
530 PyObject *res;
531
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);
539}
540
541/************************************************************************
542 The public PyHKEY API (well, not public yet :-)
543************************************************************************/
544PyObject *
545PyHKEY_New(HKEY hInit)
546{
547 PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
548 if (key)
549 key->hkey = hInit;
550 return (PyObject *)key;
551}
552
553BOOL
554PyHKEY_Close(PyObject *ob_handle)
555{
556 LONG rc;
557 PyHKEYObject *key;
558
559 if (!PyHKEY_Check(ob_handle)) {
560 PyErr_SetString(PyExc_TypeError, "bad operand type");
561 return FALSE;
562 }
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;
569}
570
571BOOL
572PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
573{
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;
580 }
581 *pHANDLE = (HKEY)0;
582 }
583 else if (PyHKEY_Check(ob)) {
584 PyHKEYObject *pH = (PyHKEYObject *)ob;
585 *pHANDLE = pH->hkey;
586 }
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;
593 *pHANDLE = (HKEY)PyInt_AsLong(ob);
594 }
595 else {
596 PyErr_SetString(
597 PyExc_TypeError,
598 "The object is not a PyHKEY object");
599 return FALSE;
600 }
601 return TRUE;
602}
603
604PyObject *
605PyHKEY_FromHKEY(HKEY h)
606{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000607 PyHKEYObject *op;
608
609 /* PyObject_New is inlined */
610 op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000611 if (op == NULL)
612 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000613 PyObject_INIT(op, &PyHKEY_Type);
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000614 op->hkey = h;
Guido van Rossum9f3712c2000-03-28 20:37:15 +0000615 return (PyObject *)op;
616}
617
618
619/************************************************************************
620 The module methods
621************************************************************************/
622BOOL
623PyWinObject_CloseHKEY(PyObject *obHandle)
624{
625 BOOL ok;
626 if (PyHKEY_Check(obHandle)) {
627 ok = PyHKEY_Close(obHandle);
628 }
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");
634 }
635 else {
636 PyErr_SetString(
637 PyExc_TypeError,
638 "A handle must be a HKEY object or an integer");
639 return FALSE;
640 }
641 return ok;
642}
643
644
645/*
646 Private Helper functions for the registry interfaces
647
648** Note that fixupMultiSZ and countString have both had changes
649** made to support "incorrect strings". The registry specification
650** calls for strings to be terminated with 2 null bytes. It seems
651** some commercial packages install strings whcich dont conform,
652** causing this code to fail - however, "regedit" etc still work
653** with these strings (ie only we dont!).
654*/
655static void
656fixupMultiSZ(char **str, char *data, int len)
657{
658 char *P;
659 int i;
660 char *Q;
661
662 Q = data + len;
663 for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
664 str[i] = P;
665 for(; *P != '\0'; P++)
666 ;
667 }
668}
669
670static int
671countStrings(char *data, int len)
672{
673 int strings;
674 char *P;
675 char *Q = data + len;
676
677 for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
678 for (; P < Q && *P != '\0'; P++)
679 ;
680 return strings;
681}
682
683/* Convert PyObject into Registry data.
684 Allocates space as needed. */
685static BOOL
686Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
687{
688 int i,j;
689 switch (typ) {
690 case REG_DWORD:
691 if (value != Py_None && !PyInt_Check(value))
692 return FALSE;
693 *retDataBuf = (BYTE *)PyMem_NEW(DWORD, sizeof(DWORD));
694 if (*retDataBuf==NULL){
695 PyErr_NoMemory();
696 return FALSE;
697 }
698 *retDataSize = sizeof(DWORD);
699 if (value == Py_None) {
700 DWORD zero = 0;
701 memcpy(*retDataBuf, &zero, sizeof(DWORD));
702 }
703 else
704 memcpy(*retDataBuf,
705 &PyInt_AS_LONG((PyIntObject *)value),
706 sizeof(DWORD));
707 break;
708 case REG_SZ:
709 case REG_EXPAND_SZ:
710 {
711 int need_decref = 0;
712 if (value == Py_None)
713 *retDataSize = 1;
714 else {
715 if (PyUnicode_Check(value)) {
716 value = PyUnicode_AsEncodedString(
717 value,
718 "mbcs",
719 NULL);
720 if (value==NULL)
721 return FALSE;
722 need_decref = 1;
723 }
724 if (!PyString_Check(value))
725 return FALSE;
726 *retDataSize = 1 + strlen(
727 PyString_AS_STRING(
728 (PyStringObject *)value));
729 }
730 *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
731 if (*retDataBuf==NULL){
732 PyErr_NoMemory();
733 return FALSE;
734 }
735 if (value == Py_None)
736 strcpy((char *)*retDataBuf, "");
737 else
738 strcpy((char *)*retDataBuf,
739 PyString_AS_STRING(
740 (PyStringObject *)value));
741 if (need_decref)
742 Py_DECREF(value);
743 break;
744 }
745 case REG_MULTI_SZ:
746 {
747 DWORD size = 0;
748 char *P;
749 PyObject **obs = NULL;
750
751 if (value == Py_None)
752 i = 0;
753 else {
754 if (!PyList_Check(value))
755 return FALSE;
756 i = PyList_Size(value);
757 }
758 obs = malloc(sizeof(PyObject *) * i);
759 memset(obs, 0, sizeof(PyObject *) * i);
760 for (j = 0; j < i; j++)
761 {
762 PyObject *t;
763 t = PyList_GET_ITEM(
764 (PyListObject *)value,j);
765 if (PyString_Check(t)) {
766 obs[j] = t;
767 Py_INCREF(t);
768 } else if (PyUnicode_Check(t)) {
769 obs[j] = PyUnicode_AsEncodedString(
770 t,
771 "mbcs",
772 NULL);
773 if (obs[j]==NULL)
774 goto reg_multi_fail;
775 } else
776 goto reg_multi_fail;
777 size += 1 + strlen(
778 PyString_AS_STRING(
779 (PyStringObject *)obs[j]));
780 }
781
782 *retDataSize = size + 1;
783 *retDataBuf = (BYTE *)PyMem_NEW(char,
784 *retDataSize);
785 if (*retDataBuf==NULL){
786 PyErr_NoMemory();
787 goto reg_multi_fail;
788 }
789 P = (char *)*retDataBuf;
790
791 for (j = 0; j < i; j++)
792 {
793 PyObject *t;
794 t = obs[j];
795 strcpy(P,
796 PyString_AS_STRING(
797 (PyStringObject *)t));
798 P += 1 + strlen(
799 PyString_AS_STRING(
800 (PyStringObject *)t));
801 Py_DECREF(obs[j]);
802 }
803 /* And doubly-terminate the list... */
804 *P = '\0';
805 free(obs);
806 break;
807 reg_multi_fail:
808 if (obs) {
809 for (j = 0; j < i; j++)
810 Py_XDECREF(obs[j]);
811
812 free(obs);
813 }
814 return FALSE;
815 }
816 case REG_BINARY:
817 /* ALSO handle ALL unknown data types here. Even if we can't
818 support it natively, we should handle the bits. */
819 default:
820 if (value == Py_None)
821 *retDataSize = 0;
822 else {
823 if (!PyString_Check(value))
824 return 0;
825 *retDataSize = PyString_Size(value);
826 *retDataBuf = (BYTE *)PyMem_NEW(char,
827 *retDataSize);
828 if (*retDataBuf==NULL){
829 PyErr_NoMemory();
830 return FALSE;
831 }
832 memcpy(*retDataBuf,
833 PyString_AS_STRING(
834 (PyStringObject *)value),
835 *retDataSize);
836 }
837 break;
838 }
839 return TRUE;
840}
841
842/* Convert Registry data into PyObject*/
843static PyObject *
844Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ)
845{
846 PyObject *obData;
847
848 switch (typ) {
849 case REG_DWORD:
850 if (retDataSize == 0)
851 obData = Py_BuildValue("i", 0);
852 else
853 obData = Py_BuildValue("i",
854 *(int *)retDataBuf);
855 break;
856 case REG_SZ:
857 case REG_EXPAND_SZ:
858 /* retDataBuf may or may not have a trailing NULL in
859 the buffer. */
860 if (retDataSize && retDataBuf[retDataSize-1] == '\0')
861 --retDataSize;
862 if (retDataSize ==0)
863 retDataBuf = "";
864 obData = PyUnicode_DecodeMBCS(retDataBuf,
865 retDataSize,
866 NULL);
867 break;
868 case REG_MULTI_SZ:
869 if (retDataSize == 0)
870 obData = PyList_New(0);
871 else
872 {
873 int index = 0;
874 int s = countStrings(retDataBuf, retDataSize);
875 char **str = (char **)malloc(sizeof(char *)*s);
876 if (str == NULL)
877 return PyErr_NoMemory();
878
879 fixupMultiSZ(str, retDataBuf, retDataSize);
880 obData = PyList_New(s);
881 for (index = 0; index < s; index++)
882 {
883 PyList_SetItem(obData,
884 index,
885 PyUnicode_DecodeMBCS(
886 (const char *)str[index],
887 _mbstrlen(str[index]),
888 NULL)
889 );
890 }
891 free(str);
892
893 break;
894 }
895 case REG_BINARY:
896 /* ALSO handle ALL unknown data types here. Even if we can't
897 support it natively, we should handle the bits. */
898 default:
899 if (retDataSize == 0) {
900 Py_INCREF(Py_None);
901 obData = Py_None;
902 }
903 else
904 obData = Py_BuildValue("s#",
905 (char *)retDataBuf,
906 retDataSize);
907 break;
908 }
909 if (obData == NULL)
910 return NULL;
911 else
912 return obData;
913}
914
915/* The Python methods */
916
917static PyObject *
918PyCloseKey(PyObject *self, PyObject *args)
919{
920 PyObject *obKey;
921 if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey))
922 return NULL;
923 if (!PyHKEY_Close(obKey))
924 return NULL;
925 Py_INCREF(Py_None);
926 return Py_None;
927}
928
929static PyObject *
930PyConnectRegistry(PyObject *self, PyObject *args)
931{
932 HKEY hKey;
933 PyObject *obKey;
934 char *szCompName = NULL;
935 HKEY retKey;
936 long rc;
937 if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey))
938 return NULL;
939 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
940 return NULL;
941 rc = RegConnectRegistry(szCompName, hKey, &retKey);
942 if (rc != ERROR_SUCCESS)
943 return PyErr_SetFromWindowsErrWithFunction(rc,
944 "ConnectRegistry");
945 return PyHKEY_FromHKEY(retKey);
946}
947
948static PyObject *
949PyCreateKey(PyObject *self, PyObject *args)
950{
951 HKEY hKey;
952 PyObject *obKey;
953 char *subKey;
954 HKEY retKey;
955 long rc;
956 if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey))
957 return NULL;
958 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
959 return NULL;
960 rc = RegCreateKey(hKey, subKey, &retKey);
961 if (rc != ERROR_SUCCESS)
962 return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
963 return PyHKEY_FromHKEY(retKey);
964}
965
966static PyObject *
967PyDeleteKey(PyObject *self, PyObject *args)
968{
969 HKEY hKey;
970 PyObject *obKey;
971 char *subKey;
972 long rc;
973 if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey))
974 return NULL;
975 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
976 return NULL;
977 rc = RegDeleteKey(hKey, subKey );
978 if (rc != ERROR_SUCCESS)
979 return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
980 Py_INCREF(Py_None);
981 return Py_None;
982}
983
984static PyObject *
985PyDeleteValue(PyObject *self, PyObject *args)
986{
987 HKEY hKey;
988 PyObject *obKey;
989 char *subKey;
990 long rc;
991 if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey))
992 return NULL;
993 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
994 return NULL;
995 Py_BEGIN_ALLOW_THREADS
996 rc = RegDeleteValue(hKey, subKey);
997 Py_END_ALLOW_THREADS
998 if (rc !=ERROR_SUCCESS)
999 return PyErr_SetFromWindowsErrWithFunction(rc,
1000 "RegDeleteValue");
1001 Py_INCREF(Py_None);
1002 return Py_None;
1003}
1004
1005static PyObject *
1006PyEnumKey(PyObject *self, PyObject *args)
1007{
1008 HKEY hKey;
1009 PyObject *obKey;
1010 int index;
1011 long rc;
1012 char *retBuf;
1013 DWORD len;
1014
1015 if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index))
1016 return NULL;
1017 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1018 return NULL;
1019
1020 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, &len,
1021 NULL, NULL, NULL, NULL, NULL, NULL))
1022 != ERROR_SUCCESS)
1023 return PyErr_SetFromWindowsErrWithFunction(rc,
1024 "RegQueryInfoKey");
1025 ++len; /* include null terminator */
1026 retBuf = (char *)alloca(len);
1027
1028 if ((rc = RegEnumKey(hKey, index, retBuf, len)) != ERROR_SUCCESS)
1029 return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKey");
1030 return Py_BuildValue("s", retBuf);
1031}
1032
1033static PyObject *
1034PyEnumValue(PyObject *self, PyObject *args)
1035{
1036 HKEY hKey;
1037 PyObject *obKey;
1038 int index;
1039 long rc;
1040 char *retValueBuf;
1041 char *retDataBuf;
1042 DWORD retValueSize;
1043 DWORD retDataSize;
1044 DWORD typ;
1045 PyObject *obData;
1046 PyObject *retVal;
1047
1048 if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index))
1049 return NULL;
1050 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1051 return NULL;
1052
1053 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
1054 NULL,
1055 &retValueSize, &retDataSize, NULL, NULL))
1056 != ERROR_SUCCESS)
1057 return PyErr_SetFromWindowsErrWithFunction(rc,
1058 "RegQueryInfoKey");
1059 ++retValueSize; /* include null terminators */
1060 ++retDataSize;
1061 retValueBuf = (char *)alloca(retValueSize);
1062 retDataBuf = (char *)alloca(retDataSize);
1063
1064 Py_BEGIN_ALLOW_THREADS
1065 rc = RegEnumValue(hKey,
1066 index,
1067 retValueBuf,
1068 &retValueSize,
1069 NULL,
1070 &typ,
1071 (BYTE *)retDataBuf,
1072 &retDataSize);
1073 Py_END_ALLOW_THREADS
1074
1075 if (rc != ERROR_SUCCESS)
1076 return PyErr_SetFromWindowsErrWithFunction(rc,
1077 "PyRegEnumValue");
1078 obData = Reg2Py(retDataBuf, retDataSize, typ);
1079 if (obData == NULL)
1080 return NULL;
1081 retVal = Py_BuildValue("sOi", retValueBuf, obData, typ);
1082 Py_DECREF(obData);
1083 return retVal;
1084}
1085
1086static PyObject *
1087PyFlushKey(PyObject *self, PyObject *args)
1088{
1089 HKEY hKey;
1090 PyObject *obKey;
1091 long rc;
1092 if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey))
1093 return NULL;
1094 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1095 return NULL;
1096 Py_BEGIN_ALLOW_THREADS
1097 rc = RegFlushKey(hKey);
1098 Py_END_ALLOW_THREADS
1099 if (rc != ERROR_SUCCESS)
1100 return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
1101 Py_INCREF(Py_None);
1102 return Py_None;
1103}
1104static PyObject *
1105PyLoadKey(PyObject *self, PyObject *args)
1106{
1107 HKEY hKey;
1108 PyObject *obKey;
1109 char *subKey;
1110 char *fileName;
1111
1112 long rc;
1113 if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName))
1114 return NULL;
1115 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1116 return NULL;
1117 Py_BEGIN_ALLOW_THREADS
1118 rc = RegLoadKey(hKey, subKey, fileName );
1119 Py_END_ALLOW_THREADS
1120 if (rc != ERROR_SUCCESS)
1121 return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
1122 Py_INCREF(Py_None);
1123 return Py_None;
1124}
1125
1126static PyObject *
1127PyOpenKey(PyObject *self, PyObject *args)
1128{
1129 HKEY hKey;
1130 PyObject *obKey;
1131
1132 char *subKey;
1133 int res = 0;
1134 HKEY retKey;
1135 long rc;
1136 REGSAM sam = KEY_READ;
1137 if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey,
1138 &res, &sam))
1139 return NULL;
1140 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1141 return NULL;
1142
1143 Py_BEGIN_ALLOW_THREADS
1144 rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey);
1145 Py_END_ALLOW_THREADS
1146 if (rc != ERROR_SUCCESS)
1147 return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
1148 return PyHKEY_FromHKEY(retKey);
1149}
1150
1151
1152static PyObject *
1153PyQueryInfoKey(PyObject *self, PyObject *args)
1154{
1155 HKEY hKey;
1156 PyObject *obKey;
1157 long rc;
1158 DWORD nSubKeys, nValues;
1159 FILETIME ft;
1160 LARGE_INTEGER li;
1161 PyObject *l;
1162 PyObject *ret;
1163 if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey))
1164 return NULL;
1165 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1166 return NULL;
1167 if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL,
1168 &nValues, NULL, NULL, NULL, &ft))
1169 != ERROR_SUCCESS)
1170 return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
1171 li.LowPart = ft.dwLowDateTime;
1172 li.HighPart = ft.dwHighDateTime;
1173 l = PyLong_FromLongLong(li.QuadPart);
1174 if (l == NULL)
1175 return NULL;
1176 ret = Py_BuildValue("iiO", nSubKeys, nValues, l);
1177 Py_DECREF(l);
1178 return ret;
1179}
1180
1181static PyObject *
1182PyQueryValue(PyObject *self, PyObject *args)
1183{
1184 HKEY hKey;
1185 PyObject *obKey;
1186 char *subKey;
1187
1188 long rc;
1189 char *retBuf;
1190 long bufSize = 0;
1191 if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey))
1192 return NULL;
1193
1194 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1195 return NULL;
1196 if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize))
1197 != ERROR_SUCCESS)
1198 return PyErr_SetFromWindowsErrWithFunction(rc,
1199 "RegQueryValue");
1200 retBuf = (char *)alloca(bufSize);
1201 if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize))
1202 != ERROR_SUCCESS)
1203 return PyErr_SetFromWindowsErrWithFunction(rc,
1204 "RegQueryValue");
1205 return Py_BuildValue("s", retBuf);
1206}
1207
1208static PyObject *
1209PyQueryValueEx(PyObject *self, PyObject *args)
1210{
1211 HKEY hKey;
1212 PyObject *obKey;
1213 char *valueName;
1214
1215 long rc;
1216 char *retBuf;
1217 DWORD bufSize = 0;
1218 DWORD typ;
1219 PyObject *obData;
1220 PyObject *result;
1221
1222 if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName))
1223 return NULL;
1224
1225 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1226 return NULL;
1227 if ((rc = RegQueryValueEx(hKey, valueName,
1228 NULL, NULL, NULL,
1229 &bufSize))
1230 != ERROR_SUCCESS)
1231 return PyErr_SetFromWindowsErrWithFunction(rc,
1232 "RegQueryValueEx");
1233 retBuf = (char *)alloca(bufSize);
1234 if ((rc = RegQueryValueEx(hKey, valueName, NULL,
1235 &typ, (BYTE *)retBuf, &bufSize))
1236 != ERROR_SUCCESS)
1237 return PyErr_SetFromWindowsErrWithFunction(rc,
1238 "RegQueryValueEx");
1239 obData = Reg2Py(retBuf, bufSize, typ);
1240 if (obData == NULL)
1241 return NULL;
1242 result = Py_BuildValue("Oi", obData, typ);
1243 Py_DECREF(obData);
1244 return result;
1245}
1246
1247
1248static PyObject *
1249PySaveKey(PyObject *self, PyObject *args)
1250{
1251 HKEY hKey;
1252 PyObject *obKey;
1253 char *fileName;
1254 LPSECURITY_ATTRIBUTES pSA = NULL;
1255
1256 long rc;
1257 if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName))
1258 return NULL;
1259 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1260 return NULL;
1261/* One day we may get security into the core?
1262 if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
1263 return NULL;
1264*/
1265 Py_BEGIN_ALLOW_THREADS
1266 rc = RegSaveKey(hKey, fileName, pSA );
1267 Py_END_ALLOW_THREADS
1268 if (rc != ERROR_SUCCESS)
1269 return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
1270 Py_INCREF(Py_None);
1271 return Py_None;
1272}
1273
1274static PyObject *
1275PySetValue(PyObject *self, PyObject *args)
1276{
1277 HKEY hKey;
1278 PyObject *obKey;
1279 char *subKey;
1280 char *str;
1281 DWORD typ;
1282 DWORD len;
1283 long rc;
1284 PyObject *obStrVal;
1285 PyObject *obSubKey;
1286 if (!PyArg_ParseTuple(args, "OOiO:SetValue",
1287 &obKey,
1288 &obSubKey,
1289 &typ,
1290 &obStrVal))
1291 return NULL;
1292 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1293 return NULL;
1294 if (typ != REG_SZ) {
1295 PyErr_SetString(PyExc_TypeError,
1296 "Type must be win32con.REG_SZ");
1297 return NULL;
1298 }
1299 /* XXX - need Unicode support */
1300 str = PyString_AsString(obStrVal);
1301 if (str == NULL)
1302 return NULL;
1303 len = PyString_Size(obStrVal);
1304 if (obSubKey == Py_None)
1305 subKey = NULL;
1306 else {
1307 subKey = PyString_AsString(obSubKey);
1308 if (subKey == NULL)
1309 return NULL;
1310 }
1311 Py_BEGIN_ALLOW_THREADS
1312 rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1);
1313 Py_END_ALLOW_THREADS
1314 if (rc != ERROR_SUCCESS)
1315 return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue");
1316 Py_INCREF(Py_None);
1317 return Py_None;
1318}
1319
1320static PyObject *
1321PySetValueEx(PyObject *self, PyObject *args)
1322{
1323 HKEY hKey;
1324 PyObject *obKey;
1325 char *valueName;
1326 PyObject *obRes;
1327 PyObject *value;
1328 BYTE *data;
1329 DWORD len;
1330 DWORD typ;
1331
1332 LONG rc;
1333
1334 if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx",
1335 &obKey,
1336 &valueName,
1337 &obRes,
1338 &typ,
1339 &value))
1340 return NULL;
1341 if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1342 return NULL;
1343 if (!Py2Reg(value, typ, &data, &len))
1344 {
1345 if (!PyErr_Occurred())
1346 PyErr_SetString(PyExc_ValueError,
1347 "Could not convert the data to the specified type.");
1348 return NULL;
1349 }
1350 Py_BEGIN_ALLOW_THREADS
1351 rc = RegSetValueEx(hKey, valueName, 0, typ, data, len);
1352 Py_END_ALLOW_THREADS
Guido van Rossumb18618d2000-05-03 23:44:39 +00001353 PyMem_DEL(data);
Guido van Rossum9f3712c2000-03-28 20:37:15 +00001354 if (rc != ERROR_SUCCESS)
1355 return PyErr_SetFromWindowsErrWithFunction(rc,
1356 "RegSetValueEx");
1357 Py_INCREF(Py_None);
1358 return Py_None;
1359}
1360
1361static struct PyMethodDef winreg_methods[] = {
1362 {"CloseKey", PyCloseKey, 1, CloseKey_doc},
1363 {"ConnectRegistry", PyConnectRegistry, 1, ConnectRegistry_doc},
1364 {"CreateKey", PyCreateKey, 1, CreateKey_doc},
1365 {"DeleteKey", PyDeleteKey, 1, DeleteKey_doc},
1366 {"DeleteValue", PyDeleteValue, 1, DeleteValue_doc},
1367 {"EnumKey", PyEnumKey, 1, EnumKey_doc},
1368 {"EnumValue", PyEnumValue, 1, EnumValue_doc},
1369 {"FlushKey", PyFlushKey, 1, FlushKey_doc},
1370 {"LoadKey", PyLoadKey, 1, LoadKey_doc},
1371 {"OpenKey", PyOpenKey, 1, OpenKey_doc},
1372 {"OpenKeyEx", PyOpenKey, 1, OpenKeyEx_doc},
1373 {"QueryValue", PyQueryValue, 1, QueryValue_doc},
1374 {"QueryValueEx", PyQueryValueEx, 1, QueryValueEx_doc},
1375 {"QueryInfoKey", PyQueryInfoKey, 1, QueryInfoKey_doc},
1376 {"SaveKey", PySaveKey, 1, SaveKey_doc},
1377 {"SetValue", PySetValue, 1, SetValue_doc},
1378 {"SetValueEx", PySetValueEx, 1, SetValueEx_doc},
1379 NULL,
1380};
1381
1382static void
1383insint(PyObject * d, char * name, long value)
1384{
1385 PyObject *v = PyInt_FromLong(value);
1386 if (!v || PyDict_SetItemString(d, name, v))
1387 PyErr_Clear();
1388 Py_XDECREF(v);
1389}
1390
1391#define ADD_INT(val) insint(d, #val, val)
1392
1393static void
1394inskey(PyObject * d, char * name, HKEY key)
1395{
1396 PyObject *v = PyLong_FromVoidPtr(key);
1397 if (!v || PyDict_SetItemString(d, name, v))
1398 PyErr_Clear();
1399 Py_XDECREF(v);
1400}
1401
1402#define ADD_KEY(val) inskey(d, #val, val)
1403
1404__declspec(dllexport) void initwinreg(void)
1405{
1406 PyObject *m, *d;
1407 m = Py_InitModule3("winreg", winreg_methods, module_doc);
1408 d = PyModule_GetDict(m);
1409 PyHKEY_Type.ob_type = &PyType_Type;
1410 PyHKEY_Type.tp_doc = PyHKEY_doc;
1411 Py_INCREF(&PyHKEY_Type);
1412 if (PyDict_SetItemString(d, "HKEYType",
1413 (PyObject *)&PyHKEY_Type) != 0)
1414 return;
1415 Py_INCREF(PyExc_WindowsError);
1416 if (PyDict_SetItemString(d, "error",
1417 PyExc_WindowsError) != 0)
1418 return;
1419
1420 /* Add the relevant constants */
1421 ADD_KEY(HKEY_CLASSES_ROOT);
1422 ADD_KEY(HKEY_CURRENT_USER);
1423 ADD_KEY(HKEY_LOCAL_MACHINE);
1424 ADD_KEY(HKEY_USERS);
1425 ADD_KEY(HKEY_PERFORMANCE_DATA);
1426#ifdef HKEY_CURRENT_CONFIG
1427 ADD_KEY(HKEY_CURRENT_CONFIG);
1428#endif
1429#ifdef HKEY_DYN_DATA
1430 ADD_KEY(HKEY_DYN_DATA);
1431#endif
1432 ADD_INT(KEY_QUERY_VALUE);
1433 ADD_INT(KEY_SET_VALUE);
1434 ADD_INT(KEY_CREATE_SUB_KEY);
1435 ADD_INT(KEY_ENUMERATE_SUB_KEYS);
1436 ADD_INT(KEY_NOTIFY);
1437 ADD_INT(KEY_CREATE_LINK);
1438 ADD_INT(KEY_READ);
1439 ADD_INT(KEY_WRITE);
1440 ADD_INT(KEY_EXECUTE);
1441 ADD_INT(KEY_ALL_ACCESS);
1442 ADD_INT(REG_OPTION_RESERVED);
1443 ADD_INT(REG_OPTION_NON_VOLATILE);
1444 ADD_INT(REG_OPTION_VOLATILE);
1445 ADD_INT(REG_OPTION_CREATE_LINK);
1446 ADD_INT(REG_OPTION_BACKUP_RESTORE);
1447 ADD_INT(REG_OPTION_OPEN_LINK);
1448 ADD_INT(REG_LEGAL_OPTION);
1449 ADD_INT(REG_CREATED_NEW_KEY);
1450 ADD_INT(REG_OPENED_EXISTING_KEY);
1451 ADD_INT(REG_WHOLE_HIVE_VOLATILE);
1452 ADD_INT(REG_REFRESH_HIVE);
1453 ADD_INT(REG_NO_LAZY_FLUSH);
1454 ADD_INT(REG_NOTIFY_CHANGE_NAME);
1455 ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
1456 ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
1457 ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
1458 ADD_INT(REG_LEGAL_CHANGE_FILTER);
1459 ADD_INT(REG_NONE);
1460 ADD_INT(REG_SZ);
1461 ADD_INT(REG_EXPAND_SZ);
1462 ADD_INT(REG_BINARY);
1463 ADD_INT(REG_DWORD);
1464 ADD_INT(REG_DWORD_LITTLE_ENDIAN);
1465 ADD_INT(REG_DWORD_BIG_ENDIAN);
1466 ADD_INT(REG_LINK);
1467 ADD_INT(REG_MULTI_SZ);
1468 ADD_INT(REG_RESOURCE_LIST);
1469 ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
1470 ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
1471}
1472