winreg.c 59.7 KB
Newer Older
1
/*
2
  winreg.c
3 4 5 6

  Windows Registry access module for Python.

  * Simple registry access written by Mark Hammond in win32api
7
    module circa 1995.
8 9 10 11 12 13 14 15 16
  * Bill Tutt expanded the support significantly not long after.
  * Numerous other people have submitted patches since then.
  * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and
    basic Unicode support added.

*/

#include "Python.h"
#include "structmember.h"
17
#include "windows.h"
18 19 20 21 22 23 24 25 26 27 28 29 30

static BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pRes, BOOL bNoneOK);
static PyObject *PyHKEY_FromHKEY(HKEY h);
static BOOL PyHKEY_Close(PyObject *obHandle);

static char errNotAHandle[] = "Object is not a handle";

/* The win32api module reports the function name that failed,
   but this concept is not in the Python core.
   Hopefully it will one day, and in the meantime I dont
   want to lose this info...
*/
#define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
31
    PyErr_SetFromWindowsErr(rc)
32 33 34 35

/* Forward declares */

/* Doc strings */
36
PyDoc_STRVAR(module_doc,
37 38 39 40 41 42 43 44 45 46 47 48
"This module provides access to the Windows registry API.\n"
"\n"
"Functions:\n"
"\n"
"CloseKey() - Closes a registry key.\n"
"ConnectRegistry() - Establishes a connection to a predefined registry handle\n"
"                    on another computer.\n"
"CreateKey() - Creates the specified key, or opens it if it already exists.\n"
"DeleteKey() - Deletes the specified key.\n"
"DeleteValue() - Removes a named value from the specified registry key.\n"
"EnumKey() - Enumerates subkeys of the specified open registry key.\n"
"EnumValue() - Enumerates values of the specified open registry key.\n"
49
"ExpandEnvironmentStrings() - Expand the env strings in a REG_EXPAND_SZ string.\n"
50 51 52
"FlushKey() - Writes all the attributes of the specified key to the registry.\n"
"LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and stores\n"
"            registration information from a specified file into that subkey.\n"
53 54
"OpenKey() - Opens the specified key.\n"
"OpenKeyEx() - Alias of OpenKey().\n"
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
"QueryValue() - Retrieves the value associated with the unnamed value for a\n"
"               specified key in the registry.\n"
"QueryValueEx() - Retrieves the type and data for a specified value name\n"
"                 associated with an open registry key.\n"
"QueryInfoKey() - Returns information about the specified key.\n"
"SaveKey() - Saves the specified key, and all its subkeys a file.\n"
"SetValue() - Associates a value with a specified key.\n"
"SetValueEx() - Stores data in the value field of an open registry key.\n"
"\n"
"Special objects:\n"
"\n"
"HKEYType -- type object for HKEY objects\n"
"error -- exception raised for Win32 errors\n"
"\n"
"Integer constants:\n"
"Many constants are defined - see the documentation for each function\n"
71
"to see what constants are used, and where.");
72 73


74
PyDoc_STRVAR(CloseKey_doc,
75 76
"CloseKey(hkey)\n"
"Closes a previously opened registry key.\n"
77 78 79 80
"\n"
"The hkey argument specifies a previously opened key.\n"
"\n"
"Note that if the key is not closed using this method, it will be\n"
81
"closed when the hkey object is destroyed by Python.");
82

83
PyDoc_STRVAR(ConnectRegistry_doc,
84
"ConnectRegistry(computer_name, key) -> key\n"
85 86 87
"Establishes a connection to a predefined registry handle on another computer.\n"
"\n"
"computer_name is the name of the remote computer, of the form \\\\computername.\n"
88
"              If None, the local computer is used.\n"
89 90 91
"key is the predefined handle to connect to.\n"
"\n"
"The return value is the handle of the opened key.\n"
92
"If the function fails, an OSError exception is raised.");
93

94
PyDoc_STRVAR(CreateKey_doc,
95 96
"CreateKey(key, sub_key) -> key\n"
"Creates or opens the specified key.\n"
97
"\n"
98
"key is an already open key, or one of the predefined HKEY_* constants.\n"
99 100
"sub_key is a string that names the key this method opens or creates.\n"
"\n"
101 102 103 104
"If key is one of the predefined keys, sub_key may be None. In that case,\n"
"the handle returned is the same key handle passed in to the function.\n"
"\n"
"If the key already exists, this function opens the existing key.\n"
105 106
"\n"
"The return value is the handle of the opened key.\n"
107
"If the function fails, an OSError exception is raised.");
108

Brian Curtin's avatar
Brian Curtin committed
109
PyDoc_STRVAR(CreateKeyEx_doc,
110 111
"CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE) -> key\n"
"Creates or opens the specified key.\n"
Brian Curtin's avatar
Brian Curtin committed
112 113 114
"\n"
"key is an already open key, or one of the predefined HKEY_* constants\n"
"sub_key is a string that names the key this method opens or creates.\n"
115 116 117 118 119 120
"reserved is a reserved integer, and must be zero.  Default is zero.\n"
"access is an integer that specifies an access mask that describes the \n"
"       desired security access for the key. Default is KEY_WRITE.\n"
"\n"
"If key is one of the predefined keys, sub_key may be None. In that case,\n"
"the handle returned is the same key handle passed in to the function.\n"
Brian Curtin's avatar
Brian Curtin committed
121 122 123 124
"\n"
"If the key already exists, this function opens the existing key\n"
"\n"
"The return value is the handle of the opened key.\n"
125
"If the function fails, an OSError exception is raised.");
Brian Curtin's avatar
Brian Curtin committed
126

127
PyDoc_STRVAR(DeleteKey_doc,
128 129
"DeleteKey(key, sub_key)\n"
"Deletes the specified key.\n"
130 131
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
132 133 134
"sub_key is a string that must be a subkey of the key identified by the key\n"
"        parameter. This value must not be None, and the key may not have\n"
"        subkeys.\n"
135 136 137
"\n"
"This method can not delete keys with subkeys.\n"
"\n"
138
"If the function succeeds, the entire key, including all of its values,\n"
139
"is removed.  If the function fails, an OSError exception is raised.");
Brian Curtin's avatar
Brian Curtin committed
140 141

PyDoc_STRVAR(DeleteKeyEx_doc,
142 143
"DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0)\n"
"Deletes the specified key (64-bit OS only).\n"
Brian Curtin's avatar
Brian Curtin committed
144 145
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
146 147 148 149 150 151
"sub_key is a string that must be a subkey of the key identified by the key\n"
"        parameter. This value must not be None, and the key may not have\n"
"        subkeys.\n"
"reserved is a reserved integer, and must be zero.  Default is zero.\n"
"access is an integer that specifies an access mask that describes the \n"
"       desired security access for the key. Default is KEY_WOW64_64KEY.\n"
Brian Curtin's avatar
Brian Curtin committed
152 153 154
"\n"
"This method can not delete keys with subkeys.\n"
"\n"
155
"If the function succeeds, the entire key, including all of its values,\n"
156
"is removed.  If the function fails, an OSError exception is raised.\n"
Brian Curtin's avatar
Brian Curtin committed
157
"On unsupported Windows versions, NotImplementedError is raised.");
158

159
PyDoc_STRVAR(DeleteValue_doc,
160 161
"DeleteValue(key, value)\n"
"Removes a named value from a registry key.\n"
162 163
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
164
"value is a string that identifies the value to remove.");
165

166
PyDoc_STRVAR(EnumKey_doc,
167 168
"EnumKey(key, index) -> string\n"
"Enumerates subkeys of an open registry key.\n"
169 170 171 172 173
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
"index is an integer that identifies the index of the key to retrieve.\n"
"\n"
"The function retrieves the name of one subkey each time it is called.\n"
174
"It is typically called repeatedly until an OSError exception is\n"
175
"raised, indicating no more values are available.");
176

177
PyDoc_STRVAR(EnumValue_doc,
178 179
"EnumValue(key, index) -> tuple\n"
"Enumerates values of an open registry key.\n"
180 181 182 183
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
"index is an integer that identifies the index of the value to retrieve.\n"
"\n"
"The function retrieves the name of one subkey each time it is called.\n"
184
"It is typically called repeatedly, until an OSError exception\n"
Mark Hammond's avatar
Mark Hammond committed
185
"is raised, indicating no more values.\n"
186 187 188 189
"\n"
"The result is a tuple of 3 items:\n"
"value_name is a string that identifies the value.\n"
"value_data is an object that holds the value data, and whose type depends\n"
190
"           on the underlying registry type.\n"
191
"data_type is an integer that identifies the type of the value data.");
192

