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