193
PyDoc_STRVAR(ExpandEnvironmentStrings_doc,
194 195
"ExpandEnvironmentStrings(string) -> string\n"
"Expand environment vars.\n");
196

197
PyDoc_STRVAR(FlushKey_doc,
198 199
"FlushKey(key)\n"
"Writes all the attributes of a key to the registry.\n"
200 201 202
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
"\n"
203 204 205 206 207 208 209 210
"It is not necessary to call FlushKey to change a key.  Registry changes are\n"
"flushed to disk by the registry using its lazy flusher.  Registry changes are\n"
"also flushed to disk at system shutdown.  Unlike CloseKey(), the FlushKey()\n"
"method returns only when all the data has been written to the registry.\n"
"\n"
"An application should only call FlushKey() if it requires absolute certainty\n"
"that registry changes are on disk.  If you don't know whether a FlushKey()\n"
"call is required, it probably isn't.");
211

212
PyDoc_STRVAR(LoadKey_doc,
213 214 215
"LoadKey(key, sub_key, file_name)\n"
"Creates a subkey under the specified key and stores registration information\n"
"from a specified file into that subkey.\n"
216 217
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
218 219 220 221 222
"sub_key is a string that identifies the sub_key to load.\n"
"file_name is the name of the file to load registry data from.  This file must\n"
"          have been created with the SaveKey() function.  Under the file\n"
"          allocation table (FAT) file system, the filename may not have an\n"
"          extension.\n"
223 224 225 226 227 228 229
"\n"
"A call to LoadKey() fails if the calling process does not have the\n"
"SE_RESTORE_PRIVILEGE privilege.\n"
"\n"
"If key is a handle returned by ConnectRegistry(), then the path specified\n"
"in fileName is relative to the remote computer.\n"
"\n"
230
"The docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE tree");
231

232
PyDoc_STRVAR(OpenKey_doc,
233 234
"OpenKey(key, sub_key, reserved=0, access=KEY_READ) -> key\n"
"Opens the specified key.\n"
235 236
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
237 238 239 240
"sub_key is a string that identifies the sub_key to open.\n"
"reserved is a reserved integer, and must be zero.  Default is zero.\n"
"access is an integer that specifies an access mask that describes the desired\n"
"       security access for the key.  Default is KEY_READ\n"
241 242
"\n"
"The result is a new handle to the specified key\n"
243
"If the function fails, an OSError exception is raised.");
244

245
PyDoc_STRVAR(OpenKeyEx_doc, "See OpenKey()");
246

247
PyDoc_STRVAR(QueryInfoKey_doc,
248 249
"QueryInfoKey(key) -> tuple\n"
"Returns information about a key.\n"
250 251 252 253 254 255
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
"\n"
"The result is a tuple of 3 items:"
"An integer that identifies the number of sub keys this key has.\n"
"An integer that identifies the number of values this key has.\n"
256
"An integer that identifies when the key was last modified (if available)\n"
257
" as 100's of nanoseconds since Jan 1, 1600.");
258

259
PyDoc_STRVAR(QueryValue_doc,
260 261
"QueryValue(key, sub_key) -> string\n"
"Retrieves the unnamed value for a key.\n"
262 263
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
Mark Hammond's avatar
Mark Hammond committed
264
"sub_key is a string that holds the name of the subkey with which the value\n"
265 266 267
"        is associated.  If this parameter is None or empty, the function\n"
"        retrieves the value set by the SetValue() method for the key\n"
"        identified by key."
268 269 270
"\n"
"Values in the registry have name, type, and data components. This method\n"
"retrieves the data for a key's first value that has a NULL name.\n"
271
"But the underlying API call doesn't return the type, Lame Lame Lame, DONT USE THIS!!!");
272

273
PyDoc_STRVAR(QueryValueEx_doc,
274 275 276
"QueryValueEx(key, value_name) -> (value, type_id)\n"
"Retrieves the type and data for a specified value name associated with an\n"
"open registry key.\n"
277 278
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
279
"value_name is a string indicating the value to query");
280

281
PyDoc_STRVAR(SaveKey_doc,
282 283
"SaveKey(key, file_name)\n"
"Saves the specified key, and all its subkeys to the specified file.\n"
284 285
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
286 287 288 289 290 291 292
"file_name is the name of the file to save registry data to.  This file cannot\n"
"          already exist. If this filename includes an extension, it cannot be\n"
"          used on file allocation table (FAT) file systems by the LoadKey(),\n"
"          ReplaceKey() or RestoreKey() methods.\n"
"\n"
"If key represents a key on a remote computer, the path described by file_name\n"
"is relative to the remote computer.\n"
293
"\n"
294 295
"The caller of this method must possess the SeBackupPrivilege security\n"
"privilege.  This function passes NULL for security_attributes to the API.");
296

297
PyDoc_STRVAR(SetValue_doc,
298 299
"SetValue(key, sub_key, type, value)\n"
"Associates a value with a specified key.\n"
300 301 302
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
"sub_key is a string that names the subkey with which the value is associated.\n"
303 304
"type is an integer that specifies the type of the data.  Currently this must\n"
"     be REG_SZ, meaning only strings are supported.\n"
305 306 307 308 309 310 311 312 313 314
"value is a string that specifies the new value.\n"
"\n"
"If the key specified by the sub_key parameter does not exist, the SetValue\n"
"function creates it.\n"
"\n"
"Value lengths are limited by available memory. Long values (more than\n"
"2048 bytes) should be stored as files with the filenames stored in \n"
"the configuration registry.  This helps the registry perform efficiently.\n"
"\n"
"The key identified by the key parameter must have been opened with\n"
315
"KEY_SET_VALUE access.");
316

317
PyDoc_STRVAR(SetValueEx_doc,
318 319
"SetValueEx(key, value_name, reserved, type, value)\n"
"Stores data in the value field of an open registry key.\n"
320 321
"\n"
"key is an already open key, or any one of the predefined HKEY_* constants.\n"
322 323
"value_name is a string containing the name of the value to set, or None.\n"
"reserved can be anything - zero is always passed to the API.\n"
324 325 326 327 328 329 330 331
"type is an integer that specifies the type of the data.  This should be one of:\n"
"  REG_BINARY -- Binary data in any form.\n"
"  REG_DWORD -- A 32-bit number.\n"
"  REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format.\n"
"  REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.\n"
"  REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references\n"
"                   to environment variables (for example, %PATH%).\n"
"  REG_LINK -- A Unicode symbolic link.\n"
Mark Hammond's avatar
Mark Hammond committed
332 333 334
"  REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by\n"
"                  two null characters.  Note that Python handles this\n"
"                  termination automatically.\n"
335 336 337 338 339 340 341 342 343 344 345 346 347
"  REG_NONE -- No defined value type.\n"
"  REG_RESOURCE_LIST -- A device-driver resource list.\n"
"  REG_SZ -- A null-terminated string.\n"
"value is a string that specifies the new value.\n"
"\n"
"This method can also set additional value and type information for the\n"
"specified key.  The key identified by the key parameter must have been\n"
"opened with KEY_SET_VALUE access.\n"
"\n"
"To open the key, use the CreateKeyEx() or OpenKeyEx() methods.\n"
"\n"
"Value lengths are limited by available memory. Long values (more than\n"
"2048 bytes) should be stored as files with the filenames stored in \n"
348
"the configuration registry.  This helps the registry perform efficiently.");
349

350
PyDoc_STRVAR(DisableReflectionKey_doc,
Christian Heimes's avatar
Christian Heimes committed
351
"Disables registry reflection for 32-bit processes running on a 64-bit\n"
352
"Operating System.  Will generally raise NotImplemented if executed on\n"
Christian Heimes's avatar
Christian Heimes committed
353
"a 32-bit Operating System.\n"
354
"\n"
355 356 357 358 359
"If the key is not on the reflection list, the function succeeds but has no effect.\n"
"Disabling reflection for a key does not affect reflection of any subkeys.");

PyDoc_STRVAR(EnableReflectionKey_doc,
"Restores registry reflection for the specified disabled key.\n"
Christian Heimes's avatar
Christian Heimes committed
360
"Will generally raise NotImplemented if executed on a 32-bit Operating System.\n"
361 362 363
"Restoring reflection for a key does not affect reflection of any subkeys.");

PyDoc_STRVAR(QueryReflectionKey_doc,
364 365
"QueryReflectionKey(hkey) -> bool\n"
"Determines the reflection state for the specified key.\n"
Christian Heimes's avatar
Christian Heimes committed
366
"Will generally raise NotImplemented if executed on a 32-bit Operating System.\n");
367

368
/* PyHKEY docstrings */
369
PyDoc_STRVAR(PyHKEY_doc,
370 371
"PyHKEY Object - A Python object, representing a win32 registry key.\n"
"\n"
Mark Hammond's avatar
Mark Hammond committed
372
"This object wraps a Windows HKEY object, automatically closing it when\n"
373 374 375 376 377 378 379 380 381 382 383 384 385 386
"the object is destroyed.  To guarantee cleanup, you can call either\n"
"the Close() method on the PyHKEY, or the CloseKey() method.\n"
"\n"
"All functions which accept a handle object also accept an integer - \n"
"however, use of the handle object is encouraged.\n"
"\n"
"Functions:\n"
"Close() - Closes the underlying handle.\n"
"Detach() - Returns the integer Win32 handle, detaching it from the object\n"
"\n"
"Properties:\n"
"handle - The integer Win32 handle.\n"
"\n"
"Operations:\n"
387
"__bool__ - Handles with an open object return true, otherwise false.\n"
388
"__int__ - Converting a handle to an integer returns the Win32 handle.\n"
389
"rich comparison - Handle objects are compared using the handle value.");
390 391


392
PyDoc_STRVAR(PyHKEY_Close_doc,
393 394
"key.Close()\n"
"Closes the underlying Windows handle.\n"
395
"\n"
396
"If the handle is already closed, no error is raised.");
397

398
PyDoc_STRVAR(PyHKEY_Detach_doc,
399 400
"key.Detach() -> int\n"
"Detaches the Windows handle from the handle object.\n"
401 402 403 404 405 406 407
"\n"
"The result is the value of the handle before it is detached.  If the\n"
"handle is already detached, this will return zero.\n"
"\n"
"After calling this function, the handle is effectively invalidated,\n"
"but the handle is not closed.  You would call this function when you\n"
"need the underlying win32 handle to exist beyond the lifetime of the\n"
408
"handle object.");
409 410 411 412 413 414 415 416


/************************************************************************

  The PyHKEY object definition

************************************************************************/
typedef struct {
417 418
    PyObject_VAR_HEAD
    HKEY hkey;
419 420 421 422 423 424 425 426 427
} PyHKEYObject;

#define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)

static char *failMsg = "bad operand type";

static PyObject *
PyHKEY_unaryFailureFunc(PyObject *ob)
{
428 429
    PyErr_SetString(PyExc_TypeError, failMsg);
    return NULL;
430 431 432 433
}
static PyObject *
PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
{
434 435
    PyErr_SetString(PyExc_TypeError, failMsg);
    return NULL;
436 437 438 439
}
static PyObject *
PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
{
440 441
    PyErr_SetString(PyExc_TypeError, failMsg);
    return NULL;
442 443 444 445 446
}

static void
PyHKEY_deallocFunc(PyObject *ob)
{
447 448 449 450 451 452 453 454
    /* Can not call PyHKEY_Close, as the ob->tp_type
       has already been cleared, thus causing the type
       check to fail!
    */
    PyHKEYObject *obkey = (PyHKEYObject *)ob;
    if (obkey->hkey)
        RegCloseKey((HKEY)obkey->hkey);
    PyObject_DEL(ob);
455 456 457
}

static int
458
PyHKEY_boolFunc(PyObject *ob)
459
{
460
    return ((PyHKEYObject *)ob)->hkey != 0;
461 462 463 464 465
}

static PyObject *
PyHKEY_intFunc(PyObject *ob)
{
466 467
    PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
    return PyLong_FromVoidPtr(pyhkey->hkey);
468 469 470 471 472
}

static PyObject *
PyHKEY_strFunc(PyObject *ob)
{
473 474
    PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
    return PyUnicode_FromFormat("<PyHKEY:%p>", pyhkey->hkey);
475 476 477 478 479
}

static int
PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
{
480 481 482 483
    PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
    PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
    return pyhkey1 == pyhkey2 ? 0 :
         (pyhkey1 < pyhkey2 ? -1 : 1);
484 485
}

486
static Py_hash_t
487 488
PyHKEY_hashFunc(PyObject *ob)
{
489 490 491 492
    /* Just use the address.
       XXX - should we use the handle value?
    */
    return _Py_HashPointer(ob);
493 494 495 496 497
}


static PyNumberMethods PyHKEY_NumberMethods =
{
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    PyHKEY_binaryFailureFunc,           /* nb_add */
    PyHKEY_binaryFailureFunc,           /* nb_subtract */
    PyHKEY_binaryFailureFunc,           /* nb_multiply */
    PyHKEY_binaryFailureFunc,           /* nb_remainder */
    PyHKEY_binaryFailureFunc,           /* nb_divmod */
    PyHKEY_ternaryFailureFunc,          /* nb_power */
    PyHKEY_unaryFailureFunc,            /* nb_negative */
    PyHKEY_unaryFailureFunc,            /* nb_positive */
    PyHKEY_unaryFailureFunc,            /* nb_absolute */
    PyHKEY_boolFunc,                    /* nb_bool */
    PyHKEY_unaryFailureFunc,            /* nb_invert */
    PyHKEY_binaryFailureFunc,           /* nb_lshift */
    PyHKEY_binaryFailureFunc,           /* nb_rshift */
    PyHKEY_binaryFailureFunc,           /* nb_and */
    PyHKEY_binaryFailureFunc,           /* nb_xor */
    PyHKEY_binaryFailureFunc,           /* nb_or */
    PyHKEY_intFunc,                     /* nb_int */
    0,                                  /* nb_reserved */
    PyHKEY_unaryFailureFunc,            /* nb_float */
517 518
};

519 520 521 522
static PyObject *PyHKEY_CloseMethod(PyObject *self, PyObject *args);
static PyObject *PyHKEY_DetachMethod(PyObject *self, PyObject *args);
static PyObject *PyHKEY_Enter(PyObject *self);
static PyObject *PyHKEY_Exit(PyObject *self, PyObject *args);
523

524
static struct PyMethodDef PyHKEY_methods[] = {
525 526 527 528 529
    {"Close",  PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc},
    {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc},
    {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL},
    {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL},
    {NULL}
530 531 532 533
};

#define OFF(e) offsetof(PyHKEYObject, e)
static PyMemberDef PyHKEY_memberlist[] = {
534 535
    {"handle",      T_INT,      OFF(hkey), READONLY},
    {NULL}    /* Sentinel */
536
};
537 538 539 540

/* The type itself */
PyTypeObject PyHKEY_Type =
{
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */
    "PyHKEY",
    sizeof(PyHKEYObject),
    0,
    PyHKEY_deallocFunc,                 /* tp_dealloc */
    0,                                  /* tp_print */
    0,                                  /* tp_getattr */
    0,                                  /* tp_setattr */
    0,                                  /* tp_reserved */
    0,                                  /* tp_repr */
    &PyHKEY_NumberMethods,              /* tp_as_number */
    0,                                  /* tp_as_sequence */
    0,                                  /* tp_as_mapping */
    PyHKEY_hashFunc,                    /* tp_hash */
    0,                                  /* tp_call */
    PyHKEY_strFunc,                     /* tp_str */
    0,                                  /* tp_getattro */
    0,                                  /* tp_setattro */
    0,                                  /* tp_as_buffer */
    0,                                  /* tp_flags */
    PyHKEY_doc,                         /* tp_doc */
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    0,                                  /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    0,                                  /*tp_iternext*/
    PyHKEY_methods,                     /*tp_methods*/
    PyHKEY_memberlist,                  /*tp_members*/
570 571 572 573 574 575 576 577 578 579
};

/************************************************************************

  The PyHKEY object methods

************************************************************************/
static PyObject *
PyHKEY_CloseMethod(PyObject *self, PyObject *args)
{
580 581 582 583 584 585
    if (!PyArg_ParseTuple(args, ":Close"))
        return NULL;
    if (!PyHKEY_Close(self))
        return NULL;
    Py_INCREF(Py_None);
    return Py_None;
586 587 588 589 590
}

static PyObject *
PyHKEY_DetachMethod(PyObject *self, PyObject *args)
{
591 592 593 594 595 596 597
    void* ret;
    PyHKEYObject *pThis = (PyHKEYObject *)self;
    if (!PyArg_ParseTuple(args, ":Detach"))
        return NULL;
    ret = (void*)pThis->hkey;
    pThis->hkey = 0;
    return PyLong_FromVoidPtr(ret);
598 599
}

600 601 602
static PyObject *
PyHKEY_Enter(PyObject *self)
{
603 604
    Py_XINCREF(self);
    return self;
605 606 607 608 609
}

static PyObject *
PyHKEY_Exit(PyObject *self, PyObject *args)
{
610 611 612
    if (!PyHKEY_Close(self))
        return NULL;
    Py_RETURN_NONE;
613 614 615
}


616 617 618 619 620 621
/************************************************************************
   The public PyHKEY API (well, not public yet :-)
************************************************************************/
PyObject *
PyHKEY_New(HKEY hInit)
{
622 623 624 625
    PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
    if (key)
        key->hkey = hInit;
    return (PyObject *)key;
626 627 628 629 630
}

BOOL
PyHKEY_Close(PyObject *ob_handle)
{
631 632 633 634 635 636 637 638 639 640 641 642 643
    LONG rc;
    PyHKEYObject *key;

    if (!PyHKEY_Check(ob_handle)) {
        PyErr_SetString(PyExc_TypeError, "bad operand type");
        return FALSE;
    }
    key = (PyHKEYObject *)ob_handle;
    rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS;
    key->hkey = 0;
    if (rc != ERROR_SUCCESS)
        PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
    return rc == ERROR_SUCCESS;
644 645 646 647 648
}

BOOL
PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
{
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    if (ob == Py_None) {
        if (!bNoneOK) {
            PyErr_SetString(
                      PyExc_TypeError,
                      "None is not a valid HKEY in this context");
            return FALSE;
        }
        *pHANDLE = (HKEY)0;
    }
    else if (PyHKEY_Check(ob)) {
        PyHKEYObject *pH = (PyHKEYObject *)ob;
        *pHANDLE = pH->hkey;
    }
    else if (PyLong_Check(ob)) {
        /* We also support integers */
        PyErr_Clear();
        *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
        if (PyErr_Occurred())
            return FALSE;
    }
    else {
        PyErr_SetString(
                        PyExc_TypeError,
            "The object is not a PyHKEY object");
        return FALSE;
    }
    return TRUE;
676 677 678 679 680
}

PyObject *
PyHKEY_FromHKEY(HKEY h)
{
681 682 683 684 685 686 687 688 689
    PyHKEYObject *op;

    /* Inline PyObject_New */
    op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
    if (op == NULL)
        return PyErr_NoMemory();
    PyObject_INIT(op, &PyHKEY_Type);
    op->hkey = h;
    return (PyObject *)op;
690 691 692 693 694 695 696 697 698
}


/************************************************************************
  The module methods
************************************************************************/
BOOL
PyWinObject_CloseHKEY(PyObject *obHandle)
{
699 700 701 702
    BOOL ok;
    if (PyHKEY_Check(obHandle)) {
        ok = PyHKEY_Close(obHandle);
    }
703
#if SIZEOF_LONG >= SIZEOF_HKEY
704 705 706 707 708 709
    else if (PyLong_Check(obHandle)) {
        long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle));
        ok = (rc == ERROR_SUCCESS);
        if (!ok)
            PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
    }
710
#else
711 712 713 714 715 716
    else if (PyLong_Check(obHandle)) {
        long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
        ok = (rc == ERROR_SUCCESS);
        if (!ok)
            PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
    }
717
#endif
718 719 720 721 722 723 724
    else {
        PyErr_SetString(
            PyExc_TypeError,
            "A handle must be a HKEY object or an integer");
        return FALSE;
    }
    return ok;
725 726 727 728 729 730 731 732 733
}


/*
   Private Helper functions for the registry interfaces

** Note that fixupMultiSZ and countString have both had changes
** made to support "incorrect strings".  The registry specification
** calls for strings to be terminated with 2 null bytes.  It seems
734
** some commercial packages install strings which dont conform,
735 736 737 738
** causing this code to fail - however, "regedit" etc still work
** with these strings (ie only we dont!).
*/
static void
739
fixupMultiSZ(wchar_t **str, wchar_t *data, int len)
740
{
741 742 743 744 745 746 747 748 749 750
    wchar_t *P;
    int i;
    wchar_t *Q;

    Q = data + len;
    for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
        str[i] = P;
        for(; *P != '\0'; P++)
            ;
    }
751 752 753
}

static int
754
countStrings(wchar_t *data, int len)
755
{
756 757 758 759 760 761 762 763
    int strings;
    wchar_t *P;
    wchar_t *Q = data + len;

    for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
        for (; P < Q && *P != '\0'; P++)
            ;
    return strings;
764 765 766 767 768 769 770
}

/* Convert PyObject into Registry data.
   Allocates space as needed. */
static BOOL
Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
{
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    Py_ssize_t i,j;
    switch (typ) {
        case REG_DWORD:
            if (value != Py_None && !PyLong_Check(value))
                return FALSE;
            *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
            if (*retDataBuf==NULL){
                PyErr_NoMemory();
                return FALSE;
            }
            *retDataSize = sizeof(DWORD);
            if (value == Py_None) {
                DWORD zero = 0;
                memcpy(*retDataBuf, &zero, sizeof(DWORD));
            }
            else {
787
                DWORD d = PyLong_AsUnsignedLong(value);
788 789 790 791 792 793
                memcpy(*retDataBuf, &d, sizeof(DWORD));
            }
            break;
        case REG_SZ:
        case REG_EXPAND_SZ:
            {
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
                if (value != Py_None) {
                    Py_ssize_t len;
                    if (!PyUnicode_Check(value))
                        return FALSE;
                    *retDataBuf = (BYTE*)PyUnicode_AsWideCharString(value, &len);
                    if (*retDataBuf == NULL)
                        return FALSE;
                    *retDataSize = Py_SAFE_DOWNCAST(
                        (len + 1) * sizeof(wchar_t),
                        Py_ssize_t, DWORD);
                }
                else {
                    *retDataBuf = (BYTE *)PyMem_NEW(wchar_t, 1);
                    if (*retDataBuf == NULL) {
                        PyErr_NoMemory();
                        return FALSE;
                    }
                    ((wchar_t *)*retDataBuf)[0] = L'\0';
                    *retDataSize = 1 * sizeof(wchar_t);
                }
                break;
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
            }
        case REG_MULTI_SZ:
            {
                DWORD size = 0;
                wchar_t *P;

                if (value == Py_None)
                    i = 0;
                else {
                    if (!PyList_Check(value))
                        return FALSE;
                    i = PyList_Size(value);
                }
                for (j = 0; j < i; j++)
                {
                    PyObject *t;
831 832 833
                    wchar_t *wstr;
                    Py_ssize_t len;

834 835 836
                    t = PyList_GET_ITEM(value, j);
                    if (!PyUnicode_Check(t))
                        return FALSE;
837 838 839 840
                    wstr = PyUnicode_AsUnicodeAndSize(t, &len);
                    if (wstr == NULL)
                        return FALSE;
                    size += Py_SAFE_DOWNCAST((len + 1) * sizeof(wchar_t),
841
                                             size_t, DWORD);
842 843 844 845 846 847 848 849 850 851 852 853 854 855
                }

                *retDataSize = size + 2;
                *retDataBuf = (BYTE *)PyMem_NEW(char,
                                                *retDataSize);
                if (*retDataBuf==NULL){
                    PyErr_NoMemory();
                    return FALSE;
                }
                P = (wchar_t *)*retDataBuf;

                for (j = 0; j < i; j++)
                {
                    PyObject *t;
856 857 858
                    wchar_t *wstr;
                    Py_ssize_t len;

859
                    t = PyList_GET_ITEM(value, j);
860 861 862 863 864
                    wstr = PyUnicode_AsUnicodeAndSize(t, &len);
                    if (wstr == NULL)
                        return FALSE;
                    wcscpy(P, wstr);
                    P += (len + 1);
865 866 867 868 869 870 871 872 873
                }
                /* And doubly-terminate the list... */
                *P = '\0';
                break;
            }
        case REG_BINARY:
        /* ALSO handle ALL unknown data types here.  Even if we can't
           support it natively, we should handle the bits. */
        default:
874
            if (value == Py_None) {
875
                *retDataSize = 0;
876 877
                *retDataBuf = NULL;
            }
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
            else {
                Py_buffer view;

                if (!PyObject_CheckBuffer(value)) {
                    PyErr_Format(PyExc_TypeError,
                        "Objects of type '%s' can not "
                        "be used as binary registry values",
                        value->ob_type->tp_name);
                    return FALSE;
                }

                if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
                    return FALSE;

                *retDataBuf = (BYTE *)PyMem_NEW(char, view.len);
                if (*retDataBuf==NULL){
                    PyBuffer_Release(&view);
                    PyErr_NoMemory();
                    return FALSE;
                }
898
                *retDataSize = Py_SAFE_DOWNCAST(view.len, Py_ssize_t, DWORD);
899 900 901 902 903 904
                memcpy(*retDataBuf, view.buf, view.len);
                PyBuffer_Release(&view);
            }
            break;
    }
    return TRUE;
905 906 907 908
}

/* Convert Registry data into PyObject*/
static PyObject *
909
Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ)
910
{
911 912 913 914 915
    PyObject *obData;

    switch (typ) {
        case REG_DWORD:
            if (retDataSize == 0)
916
                obData = PyLong_FromUnsignedLong(0);
917
            else
918
                obData = PyLong_FromUnsignedLong(*(int *)retDataBuf);
919 920 921 922 923 924 925 926 927 928 929
            break;
        case REG_SZ:
        case REG_EXPAND_SZ:
            {
                /* the buffer may or may not have a trailing NULL */
                wchar_t *data = (wchar_t *)retDataBuf;
                int len = retDataSize / 2;
                if (retDataSize && data[len-1] == '\0')
                    retDataSize -= 2;
                if (retDataSize <= 0)
                    data = L"";
Martin v. Löwis's avatar
Martin v. Löwis committed
930
                obData = PyUnicode_FromWideChar(data, retDataSize/2);
931 932 933 934 935 936 937 938 939 940 941
                break;
            }
        case REG_MULTI_SZ:
            if (retDataSize == 0)
                obData = PyList_New(0);
            else
            {
                int index = 0;
                wchar_t *data = (wchar_t *)retDataBuf;
                int len = retDataSize / 2;
                int s = countStrings(data, len);
942
                wchar_t **str = PyMem_New(wchar_t *, s);
943 944 945 946 947
                if (str == NULL)
                    return PyErr_NoMemory();

                fixupMultiSZ(str, data, len);
                obData = PyList_New(s);
948
                if (obData == NULL) {
949
                    PyMem_Free(str);
950
                    return NULL;
951
                }
952 953 954 955 956 957 958
                for (index = 0; index < s; index++)
                {
                    size_t len = wcslen(str[index]);
                    if (len > INT_MAX) {
                        PyErr_SetString(PyExc_OverflowError,
                            "registry string is too long for a Python string");
                        Py_DECREF(obData);
959
                        PyMem_Free(str);
960 961 962 963
                        return NULL;
                    }
                    PyList_SetItem(obData,
                                   index,
Martin v. Löwis's avatar
Martin v. Löwis committed
964
                                   PyUnicode_FromWideChar(str[index], len));
965
                }
966
                PyMem_Free(str);
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983

                break;
            }
        case REG_BINARY:
        /* ALSO handle ALL unknown data types here.  Even if we can't
           support it natively, we should handle the bits. */
        default:
            if (retDataSize == 0) {
                Py_INCREF(Py_None);
                obData = Py_None;
            }
            else
                obData = PyBytes_FromStringAndSize(
                             (char *)retDataBuf, retDataSize);
            break;
    }
    return obData;
984 985 986 987 988 989 990
}

/* The Python methods */

static PyObject *
PyCloseKey(PyObject *self, PyObject *args)
{
991 992 993 994 995 996 997
    PyObject *obKey;
    if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey))
        return NULL;
    if (!PyHKEY_Close(obKey))
        return NULL;
    Py_INCREF(Py_None);
    return Py_None;
998 999 1000 1001 1002
}

static PyObject *
PyConnectRegistry(PyObject *self, PyObject *args)
{
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    HKEY hKey;
    PyObject *obKey;
    wchar_t *szCompName = NULL;
    HKEY retKey;
    long rc;
    if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    Py_BEGIN_ALLOW_THREADS
    rc = RegConnectRegistryW(szCompName, hKey, &retKey);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "ConnectRegistry");
    return PyHKEY_FromHKEY(retKey);
1019 1020 1021 1022 1023
}

static PyObject *
PyCreateKey(PyObject *self, PyObject *args)
{
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    HKEY hKey;
    PyObject *obKey;
    wchar_t *subKey;
    HKEY retKey;
    long rc;
    if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    rc = RegCreateKeyW(hKey, subKey, &retKey);
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
    return PyHKEY_FromHKEY(retKey);
1037 1038
}

Brian Curtin's avatar
Brian Curtin committed
1039
static PyObject *
1040
PyCreateKeyEx(PyObject *self, PyObject *args, PyObject *kwargs)
Brian Curtin's avatar
Brian Curtin committed
1041
{
1042
    HKEY hKey;
1043 1044
    PyObject *key;
    wchar_t *sub_key;
1045
    HKEY retKey;
1046 1047
    int reserved = 0;
    REGSAM access = KEY_WRITE;
1048
    long rc;
1049 1050 1051 1052 1053

    char *kwlist[] = {"key", "sub_key", "reserved", "access", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OZ|ii:CreateKeyEx", kwlist,
                                     &key, &sub_key, &reserved, &access))
1054
        return NULL;
1055
    if (!PyHKEY_AsHKEY(key, &hKey, FALSE))
1056 1057
        return NULL;

1058 1059
    rc = RegCreateKeyExW(hKey, sub_key, reserved, NULL, (DWORD)NULL,
                         access, NULL, &retKey, NULL);
1060 1061 1062
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx");
    return PyHKEY_FromHKEY(retKey);
Brian Curtin's avatar
Brian Curtin committed
1063 1064
}

1065 1066 1067
static PyObject *
PyDeleteKey(PyObject *self, PyObject *args)
{
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    HKEY hKey;
    PyObject *obKey;
    wchar_t *subKey;
    long rc;
    if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    rc = RegDeleteKeyW(hKey, subKey );
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
    Py_INCREF(Py_None);
    return Py_None;
1081 1082
}

Brian Curtin's avatar
Brian Curtin committed
1083
static PyObject *
1084
PyDeleteKeyEx(PyObject *self, PyObject *args, PyObject *kwargs)
Brian Curtin's avatar
Brian Curtin committed
1085
{
1086
    HKEY hKey;
1087
    PyObject *key;
1088 1089 1090
    HMODULE hMod;
    typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int);
    RDKEFunc pfn = NULL;
1091
    wchar_t *sub_key;
1092
    long rc;
1093 1094
    int reserved = 0;
    REGSAM access = KEY_WOW64_64KEY;
1095

1096 1097 1098
    char *kwlist[] = {"key", "sub_key", "access", "reserved", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Ou|ii:DeleteKeyEx", kwlist,
                                     &key, &sub_key, &access, &reserved))
1099
        return NULL;
1100
    if (!PyHKEY_AsHKEY(key, &hKey, FALSE))
1101 1102 1103 1104
        return NULL;

    /* Only available on 64bit platforms, so we must load it
       dynamically. */
1105
    hMod = GetModuleHandleW(L"advapi32.dll");
1106 1107 1108 1109 1110 1111 1112 1113 1114
    if (hMod)
        pfn = (RDKEFunc)GetProcAddress(hMod,
                                                                   "RegDeleteKeyExW");
    if (!pfn) {
        PyErr_SetString(PyExc_NotImplementedError,
                                        "not implemented on this platform");
        return NULL;
    }
    Py_BEGIN_ALLOW_THREADS
1115
    rc = (*pfn)(hKey, sub_key, access, reserved);
1116 1117 1118 1119 1120 1121
    Py_END_ALLOW_THREADS

    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx");
    Py_INCREF(Py_None);
    return Py_None;
Brian Curtin's avatar
Brian Curtin committed
1122 1123
}

1124 1125 1126
static PyObject *
PyDeleteValue(PyObject *self, PyObject *args)
{
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    HKEY hKey;
    PyObject *obKey;
    wchar_t *subKey;
    long rc;
    if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    Py_BEGIN_ALLOW_THREADS
    rc = RegDeleteValueW(hKey, subKey);
    Py_END_ALLOW_THREADS
    if (rc !=ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegDeleteValue");
    Py_INCREF(Py_None);
    return Py_None;
1143 1144 1145 1146 1147
}

static PyObject *
PyEnumKey(PyObject *self, PyObject *args)
{
1148 1149 1150 1151 1152
    HKEY hKey;
    PyObject *obKey;
    int index;
    long rc;
    PyObject *retStr;
1153 1154 1155 1156 1157 1158 1159 1160

    /* The Windows docs claim that the max key name length is 255
     * characters, plus a terminating nul character.  However,
     * empirical testing demonstrates that it is possible to
     * create a 256 character key that is missing the terminating
     * nul.  RegEnumKeyEx requires a 257 character buffer to
     * retrieve such a key name. */
    wchar_t tmpbuf[257];
1161
    DWORD len = sizeof(tmpbuf)/sizeof(wchar_t); /* includes NULL terminator */
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

    if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx");

Martin v. Löwis's avatar
Martin v. Löwis committed
1174
    retStr = PyUnicode_FromWideChar(tmpbuf, len);
1175
    return retStr;  /* can be NULL */
1176 1177 1178 1179 1180
}

static PyObject *
PyEnumValue(PyObject *self, PyObject *args)
{
1181 1182 1183 1184 1185
    HKEY hKey;
    PyObject *obKey;
    int index;
    long rc;
    wchar_t *retValueBuf;
1186
    BYTE *tmpBuf;
1187
    BYTE *retDataBuf;
1188 1189
    DWORD retValueSize, bufValueSize;
    DWORD retDataSize, bufDataSize;
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    DWORD typ;
    PyObject *obData;
    PyObject *retVal;

    if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;

    if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
                              NULL,
                              &retValueSize, &retDataSize, NULL, NULL))
        != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegQueryInfoKey");
    ++retValueSize;    /* include null terminators */
    ++retDataSize;
1207 1208
    bufDataSize = retDataSize;
    bufValueSize = retValueSize;
1209
    retValueBuf = PyMem_New(wchar_t, retValueSize);
1210 1211 1212 1213 1214 1215 1216 1217
    if (retValueBuf == NULL)
        return PyErr_NoMemory();
    retDataBuf = (BYTE *)PyMem_Malloc(retDataSize);
    if (retDataBuf == NULL) {
        PyMem_Free(retValueBuf);
        return PyErr_NoMemory();
    }

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    while (1) {
        Py_BEGIN_ALLOW_THREADS
        rc = RegEnumValueW(hKey,
                  index,
                  retValueBuf,
                  &retValueSize,
                  NULL,
                  &typ,
                  (BYTE *)retDataBuf,
                  &retDataSize);
        Py_END_ALLOW_THREADS

        if (rc != ERROR_MORE_DATA)
            break;

        bufDataSize *= 2;
1234
        tmpBuf = (BYTE *)PyMem_Realloc(retDataBuf, bufDataSize);
1235
        if (tmpBuf == NULL) {
1236 1237 1238 1239
            PyErr_NoMemory();
            retVal = NULL;
            goto fail;
        }
1240
        retDataBuf = tmpBuf;
1241 1242 1243
        retDataSize = bufDataSize;
        retValueSize = bufValueSize;
    }
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256

    if (rc != ERROR_SUCCESS) {
        retVal = PyErr_SetFromWindowsErrWithFunction(rc,
                                                     "PyRegEnumValue");
        goto fail;
    }
    obData = Reg2Py(retDataBuf, retDataSize, typ);
    if (obData == NULL) {
        retVal = NULL;
        goto fail;
    }
    retVal = Py_BuildValue("uOi", retValueBuf, obData, typ);
    Py_DECREF(obData);
1257
  fail:
1258 1259 1260
    PyMem_Free(retValueBuf);
    PyMem_Free(retDataBuf);
    return retVal;
1261 1262
}

1263 1264 1265
static PyObject *
PyExpandEnvironmentStrings(PyObject *self, PyObject *args)
{
Victor Stinner's avatar
Victor Stinner committed
1266 1267
    wchar_t *retValue = NULL;
    wchar_t *src;
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    DWORD retValueSize;
    DWORD rc;
    PyObject *o;

    if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src))
        return NULL;

    retValueSize = ExpandEnvironmentStringsW(src, retValue, 0);
    if (retValueSize == 0) {
        return PyErr_SetFromWindowsErrWithFunction(retValueSize,
                                        "ExpandEnvironmentStrings");
    }
1280
    retValue = PyMem_New(wchar_t, retValueSize);
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    if (retValue == NULL) {
        return PyErr_NoMemory();
    }

    rc = ExpandEnvironmentStringsW(src, retValue, retValueSize);
    if (rc == 0) {
        PyMem_Free(retValue);
        return PyErr_SetFromWindowsErrWithFunction(retValueSize,
                                        "ExpandEnvironmentStrings");
    }
Victor Stinner's avatar
Victor Stinner committed
1291
    o = PyUnicode_FromWideChar(retValue, wcslen(retValue));
1292 1293
    PyMem_Free(retValue);
    return o;
1294 1295
}

1296 1297 1298
static PyObject *
PyFlushKey(PyObject *self, PyObject *args)
{
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    HKEY hKey;
    PyObject *obKey;
    long rc;
    if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    Py_BEGIN_ALLOW_THREADS
    rc = RegFlushKey(hKey);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
    Py_INCREF(Py_None);
    return Py_None;
1313 1314 1315 1316
}
static PyObject *
PyLoadKey(PyObject *self, PyObject *args)
{
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    HKEY hKey;
    PyObject *obKey;
    wchar_t *subKey;
    wchar_t *fileName;

    long rc;
    if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    Py_BEGIN_ALLOW_THREADS
    rc = RegLoadKeyW(hKey, subKey, fileName );
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
    Py_INCREF(Py_None);
    return Py_None;
1334 1335 1336
}

static PyObject *
1337
PyOpenKey(PyObject *self, PyObject *args, PyObject *kwargs)
1338
{
1339
    HKEY hKey;
1340 1341 1342
    PyObject *key;
    wchar_t *sub_key;
    int reserved = 0;
1343 1344
    HKEY retKey;
    long rc;
1345 1346 1347 1348 1349 1350
    REGSAM access = KEY_READ;

    char *kwlist[] = {"key", "sub_key", "reserved", "access", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OZ|ii:OpenKey", kwlist,
                                     &key, &sub_key, &reserved, &access))
1351
        return NULL;
1352
    if (!PyHKEY_AsHKEY(key, &hKey, FALSE))
1353 1354 1355
        return NULL;

    Py_BEGIN_ALLOW_THREADS
1356
    rc = RegOpenKeyExW(hKey, sub_key, reserved, access, &retKey);
1357 1358 1359 1360
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
    return PyHKEY_FromHKEY(retKey);
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
}


static PyObject *
PyQueryInfoKey(PyObject *self, PyObject *args)
{
  HKEY hKey;
  PyObject *obKey;
  long rc;
  DWORD nSubKeys, nValues;
  FILETIME ft;
  LARGE_INTEGER li;
  PyObject *l;
  PyObject *ret;
  if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey))
1376
    return NULL;
1377
  if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
1378
    return NULL;
1379
  if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL,
1380
                            &nValues,  NULL,  NULL, NULL, &ft))
1381
      != ERROR_SUCCESS)
1382
    return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
1383 1384 1385 1386
  li.LowPart = ft.dwLowDateTime;
  li.HighPart = ft.dwHighDateTime;
  l = PyLong_FromLongLong(li.QuadPart);
  if (l == NULL)
1387
    return NULL;
1388 1389 1390 1391 1392 1393 1394 1395
  ret = Py_BuildValue("iiO", nSubKeys, nValues, l);
  Py_DECREF(l);
  return ret;
}

static PyObject *
PyQueryValue(PyObject *self, PyObject *args)
{
1396 1397 1398 1399 1400 1401
    HKEY hKey;
    PyObject *obKey;
    wchar_t *subKey;
    long rc;
    PyObject *retStr;
    wchar_t *retBuf;
1402 1403 1404
    DWORD bufSize = 0;
    DWORD retSize = 0;
    wchar_t *tmp;
1405 1406 1407 1408 1409 1410

    if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey))
        return NULL;

    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
1411 1412 1413 1414 1415

    rc = RegQueryValueW(hKey, subKey, NULL, &retSize);
    if (rc == ERROR_MORE_DATA)
        retSize = 256;
    else if (rc != ERROR_SUCCESS)
1416 1417
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegQueryValue");
1418 1419 1420

    bufSize = retSize;
    retBuf = (wchar_t *) PyMem_Malloc(bufSize);
1421 1422 1423
    if (retBuf == NULL)
        return PyErr_NoMemory();

1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    while (1) {
        retSize = bufSize;
        rc = RegQueryValueW(hKey, subKey, retBuf, &retSize);
        if (rc != ERROR_MORE_DATA)
            break;

        bufSize *= 2;
        tmp = (wchar_t *) PyMem_Realloc(retBuf, bufSize);
        if (tmp == NULL) {
            PyMem_Free(retBuf);
            return PyErr_NoMemory();
        }
        retBuf = tmp;
    }

    if (rc != ERROR_SUCCESS) {
1440 1441 1442 1443 1444
        PyMem_Free(retBuf);
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegQueryValue");
    }

Martin v. Löwis's avatar
Martin v. Löwis committed
1445
    retStr = PyUnicode_FromWideChar(retBuf, wcslen(retBuf));
1446 1447
    PyMem_Free(retBuf);
    return retStr;
1448 1449 1450 1451 1452
}

static PyObject *
PyQueryValueEx(PyObject *self, PyObject *args)
{
1453 1454 1455 1456 1457
    HKEY hKey;
    PyObject *obKey;
    wchar_t *valueName;

    long rc;
1458 1459
    BYTE *retBuf, *tmp;
    DWORD bufSize = 0, retSize;
1460 1461 1462 1463 1464 1465 1466 1467 1468
    DWORD typ;
    PyObject *obData;
    PyObject *result;

    if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName))
        return NULL;

    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
1469 1470 1471 1472 1473

    rc = RegQueryValueExW(hKey, valueName, NULL, NULL, NULL, &bufSize);
    if (rc == ERROR_MORE_DATA)
        bufSize = 256;
    else if (rc != ERROR_SUCCESS)
1474 1475 1476 1477 1478
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegQueryValueEx");
    retBuf = (BYTE *)PyMem_Malloc(bufSize);
    if (retBuf == NULL)
        return PyErr_NoMemory();
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496

    while (1) {
        retSize = bufSize;
        rc = RegQueryValueExW(hKey, valueName, NULL, &typ,
                             (BYTE *)retBuf, &retSize);
        if (rc != ERROR_MORE_DATA)
            break;

        bufSize *= 2;
        tmp = (char *) PyMem_Realloc(retBuf, bufSize);
        if (tmp == NULL) {
            PyMem_Free(retBuf);
            return PyErr_NoMemory();
        }
       retBuf = tmp;
    }

    if (rc != ERROR_SUCCESS) {
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
        PyMem_Free(retBuf);
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegQueryValueEx");
    }
    obData = Reg2Py(retBuf, bufSize, typ);
    PyMem_Free(retBuf);
    if (obData == NULL)
        return NULL;
    result = Py_BuildValue("Oi", obData, typ);
    Py_DECREF(obData);
    return result;
1508 1509 1510 1511 1512 1513
}


static PyObject *
PySaveKey(PyObject *self, PyObject *args)
{
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    HKEY hKey;
    PyObject *obKey;
    wchar_t *fileName;
    LPSECURITY_ATTRIBUTES pSA = NULL;

    long rc;
    if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
1524
/*  One day we may get security into the core?
1525 1526
    if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
        return NULL;
1527
*/
1528 1529 1530 1531 1532 1533 1534
    Py_BEGIN_ALLOW_THREADS
    rc = RegSaveKeyW(hKey, fileName, pSA );
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
    Py_INCREF(Py_None);
    return Py_None;
1535 1536 1537 1538 1539
}

static PyObject *
PySetValue(PyObject *self, PyObject *args)
{
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    HKEY hKey;
    PyObject *obKey;
    wchar_t *subKey;
    wchar_t *str;
    DWORD typ;
    DWORD len;
    long rc;
    if (!PyArg_ParseTuple(args, "OZiu#:SetValue",
                          &obKey,
                          &subKey,
                          &typ,
                          &str,
                          &len))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    if (typ != REG_SZ) {
        PyErr_SetString(PyExc_TypeError,
                        "Type must be winreg.REG_SZ");
        return NULL;
    }

    Py_BEGIN_ALLOW_THREADS
    rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue");
    Py_INCREF(Py_None);
    return Py_None;
1569 1570 1571 1572 1573
}

static PyObject *
PySetValueEx(PyObject *self, PyObject *args)
{
1574 1575
    HKEY hKey;
    PyObject *obKey;
Victor Stinner's avatar
Victor Stinner committed
1576
    wchar_t *valueName;
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
    PyObject *obRes;
    PyObject *value;
    BYTE *data;
    DWORD len;
    DWORD typ;

    LONG rc;

    if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx",
                          &obKey,
                          &valueName,
                          &obRes,
                          &typ,
                          &value))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;
    if (!Py2Reg(value, typ, &data, &len))
    {
        if (!PyErr_Occurred())
            PyErr_SetString(PyExc_ValueError,
                     "Could not convert the data to the specified type.");
        return NULL;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = RegSetValueExW(hKey, valueName, 0, typ, data, len);
    Py_END_ALLOW_THREADS
    PyMem_DEL(data);
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegSetValueEx");
    Py_INCREF(Py_None);
    return Py_None;
1610 1611
}

1612 1613 1614
static PyObject *
PyDisableReflectionKey(PyObject *self, PyObject *args)
{
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
    HKEY hKey;
    PyObject *obKey;
    HMODULE hMod;
    typedef LONG (WINAPI *RDRKFunc)(HKEY);
    RDRKFunc pfn = NULL;
    LONG rc;

    if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;

    /* Only available on 64bit platforms, so we must load it
       dynamically.*/
1629
    hMod = GetModuleHandleW(L"advapi32.dll");
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    if (hMod)
        pfn = (RDRKFunc)GetProcAddress(hMod,
                                       "RegDisableReflectionKey");
    if (!pfn) {
        PyErr_SetString(PyExc_NotImplementedError,
                        "not implemented on this platform");
        return NULL;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = (*pfn)(hKey);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegDisableReflectionKey");
    Py_INCREF(Py_None);
    return Py_None;
1646 1647 1648 1649 1650
}

static PyObject *
PyEnableReflectionKey(PyObject *self, PyObject *args)
{
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
    HKEY hKey;
    PyObject *obKey;
    HMODULE hMod;
    typedef LONG (WINAPI *RERKFunc)(HKEY);
    RERKFunc pfn = NULL;
    LONG rc;

    if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;

    /* Only available on 64bit platforms, so we must load it
       dynamically.*/
1665
    hMod = GetModuleHandleW(L"advapi32.dll");
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    if (hMod)
        pfn = (RERKFunc)GetProcAddress(hMod,
                                       "RegEnableReflectionKey");
    if (!pfn) {
        PyErr_SetString(PyExc_NotImplementedError,
                        "not implemented on this platform");
        return NULL;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = (*pfn)(hKey);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegEnableReflectionKey");
    Py_INCREF(Py_None);
    return Py_None;
1682 1683 1684 1685 1686
}

static PyObject *
PyQueryReflectionKey(PyObject *self, PyObject *args)
{
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
    HKEY hKey;
    PyObject *obKey;
    HMODULE hMod;
    typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *);
    RQRKFunc pfn = NULL;
    BOOL result;
    LONG rc;

    if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey))
        return NULL;
    if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
        return NULL;

    /* Only available on 64bit platforms, so we must load it
       dynamically.*/
1702
    hMod = GetModuleHandleW(L"advapi32.dll");
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    if (hMod)
        pfn = (RQRKFunc)GetProcAddress(hMod,
                                       "RegQueryReflectionKey");
    if (!pfn) {
        PyErr_SetString(PyExc_NotImplementedError,
                        "not implemented on this platform");
        return NULL;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = (*pfn)(hKey, &result);
    Py_END_ALLOW_THREADS
    if (rc != ERROR_SUCCESS)
        return PyErr_SetFromWindowsErrWithFunction(rc,
                                                   "RegQueryReflectionKey");
    return PyBool_FromLong(result);
1718 1719
}

1720
static struct PyMethodDef winreg_methods[] = {
1721 1722 1723
    {"CloseKey",         PyCloseKey,        METH_VARARGS, CloseKey_doc},
    {"ConnectRegistry",  PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc},
    {"CreateKey",        PyCreateKey,       METH_VARARGS, CreateKey_doc},
1724 1725
    {"CreateKeyEx",      (PyCFunction)PyCreateKeyEx,
                         METH_VARARGS | METH_KEYWORDS, CreateKeyEx_doc},
1726
    {"DeleteKey",        PyDeleteKey,       METH_VARARGS, DeleteKey_doc},
1727 1728
    {"DeleteKeyEx",      (PyCFunction)PyDeleteKeyEx,
                         METH_VARARGS | METH_KEYWORDS, DeleteKeyEx_doc},
1729 1730 1731 1732 1733 1734 1735 1736 1737
    {"DeleteValue",      PyDeleteValue,     METH_VARARGS, DeleteValue_doc},
    {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc},
    {"EnableReflectionKey",  PyEnableReflectionKey,  METH_VARARGS, EnableReflectionKey_doc},
    {"EnumKey",          PyEnumKey,         METH_VARARGS, EnumKey_doc},
    {"EnumValue",        PyEnumValue,       METH_VARARGS, EnumValue_doc},
    {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS,
        ExpandEnvironmentStrings_doc },
    {"FlushKey",         PyFlushKey,        METH_VARARGS, FlushKey_doc},
    {"LoadKey",          PyLoadKey,         METH_VARARGS, LoadKey_doc},
1738 1739 1740 1741
    {"OpenKey",          (PyCFunction)PyOpenKey, METH_VARARGS | METH_KEYWORDS,
                                                 OpenKey_doc},
    {"OpenKeyEx",        (PyCFunction)PyOpenKey, METH_VARARGS | METH_KEYWORDS,
                                                 OpenKeyEx_doc},
1742 1743 1744 1745 1746 1747 1748 1749
    {"QueryValue",       PyQueryValue,      METH_VARARGS, QueryValue_doc},
    {"QueryValueEx",     PyQueryValueEx,    METH_VARARGS, QueryValueEx_doc},
    {"QueryInfoKey",     PyQueryInfoKey,    METH_VARARGS, QueryInfoKey_doc},
    {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc},
    {"SaveKey",          PySaveKey,         METH_VARARGS, SaveKey_doc},
    {"SetValue",         PySetValue,        METH_VARARGS, SetValue_doc},
    {"SetValueEx",       PySetValueEx,      METH_VARARGS, SetValueEx_doc},
    NULL,
1750 1751 1752 1753 1754
};

static void
insint(PyObject * d, char * name, long value)
{
1755 1756 1757 1758
    PyObject *v = PyLong_FromLong(value);
    if (!v || PyDict_SetItemString(d, name, v))
        PyErr_Clear();
    Py_XDECREF(v);
1759 1760 1761 1762 1763 1764 1765
}

#define ADD_INT(val) insint(d, #val, val)

static void
inskey(PyObject * d, char * name, HKEY key)
{
1766 1767 1768 1769
    PyObject *v = PyLong_FromVoidPtr(key);
    if (!v || PyDict_SetItemString(d, name, v))
        PyErr_Clear();
    Py_XDECREF(v);
1770 1771 1772 1773
}

#define ADD_KEY(val) inskey(d, #val, val)

1774 1775

static struct PyModuleDef winregmodule = {
1776 1777 1778 1779 1780 1781 1782 1783 1784
    PyModuleDef_HEAD_INIT,
    "winreg",
    module_doc,
    -1,
    winreg_methods,
    NULL,
    NULL,
    NULL,
    NULL
1785 1786 1787
};

PyMODINIT_FUNC PyInit_winreg(void)
1788
{
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
    PyObject *m, *d;
    m = PyModule_Create(&winregmodule);
    if (m == NULL)
        return NULL;
    d = PyModule_GetDict(m);
    PyHKEY_Type.tp_doc = PyHKEY_doc;
    if (PyType_Ready(&PyHKEY_Type) < 0)
        return NULL;
    Py_INCREF(&PyHKEY_Type);
    if (PyDict_SetItemString(d, "HKEYType",
                             (PyObject *)&PyHKEY_Type) != 0)
        return NULL;
1801
    Py_INCREF(PyExc_OSError);
1802
    if (PyDict_SetItemString(d, "error",
1803
                             PyExc_OSError) != 0)
1804 1805 1806 1807 1808 1809 1810 1811
        return NULL;

    /* Add the relevant constants */
    ADD_KEY(HKEY_CLASSES_ROOT);
    ADD_KEY(HKEY_CURRENT_USER);
    ADD_KEY(HKEY_LOCAL_MACHINE);
    ADD_KEY(HKEY_USERS);
    ADD_KEY(HKEY_PERFORMANCE_DATA);
1812
#ifdef HKEY_CURRENT_CONFIG
1813
    ADD_KEY(HKEY_CURRENT_CONFIG);
1814 1815
#endif
#ifdef HKEY_DYN_DATA
1816
    ADD_KEY(HKEY_DYN_DATA);
1817
#endif
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
    ADD_INT(KEY_QUERY_VALUE);
    ADD_INT(KEY_SET_VALUE);
    ADD_INT(KEY_CREATE_SUB_KEY);
    ADD_INT(KEY_ENUMERATE_SUB_KEYS);
    ADD_INT(KEY_NOTIFY);
    ADD_INT(KEY_CREATE_LINK);
    ADD_INT(KEY_READ);
    ADD_INT(KEY_WRITE);
    ADD_INT(KEY_EXECUTE);
    ADD_INT(KEY_ALL_ACCESS);
1828
#ifdef KEY_WOW64_64KEY
1829
    ADD_INT(KEY_WOW64_64KEY);
1830 1831
#endif
#ifdef KEY_WOW64_32KEY
1832
    ADD_INT(KEY_WOW64_32KEY);
1833
#endif
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
    ADD_INT(REG_OPTION_RESERVED);
    ADD_INT(REG_OPTION_NON_VOLATILE);
    ADD_INT(REG_OPTION_VOLATILE);
    ADD_INT(REG_OPTION_CREATE_LINK);
    ADD_INT(REG_OPTION_BACKUP_RESTORE);
    ADD_INT(REG_OPTION_OPEN_LINK);
    ADD_INT(REG_LEGAL_OPTION);
    ADD_INT(REG_CREATED_NEW_KEY);
    ADD_INT(REG_OPENED_EXISTING_KEY);
    ADD_INT(REG_WHOLE_HIVE_VOLATILE);
    ADD_INT(REG_REFRESH_HIVE);
    ADD_INT(REG_NO_LAZY_FLUSH);
    ADD_INT(REG_NOTIFY_CHANGE_NAME);
    ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
    ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
    ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
    ADD_INT(REG_LEGAL_CHANGE_FILTER);
    ADD_INT(REG_NONE);
    ADD_INT(REG_SZ);
    ADD_INT(REG_EXPAND_SZ);
    ADD_INT(REG_BINARY);
    ADD_INT(REG_DWORD);
    ADD_INT(REG_DWORD_LITTLE_ENDIAN);
    ADD_INT(REG_DWORD_BIG_ENDIAN);
    ADD_INT(REG_LINK);
    ADD_INT(REG_MULTI_SZ);
    ADD_INT(REG_RESOURCE_LIST);
    ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
    ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
    return m;
1864 1865
}

1866