2 * Registry processing routines. Routines, common for registry
3 * processing frontends.
5 * Copyright 1999 Sylvain St-Germain
6 * Copyright 2002 Andriy Palamarchuk
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #define REG_VAL_BUF_SIZE 4096
27 /* maximal number of characters in hexadecimal data line,
28 not including '\' character */
29 #define REG_FILE_HEX_LINE_LEN 76
31 /* Globals used by the api setValue */
32 static LPSTR currentKeyName
= NULL
;
33 static HKEY currentKeyClass
= 0;
34 static HKEY currentKeyHandle
= 0;
35 static BOOL bTheKeyIsOpen
= FALSE
;
37 static const CHAR
*app_name
= "UNKNOWN";
39 static const CHAR
*reg_class_names
[] = {
40 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
41 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
44 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
46 static HKEY reg_class_keys
[REG_CLASS_NUMBER
] = {
47 HKEY_LOCAL_MACHINE
, HKEY_USERS
, HKEY_CLASSES_ROOT
,
48 HKEY_CURRENT_CONFIG
, HKEY_CURRENT_USER
, HKEY_DYN_DATA
52 #define NOT_ENOUGH_MEMORY 1
55 /* processing macros */
57 /* common check of memory allocation results */
58 #define CHECK_ENOUGH_MEMORY(p) \
61 fprintf(stderr,"%s: file %s, line %d: Not enough memory\n", \
62 getAppName(), __FILE__, __LINE__); \
63 exit(NOT_ENOUGH_MEMORY); \
66 /******************************************************************************
67 * This is a replacement for strsep which is not portable (missing on Solaris).
71 char* getToken(char** str
, const char* delims
)
82 if (strchr(delims
,**str
)!=NULL
) {
89 /* There is no other token */
95 /******************************************************************************
96 * Copies file name from command line string to the buffer.
97 * Rewinds the command line string pointer to the next non-space character
98 * after the file name.
99 * Buffer contains an empty string if no filename was found;
102 * command_line - command line current position pointer
103 * where *s[0] is the first symbol of the file name.
104 * file_name - buffer to write the file name to.
106 void get_file_name(CHAR
**command_line
, CHAR
*file_name
)
108 CHAR
*s
= *command_line
;
109 int pos
= 0; /* position of pointer "s" in *command_line */
121 fprintf(stderr
,"%s: Unexpected end of file name!\n",
129 while(s
[0] && !isspace(s
[0])) {
134 memcpy(file_name
, *command_line
, pos
* sizeof((*command_line
)[0]));
135 /* remove the last backslash */
136 if (file_name
[pos
- 1] == '\\') {
137 file_name
[pos
- 1] = '\0';
139 file_name
[pos
] = '\0';
146 while(s
[0] && isspace(s
[0])) {
150 (*command_line
) += pos
;
154 /******************************************************************************
155 * Converts a hex representation of a DWORD into a DWORD.
157 static BOOL
convertHexToDWord(char* str
, DWORD
*dw
)
160 if (strlen(str
) > 8 || sscanf(str
, "%lx%c", dw
, &dummy
) != 1) {
161 fprintf(stderr
,"%s: ERROR, invalid hex value\n", getAppName());
167 /******************************************************************************
168 * Converts a hex comma separated values list into a binary string.
170 static BYTE
* convertHexCSVToHex(char *str
, DWORD
*size
)
175 /* The worst case is 1 digit + 1 comma per byte */
176 *size
=(strlen(str
)+1)/2;
177 data
=HeapAlloc(GetProcessHeap(), 0, *size
);
178 CHECK_ENOUGH_MEMORY(data
);
187 if (s
[1] != ',' && s
[1] != '\0' && s
[2] != ',' && s
[2] != '\0') {
188 fprintf(stderr
,"%s: ERROR converting CSV hex stream. Invalid sequence at '%s'\n",
190 HeapFree(GetProcessHeap(), 0, data
);
193 if (sscanf(s
, "%x%c", &wc
, &dummy
) < 1 || dummy
!= ',') {
194 fprintf(stderr
,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
196 HeapFree(GetProcessHeap(), 0, data
);
201 /* Skip one or two digits and any comma */
202 while (*s
&& *s
!=',') s
++;
209 /******************************************************************************
210 * This function returns the HKEY associated with the data type encoded in the
211 * value. It modifies the input parameter (key value) in order to skip this
212 * "now useless" data type information.
214 * Note: Updated based on the algorithm used in 'server/registry.c'
216 DWORD
getDataType(LPSTR
*lpValue
, DWORD
* parse_type
)
218 struct data_type
{ const char *tag
; int len
; int type
; int parse_type
; };
220 static const struct data_type data_types
[] = { /* actual type */ /* type to assume for parsing */
221 { "\"", 1, REG_SZ
, REG_SZ
},
222 { "str:\"", 5, REG_SZ
, REG_SZ
},
223 { "str(2):\"", 8, REG_EXPAND_SZ
, REG_SZ
},
224 { "hex:", 4, REG_BINARY
, REG_BINARY
},
225 { "dword:", 6, REG_DWORD
, REG_DWORD
},
226 { "hex(", 4, -1, REG_BINARY
},
230 const struct data_type
*ptr
;
233 for (ptr
= data_types
; ptr
->tag
; ptr
++) {
234 if (memcmp( ptr
->tag
, *lpValue
, ptr
->len
))
238 *parse_type
= ptr
->parse_type
;
243 /* "hex(xx):" is special */
244 type
= (int)strtoul( *lpValue
, &end
, 16 );
245 if (**lpValue
=='\0' || *end
!=')' || *(end
+1)!=':') {
253 *parse_type
=REG_NONE
;
257 /******************************************************************************
258 * Returns an allocated buffer with a cleaned copy (removed the surrounding
259 * dbl quotes) of the passed value.
261 LPSTR
getArg( LPSTR arg
)
270 * Get rid of surrounding quotes
274 if( arg
[len
-1] == '\"' ) arg
[len
-1] = '\0';
275 if( arg
[0] == '\"' ) arg
++;
277 tmp
= HeapAlloc(GetProcessHeap(), 0, strlen(arg
)+1);
278 CHECK_ENOUGH_MEMORY(tmp
);
284 /******************************************************************************
285 * Replaces escape sequences with the characters.
287 static void REGPROC_unescape_string(LPSTR str
)
289 size_t str_idx
= 0; /* current character under analysis */
290 size_t val_idx
= 0; /* the last character of the unescaped string */
291 size_t len
= strlen(str
);
292 for (str_idx
= 0; str_idx
< len
; str_idx
++, val_idx
++) {
293 if (str
[str_idx
] == '\\') {
295 switch (str
[str_idx
]) {
301 str
[val_idx
] = str
[str_idx
];
304 fprintf(stderr
,"Warning! Unrecognized escape sequence: \\%c'\n",
306 str
[val_idx
] = str
[str_idx
];
310 str
[val_idx
] = str
[str_idx
];
316 /******************************************************************************
317 * Sets the value with name val_name to the data in val_data for the currently
321 * val_name - name of the registry value
322 * val_data - registry value data
324 LONG
setValue(LPSTR val_name
, LPSTR val_data
)
327 DWORD dwDataType
, dwParseType
;
331 if ( (val_name
== NULL
) || (val_data
== NULL
) )
332 return ERROR_INVALID_PARAMETER
;
334 if (strcmp(val_data
, "-") == 0)
336 res
=RegDeleteValueA(currentKeyHandle
,val_name
);
337 return (res
== ERROR_FILE_NOT_FOUND
? ERROR_SUCCESS
: res
);
340 /* Get the data type stored into the value field */
341 dwDataType
= getDataType(&val_data
, &dwParseType
);
343 if (dwParseType
== REG_SZ
) /* no conversion for string */
345 dwLen
= (DWORD
) strlen(val_data
);
346 if (dwLen
>0 && val_data
[dwLen
-1]=='"')
349 val_data
[dwLen
]='\0';
352 REGPROC_unescape_string(val_data
);
353 lpbData
= (LPBYTE
)val_data
;
355 else if (dwParseType
== REG_DWORD
) /* Convert the dword types */
357 if (!convertHexToDWord(val_data
, &dwData
))
358 return ERROR_INVALID_DATA
;
359 lpbData
= (BYTE
*)&dwData
;
360 dwLen
= sizeof(dwData
);
362 else if (dwParseType
== REG_BINARY
) /* Convert the binary data */
364 lpbData
= convertHexCSVToHex(val_data
, &dwLen
);
366 return ERROR_INVALID_DATA
;
368 else /* unknown format */
370 fprintf(stderr
,"%s: ERROR, unknown data format\n", getAppName());
371 return ERROR_INVALID_DATA
;
374 res
= RegSetValueExA(
382 if (dwParseType
== REG_BINARY
)
383 HeapFree(GetProcessHeap(), 0, lpbData
);
388 /******************************************************************************
391 LONG
openKey( LPSTR stdInput
)
397 if (stdInput
== NULL
)
398 return ERROR_INVALID_PARAMETER
;
400 /* Get the registry class */
401 if (!getRegClass(stdInput
, ¤tKeyClass
)) /* Sets global variable */
402 return ERROR_INVALID_PARAMETER
;
404 /* Get the key name */
405 currentKeyName
= getRegKeyName(stdInput
); /* Sets global variable */
406 if (currentKeyName
== NULL
)
407 return ERROR_INVALID_PARAMETER
;
409 res
= RegCreateKeyExA(
410 currentKeyClass
, /* Class */
411 currentKeyName
, /* Sub Key */
413 NULL
, /* object type */
414 REG_OPTION_NON_VOLATILE
, /* option, REG_OPTION_NON_VOLATILE ... */
415 KEY_ALL_ACCESS
, /* access mask, KEY_ALL_ACCESS */
416 NULL
, /* security attribute */
417 ¤tKeyHandle
, /* result */
418 &dwDisp
); /* disposition, REG_CREATED_NEW_KEY or
419 REG_OPENED_EXISTING_KEY */
421 if (res
== ERROR_SUCCESS
)
422 bTheKeyIsOpen
= TRUE
;
428 /******************************************************************************
429 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
430 * the key name (what starts after the first '\')
432 LPSTR
getRegKeyName(LPSTR lpLine
)
435 char lpLineCopy
[KEY_MAX_LEN
];
440 strcpy(lpLineCopy
, lpLine
);
442 keyNameBeg
= strchr(lpLineCopy
, '\\'); /* The key name start by '\' */
445 if (lpLine
[0] == '[') /* need to find matching ']' */
449 keyNameEnd
= strrchr(lpLineCopy
, ']');
451 *keyNameEnd
= '\0'; /* remove ']' from the key name */
455 keyNameBeg
= lpLineCopy
+ strlen(lpLineCopy
); /* branch - empty string */
457 currentKeyName
= HeapAlloc(GetProcessHeap(), 0, strlen(keyNameBeg
) + 1);
458 CHECK_ENOUGH_MEMORY(currentKeyName
);
459 strcpy(currentKeyName
, keyNameBeg
);
460 return currentKeyName
;
463 /******************************************************************************
464 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
465 * the key class (what ends before the first '\')
467 BOOL
getRegClass(LPSTR lpClass
, HKEY
* hkey
)
473 char lpClassCopy
[KEY_MAX_LEN
];
478 lstrcpynA(lpClassCopy
, lpClass
, KEY_MAX_LEN
);
480 classNameEnd
= strchr(lpClassCopy
, '\\'); /* The class name ends by '\' */
481 if (!classNameEnd
) /* or the whole string */
483 classNameEnd
= lpClassCopy
+ strlen(lpClassCopy
);
484 if (classNameEnd
[-1] == ']')
489 *classNameEnd
= '\0'; /* Isolate the class name */
490 if (lpClassCopy
[0] == '[') {
491 classNameBeg
= lpClassCopy
+ 1;
493 classNameBeg
= lpClassCopy
;
496 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++) {
497 if (!strcmp(classNameBeg
, reg_class_names
[i
])) {
498 *hkey
= reg_class_keys
[i
];
505 /******************************************************************************
506 * Close the currently opened key.
510 RegCloseKey(currentKeyHandle
);
512 HeapFree(GetProcessHeap(), 0, currentKeyName
); /* Allocated by getKeyName */
514 bTheKeyIsOpen
= FALSE
;
516 currentKeyName
= NULL
;
518 currentKeyHandle
= 0;
521 /******************************************************************************
522 * This function is the main entry point to the setValue type of action. It
523 * receives the currently read line and dispatch the work depending on the
526 void doSetValue(LPSTR stdInput
)
529 * We encountered the end of the file, make sure we
530 * close the opened key and exit
532 if (stdInput
== NULL
) {
533 if (bTheKeyIsOpen
!= FALSE
)
539 if ( stdInput
[0] == '[') /* We are reading a new key */
541 if ( bTheKeyIsOpen
!= FALSE
)
542 closeKey(); /* Close the previous key before */
544 /* delete the key if we encounter '-' at the start of reg key */
545 if ( stdInput
[1] == '-')
547 int last_chr
= strlen(stdInput
) - 1;
549 /* skip leading "[-" and get rid of trailing "]" */
550 if (stdInput
[last_chr
] == ']')
551 stdInput
[last_chr
] = '\0';
552 delete_registry_key(stdInput
+2);
556 if ( openKey(stdInput
) != ERROR_SUCCESS
)
557 fprintf(stderr
,"%s: setValue failed to open key %s\n",
558 getAppName(), stdInput
);
559 } else if( ( bTheKeyIsOpen
) &&
560 (( stdInput
[0] == '@') || /* reading a default @=data pair */
561 ( stdInput
[0] == '\"'))) /* reading a new value=data pair */
563 processSetValue(stdInput
);
564 } else /* since we are assuming that the */
565 { /* file format is valid we must */
566 if ( bTheKeyIsOpen
) /* be reading a blank line which */
567 closeKey(); /* indicate end of this key processing */
571 /******************************************************************************
572 * This function is the main entry point to the deleteValue type of action. It
573 * receives the currently read line and dispatch the work depending on the
576 void doDeleteValue(LPSTR line
)
578 UNREFERENCED_PARAMETER(line
);
579 fprintf(stderr
,"%s: deleteValue not yet implemented\n", getAppName());
582 /******************************************************************************
583 * This function is the main entry point to the deleteKey type of action. It
584 * receives the currently read line and dispatch the work depending on the
587 void doDeleteKey(LPSTR line
)
589 UNREFERENCED_PARAMETER(line
);
590 fprintf(stderr
,"%s: deleteKey not yet implemented\n", getAppName());
593 /******************************************************************************
594 * This function is the main entry point to the createKey type of action. It
595 * receives the currently read line and dispatch the work depending on the
598 void doCreateKey(LPSTR line
)
600 UNREFERENCED_PARAMETER(line
);
601 fprintf(stderr
,"%s: createKey not yet implemented\n", getAppName());
604 /******************************************************************************
605 * This function is a wrapper for the setValue function. It prepares the
606 * land and clean the area once completed.
607 * Note: this function modifies the line parameter.
609 * line - registry file unwrapped line. Should have the registry value name and
610 * complete registry value data.
612 void processSetValue(LPSTR line
)
614 LPSTR val_name
; /* registry value name */
615 LPSTR val_data
; /* registry value data */
617 int line_idx
= 0; /* current character under analysis */
621 if (line
[line_idx
] == '@' && line
[line_idx
+ 1] == '=') {
622 line
[line_idx
] = '\0';
625 } else if (line
[line_idx
] == '\"') {
627 val_name
= line
+ line_idx
;
629 /* check if the line is unterminated (otherwise it may loop forever!) */
630 if (line
[line_idx
] == '\0') {
631 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", line
);
634 if (line
[line_idx
] == '\\') /* skip escaped character */
638 if (line
[line_idx
] == '\"') {
639 line
[line_idx
] = '\0';
647 if (line
[line_idx
] != '=') {
648 line
[line_idx
] = '\"';
649 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", line
);
654 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", line
);
657 line_idx
++; /* skip the '=' character */
658 val_data
= line
+ line_idx
;
660 REGPROC_unescape_string(val_name
);
661 res
= setValue(val_name
, val_data
);
662 if ( res
!= ERROR_SUCCESS
)
663 fprintf(stderr
,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
670 /******************************************************************************
671 * Calls command for each line of a registry file.
672 * Correctly processes comments (in # form), line continuation.
675 * in - input stream to read from
676 * command - command to be called for each line
678 void processRegLines(FILE *in
, CommandAPI command
)
680 LPSTR line
= NULL
; /* line read from input stream */
681 size_t lineSize
= REG_VAL_BUF_SIZE
;
683 line
= HeapAlloc(GetProcessHeap(), 0, lineSize
);
684 CHECK_ENOUGH_MEMORY(line
);
687 LPSTR s
; /* The pointer into line for where the current fgets should read */
690 size_t size_remaining
;
692 char *s_eol
; /* various local uses */
694 /* Do we need to expand the buffer ? */
695 assert (s
>= line
&& s
<= line
+ lineSize
);
696 size_remaining
= lineSize
- (s
-line
);
697 if (size_remaining
< 2) /* room for 1 character and the \0 */
700 size_t new_size
= lineSize
+ REG_VAL_BUF_SIZE
;
701 if (new_size
> lineSize
) /* no arithmetic overflow */
702 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, line
, new_size
);
705 CHECK_ENOUGH_MEMORY(new_buffer
);
707 s
= line
+ lineSize
- size_remaining
;
709 size_remaining
= lineSize
- (s
-line
);
712 /* Get as much as possible into the buffer, terminated either by
713 * eof, error, eol or getting the maximum amount. Abort on error.
715 size_to_get
= (int) (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
716 if (NULL
== fgets (s
, size_to_get
, in
)) {
718 perror ("While reading input");
723 /* It is not clear to me from the definition that the
724 * contents of the buffer are well defined on detecting
725 * an eof without managing to read anything.
730 /* If we didn't read the eol nor the eof go around for the rest */
731 s_eol
= strchr (s
, '\n');
732 if (!feof (in
) && !s_eol
) {
733 s
= strchr (s
, '\0');
734 /* It should be s + size_to_get - 1 but this is safer */
738 /* If it is a comment line then discard it and go around again */
739 if (line
[0] == '#') {
744 /* Remove any line feed. Leave s_eol on the \0 */
747 if (s_eol
> line
&& *(s_eol
-1) == '\r')
750 s_eol
= strchr (s
, '\0');
752 /* If there is a concatenating \\ then go around again */
753 if (s_eol
> line
&& *(s_eol
-1) == '\\') {
756 /* The following error protection could be made more self-
757 * correcting but I thought it not worth trying.
759 if ((c
= fgetc (in
)) == EOF
|| c
!= ' ' ||
760 (c
= fgetc (in
)) == EOF
|| c
!= ' ')
761 fprintf(stderr
,"%s: ERROR - invalid continuation.\n",
766 break; /* That is the full virtual line */
773 HeapFree(GetProcessHeap(), 0, line
);
776 /******************************************************************************
777 * This function is the main entry point to the registerDLL action. It
778 * receives the currently read line, then loads and registers the requested DLLs
780 void doRegisterDLL(LPSTR stdInput
)
785 /* Check for valid input */
786 if (stdInput
== NULL
)
789 /* Load and register the library, then free it */
790 theLib
= LoadLibraryA(stdInput
);
792 FARPROC lpfnDLLRegProc
= GetProcAddress(theLib
, "DllRegisterServer");
794 retVal
= (*lpfnDLLRegProc
)();
796 fprintf(stderr
,"%s: Couldn't find DllRegisterServer proc in '%s'.\n",
797 getAppName(), stdInput
);
800 fprintf(stderr
,"%s: DLLRegisterServer error 0x%x in '%s'.\n",
801 getAppName(), retVal
, stdInput
);
805 fprintf(stderr
,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput
);
809 /******************************************************************************
810 * This function is the main entry point to the unregisterDLL action. It
811 * receives the currently read line, then loads and unregisters the requested DLLs
813 void doUnregisterDLL(LPSTR stdInput
)
818 /* Check for valid input */
819 if (stdInput
== NULL
)
822 /* Load and unregister the library, then free it */
823 theLib
= LoadLibraryA(stdInput
);
825 FARPROC lpfnDLLRegProc
= GetProcAddress(theLib
, "DllUnregisterServer");
827 retVal
= (*lpfnDLLRegProc
)();
829 fprintf(stderr
,"%s: Couldn't find DllUnregisterServer proc in '%s'.\n",
830 getAppName(), stdInput
);
833 fprintf(stderr
,"%s: DLLUnregisterServer error 0x%x in '%s'.\n",
834 getAppName(), retVal
, stdInput
);
838 fprintf(stderr
,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput
);
842 /****************************************************************************
843 * REGPROC_print_error
845 * Print the message for GetLastError
848 static void REGPROC_print_error(void)
854 error_code
= GetLastError ();
855 status
= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
856 NULL
, error_code
, 0, (LPTSTR
) &lpMsgBuf
, 0, NULL
);
858 fprintf(stderr
,"%s: Cannot display message for error %ld, status %ld\n",
859 getAppName(), error_code
, GetLastError());
863 LocalFree((HLOCAL
)lpMsgBuf
);
867 /******************************************************************************
868 * Checks whether the buffer has enough room for the string or required size.
869 * Resizes the buffer if necessary.
872 * buffer - pointer to a buffer for string
873 * len - current length of the buffer in characters.
874 * required_len - length of the string to place to the buffer in characters.
875 * The length does not include the terminating null character.
877 static void REGPROC_resize_char_buffer(CHAR
**buffer
, DWORD
*len
, DWORD required_len
)
880 if (required_len
> *len
) {
883 *buffer
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(**buffer
));
885 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *len
* sizeof(**buffer
));
886 CHECK_ENOUGH_MEMORY(*buffer
);
890 /******************************************************************************
891 * Prints string str to file
893 static void REGPROC_export_string(FILE *file
, CHAR
*str
)
895 size_t len
= strlen(str
);
898 /* escaping characters */
899 for (i
= 0; i
< len
; i
++) {
918 /******************************************************************************
919 * Writes contents of the registry key to the specified file stream.
922 * file - writable file stream to export registry branch to.
923 * key - registry branch to export.
924 * reg_key_name_buf - name of the key with registry class.
925 * Is resized if necessary.
926 * reg_key_name_len - length of the buffer for the registry class in characters.
927 * val_name_buf - buffer for storing value name.
928 * Is resized if necessary.
929 * val_name_len - length of the buffer for storing value names in characters.
930 * val_buf - buffer for storing values while extracting.
931 * Is resized if necessary.
932 * val_size - size of the buffer for storing values in bytes.
934 static void export_hkey(FILE *file
, HKEY key
,
935 CHAR
**reg_key_name_buf
, DWORD
*reg_key_name_len
,
936 CHAR
**val_name_buf
, DWORD
*val_name_len
,
937 BYTE
**val_buf
, DWORD
*val_size
)
939 DWORD max_sub_key_len
;
940 DWORD max_val_name_len
;
947 /* get size information and resize the buffers if necessary */
948 if (RegQueryInfoKey(key
, NULL
, NULL
, NULL
, NULL
,
949 &max_sub_key_len
, NULL
,
950 NULL
, &max_val_name_len
, &max_val_size
, NULL
, NULL
951 ) != ERROR_SUCCESS
) {
952 REGPROC_print_error();
954 curr_len
= (DWORD
) strlen(*reg_key_name_buf
);
955 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_len
,
956 max_sub_key_len
+ curr_len
+ 1);
957 REGPROC_resize_char_buffer(val_name_buf
, val_name_len
,
959 if (max_val_size
> *val_size
) {
960 *val_size
= max_val_size
;
961 if (!*val_buf
) *val_buf
= HeapAlloc(GetProcessHeap(), 0, *val_size
);
962 else *val_buf
= HeapReAlloc(GetProcessHeap(), 0, *val_buf
, *val_size
);
963 CHECK_ENOUGH_MEMORY(val_buf
);
966 /* output data for the current key */
968 fputs(*reg_key_name_buf
, file
);
970 /* print all the values */
975 DWORD val_name_len1
= *val_name_len
;
976 DWORD val_size1
= *val_size
;
977 ret
= RegEnumValueA(key
, i
, *val_name_buf
, &val_name_len1
, NULL
,
978 &value_type
, *val_buf
, &val_size1
);
979 if (ret
!= ERROR_SUCCESS
) {
981 if (ret
!= ERROR_NO_MORE_ITEMS
) {
982 REGPROC_print_error();
987 if ((*val_name_buf
)[0]) {
989 REGPROC_export_string(file
, *val_name_buf
);
995 switch (value_type
) {
999 REGPROC_export_string(file
, (char*) *val_buf
);
1000 fputs("\"\n", file
);
1004 fprintf(file
, "dword:%08lx\n", *((DWORD
*)*val_buf
));
1008 fprintf(stderr
,"%s: warning - unsupported registry format '%ld', "
1009 "treat as binary\n",
1010 getAppName(), value_type
);
1011 fprintf(stderr
,"key name: \"%s\"\n", *reg_key_name_buf
);
1012 fprintf(stderr
,"value name:\"%s\"\n\n", *val_name_buf
);
1018 const CHAR
*hex_prefix
;
1022 if (value_type
== REG_BINARY
) {
1023 hex_prefix
= "hex:";
1026 sprintf(buf
, "hex(%ld):", value_type
);
1029 /* position of where the next character will be printed */
1030 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1031 cur_pos
= (int) (strlen("\"\"=") + strlen("hex:") +
1032 strlen(*val_name_buf
));
1034 fputs(hex_prefix
, file
);
1035 for (i1
= 0; i1
< val_size1
; i1
++) {
1036 fprintf(file
, "%02x", (unsigned int)(*val_buf
)[i1
]);
1037 if (i1
+ 1 < val_size1
) {
1043 if (cur_pos
> REG_FILE_HEX_LINE_LEN
) {
1044 fputs("\\\n ", file
);
1057 (*reg_key_name_buf
)[curr_len
] = '\\';
1059 DWORD buf_len
= *reg_key_name_len
- curr_len
;
1061 ret
= RegEnumKeyExA(key
, i
, *reg_key_name_buf
+ curr_len
+ 1, &buf_len
,
1062 NULL
, NULL
, NULL
, NULL
);
1063 if (ret
!= ERROR_SUCCESS
&& ret
!= ERROR_MORE_DATA
) {
1065 if (ret
!= ERROR_NO_MORE_ITEMS
) {
1066 REGPROC_print_error();
1072 if (RegOpenKeyA(key
, *reg_key_name_buf
+ curr_len
+ 1,
1073 &subkey
) == ERROR_SUCCESS
) {
1074 export_hkey(file
, subkey
, reg_key_name_buf
, reg_key_name_len
,
1075 val_name_buf
, val_name_len
, val_buf
, val_size
);
1076 RegCloseKey(subkey
);
1078 REGPROC_print_error();
1082 (*reg_key_name_buf
)[curr_len
] = '\0';
1085 /******************************************************************************
1086 * Open file for export.
1088 static FILE *REGPROC_open_export_file(const TCHAR
*file_name
)
1090 FILE *file
= _tfopen(file_name
, _T("w"));
1093 /* fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_name);*/
1096 fputs("REGEDIT4\n", file
);
1100 /******************************************************************************
1101 * Writes contents of the registry key to the specified file stream.
1104 * file_name - name of a file to export registry branch to.
1105 * reg_key_name - registry branch to export. The whole registry is exported if
1106 * reg_key_name is NULL or contains an empty string.
1108 BOOL
export_registry_key(const TCHAR
*file_name
, CHAR
*reg_key_name
)
1112 CHAR
*reg_key_name_buf
;
1115 DWORD reg_key_name_len
= KEY_MAX_LEN
;
1116 DWORD val_name_len
= KEY_MAX_LEN
;
1117 DWORD val_size
= REG_VAL_BUF_SIZE
;
1120 reg_key_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1121 reg_key_name_len
* sizeof(*reg_key_name_buf
));
1122 val_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1123 val_name_len
* sizeof(*val_name_buf
));
1124 val_buf
= HeapAlloc(GetProcessHeap(), 0, val_size
);
1125 CHECK_ENOUGH_MEMORY(reg_key_name_buf
&& val_name_buf
&& val_buf
);
1127 if (reg_key_name
&& reg_key_name
[0]) {
1131 REGPROC_resize_char_buffer(®_key_name_buf
, ®_key_name_len
,
1132 (DWORD
) strlen(reg_key_name
));
1133 strcpy(reg_key_name_buf
, reg_key_name
);
1135 /* open the specified key */
1136 if (!getRegClass(reg_key_name
, ®_key_class
)) {
1137 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1138 getAppName(), reg_key_name
);
1141 branch_name
= getRegKeyName(reg_key_name
);
1142 CHECK_ENOUGH_MEMORY(branch_name
);
1143 if (!branch_name
[0]) {
1144 /* no branch - registry class is specified */
1145 file
= REGPROC_open_export_file(file_name
);
1146 export_hkey(file
, reg_key_class
,
1147 ®_key_name_buf
, ®_key_name_len
,
1148 &val_name_buf
, &val_name_len
,
1149 &val_buf
, &val_size
);
1150 } else if (RegOpenKeyA(reg_key_class
, branch_name
, &key
) == ERROR_SUCCESS
) {
1151 file
= REGPROC_open_export_file(file_name
);
1152 export_hkey(file
, key
,
1153 ®_key_name_buf
, ®_key_name_len
,
1154 &val_name_buf
, &val_name_len
,
1155 &val_buf
, &val_size
);
1158 fprintf(stderr
,"%s: Can't export. Registry key '%s' does not exist!\n",
1159 getAppName(), reg_key_name
);
1160 REGPROC_print_error();
1162 HeapFree(GetProcessHeap(), 0, branch_name
);
1166 /* export all registry classes */
1167 file
= REGPROC_open_export_file(file_name
);
1168 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++) {
1169 /* do not export HKEY_CLASSES_ROOT */
1170 if (reg_class_keys
[i
] != HKEY_CLASSES_ROOT
&&
1171 reg_class_keys
[i
] != HKEY_CURRENT_USER
&&
1172 reg_class_keys
[i
] != HKEY_CURRENT_CONFIG
&&
1173 reg_class_keys
[i
] != HKEY_DYN_DATA
) {
1174 strcpy(reg_key_name_buf
, reg_class_names
[i
]);
1175 export_hkey(file
, reg_class_keys
[i
],
1176 ®_key_name_buf
, ®_key_name_len
,
1177 &val_name_buf
, &val_name_len
,
1178 &val_buf
, &val_size
);
1186 HeapFree(GetProcessHeap(), 0, val_buf
);
1190 /******************************************************************************
1191 * Reads contents of the specified file into the registry.
1193 BOOL
import_registry_file(LPTSTR filename
)
1195 FILE* reg_file
= _tfopen(filename
, _T("r"));
1198 unsigned char ch1
= fgetc(reg_file
);
1199 unsigned char ch2
= fgetc(reg_file
);
1201 /* detect UTF-16.LE or UTF-16.BE format */
1202 if ((ch1
== 0xff && ch2
== 0xfe) ||
1203 (ch1
== 0xfe && ch2
== 0xff)) {
1204 /* TODO: implement support for UNICODE files! */
1206 /* restore read point to the first line */
1207 fseek(reg_file
, 0L, SEEK_SET
);
1208 processRegLines(reg_file
, doSetValue
);
1216 /******************************************************************************
1217 * Recursive function which removes the registry key with all subkeys.
1219 static void delete_branch(HKEY key
,
1220 CHAR
**reg_key_name_buf
, DWORD
*reg_key_name_len
)
1223 DWORD max_sub_key_len
;
1229 if (RegOpenKeyA(key
, *reg_key_name_buf
, &branch_key
) != ERROR_SUCCESS
) {
1230 REGPROC_print_error();
1233 /* get size information and resize the buffers if necessary */
1234 if (RegQueryInfoKey(branch_key
, NULL
, NULL
, NULL
,
1235 &subkeys
, &max_sub_key_len
,
1236 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
1237 ) != ERROR_SUCCESS
) {
1238 REGPROC_print_error();
1240 curr_len
= (DWORD
) strlen(*reg_key_name_buf
);
1241 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_len
,
1242 max_sub_key_len
+ curr_len
+ 1);
1244 (*reg_key_name_buf
)[curr_len
] = '\\';
1245 for (i
= subkeys
- 1; i
>= 0; i
--) {
1246 DWORD buf_len
= *reg_key_name_len
- curr_len
;
1248 ret
= RegEnumKeyExA(branch_key
, i
, *reg_key_name_buf
+ curr_len
+ 1,
1249 &buf_len
, NULL
, NULL
, NULL
, NULL
);
1250 if (ret
!= ERROR_SUCCESS
&&
1251 ret
!= ERROR_MORE_DATA
&&
1252 ret
!= ERROR_NO_MORE_ITEMS
) {
1253 REGPROC_print_error();
1255 delete_branch(key
, reg_key_name_buf
, reg_key_name_len
);
1258 (*reg_key_name_buf
)[curr_len
] = '\0';
1259 RegCloseKey(branch_key
);
1260 RegDeleteKeyA(key
, *reg_key_name_buf
);
1263 /******************************************************************************
1264 * Removes the registry key with all subkeys. Parses full key name.
1267 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1268 * empty, points to register key class, does not exist.
1270 void delete_registry_key(CHAR
*reg_key_name
)
1273 DWORD branch_name_len
;
1277 if (!reg_key_name
|| !reg_key_name
[0])
1279 /* open the specified key */
1280 if (!getRegClass(reg_key_name
, ®_key_class
)) {
1281 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1282 getAppName(), reg_key_name
);
1285 branch_name
= getRegKeyName(reg_key_name
);
1286 CHECK_ENOUGH_MEMORY(branch_name
);
1287 branch_name_len
= (DWORD
) strlen(branch_name
);
1288 if (!branch_name
[0]) {
1289 fprintf(stderr
,"%s: Can't delete registry class '%s'\n",
1290 getAppName(), reg_key_name
);
1293 if (RegOpenKeyA(reg_key_class
, branch_name
, &branch_key
) == ERROR_SUCCESS
) {
1294 /* check whether the key exists */
1295 RegCloseKey(branch_key
);
1296 delete_branch(reg_key_class
, &branch_name
, &branch_name_len
);
1298 HeapFree(GetProcessHeap(), 0, branch_name
);
1301 /******************************************************************************
1302 * Sets the application name. Then application name is used in the error
1305 void setAppName(const CHAR
*name
)
1310 const CHAR
*getAppName(void)
1315 LONG
RegCopyKey(HKEY hDestKey
, LPCTSTR lpDestSubKey
, HKEY hSrcKey
, LPCTSTR lpSrcSubKey
)
1318 DWORD dwDisposition
;
1319 HKEY hDestSubKey
= NULL
;
1320 HKEY hSrcSubKey
= NULL
;
1321 DWORD dwIndex
, dwType
, cbName
, cbData
;
1322 TCHAR szSubKey
[256];
1323 TCHAR szValueName
[256];
1324 BYTE szValueData
[512];
1328 /* open the source subkey, if specified */
1331 lResult
= RegOpenKeyEx(hSrcKey
, lpSrcSubKey
, 0, KEY_ALL_ACCESS
, &hSrcSubKey
);
1334 hSrcKey
= hSrcSubKey
;
1337 /* create the destination subkey */
1338 lResult
= RegCreateKeyEx(hDestKey
, lpDestSubKey
, 0, NULL
, 0, KEY_WRITE
, NULL
,
1339 &hDestSubKey
, &dwDisposition
);
1343 /* copy all subkeys */
1347 cbName
= sizeof(szSubKey
) / sizeof(szSubKey
[0]);
1348 lResult
= RegEnumKeyEx(hSrcKey
, dwIndex
++, szSubKey
, &cbName
, NULL
, NULL
, NULL
, &ft
);
1349 if (lResult
== ERROR_SUCCESS
)
1351 lResult
= RegCopyKey(hDestSubKey
, szSubKey
, hSrcKey
, szSubKey
);
1356 while(lResult
== ERROR_SUCCESS
);
1358 /* copy all subvalues */
1362 cbName
= sizeof(szValueName
) / sizeof(szValueName
[0]);
1363 cbData
= sizeof(szValueData
) / sizeof(szValueData
[0]);
1364 lResult
= RegEnumValue(hSrcKey
, dwIndex
++, szValueName
, &cbName
, NULL
, &dwType
, szValueData
, &cbData
);
1365 if (lResult
== ERROR_SUCCESS
)
1367 lResult
= RegSetValueEx(hDestSubKey
, szValueName
, 0, dwType
, szValueData
, cbData
);
1372 while(lResult
== ERROR_SUCCESS
);
1374 lResult
= ERROR_SUCCESS
;
1378 RegCloseKey(hSrcSubKey
);
1380 RegCloseKey(hDestSubKey
);
1381 if (lResult
!= ERROR_SUCCESS
)
1382 SHDeleteKey(hDestKey
, lpDestSubKey
);
1387 LONG
RegMoveKey(HKEY hDestKey
, LPCTSTR lpDestSubKey
, HKEY hSrcKey
, LPCTSTR lpSrcSubKey
)
1392 return ERROR_INVALID_FUNCTION
;
1394 lResult
= RegCopyKey(hDestKey
, lpDestSubKey
, hSrcKey
, lpSrcSubKey
);
1395 if (lResult
== ERROR_SUCCESS
)
1396 SHDeleteKey(hSrcKey
, lpSrcSubKey
);
1401 LONG
RegRenameKey(HKEY hKey
, LPCTSTR lpSubKey
, LPCTSTR lpNewName
)
1404 LPTSTR lpNewSubKey
= NULL
;
1410 s
= _tcsrchr(lpSubKey
, _T('\\'));
1414 lpNewSubKey
= (LPTSTR
) HeapAlloc(GetProcessHeap(), 0, (s
- lpSubKey
+ _tcslen(lpNewName
) + 1) * sizeof(TCHAR
));
1415 if (lpNewSubKey
!= NULL
)
1417 memcpy(lpNewSubKey
, lpSubKey
, (s
- lpSubKey
) * sizeof(TCHAR
));
1418 _tcscpy(lpNewSubKey
+ (s
- lpSubKey
), lpNewName
);
1419 lpNewName
= lpNewSubKey
;
1422 return ERROR_NOT_ENOUGH_MEMORY
;
1425 Ret
= RegMoveKey(hKey
, lpNewName
, hKey
, lpSubKey
);
1429 HeapFree(GetProcessHeap(), 0, lpNewSubKey
);
1434 LONG
RegRenameValue(HKEY hKey
, LPCTSTR lpSubKey
, LPCTSTR lpDestValue
, LPCTSTR lpSrcValue
)
1437 HKEY hSubKey
= NULL
;
1438 DWORD dwType
, cbData
;
1443 lResult
= RegOpenKey(hKey
, lpSubKey
, &hSubKey
);
1444 if (lResult
!= ERROR_SUCCESS
)
1449 cbData
= sizeof(data
);
1450 lResult
= RegQueryValueEx(hKey
, lpSrcValue
, NULL
, &dwType
, data
, &cbData
);
1451 if (lResult
!= ERROR_SUCCESS
)
1454 lResult
= RegSetValueEx(hKey
, lpDestValue
, 0, dwType
, data
, cbData
);
1455 if (lResult
!= ERROR_SUCCESS
)
1458 RegDeleteValue(hKey
, lpSrcValue
);
1462 RegCloseKey(hSubKey
);
1466 LONG
RegQueryStringValue(HKEY hKey
, LPCTSTR lpSubKey
, LPCTSTR lpValueName
, LPTSTR pszBuffer
, DWORD dwBufferLen
)
1469 HKEY hSubKey
= NULL
;
1470 DWORD cbData
, dwType
;
1474 lResult
= RegOpenKey(hKey
, lpSubKey
, &hSubKey
);
1475 if (lResult
!= ERROR_SUCCESS
)
1480 cbData
= (dwBufferLen
- 1) * sizeof(*pszBuffer
);
1481 lResult
= RegQueryValueEx(hKey
, lpValueName
, NULL
, &dwType
, (LPBYTE
) pszBuffer
, &cbData
);
1482 if (lResult
!= ERROR_SUCCESS
)
1484 if (dwType
!= REG_SZ
)
1490 pszBuffer
[cbData
/ sizeof(*pszBuffer
)] = '\0';
1493 if (lResult
!= ERROR_SUCCESS
)
1494 pszBuffer
[0] = '\0';
1496 RegCloseKey(hSubKey
);
1500 /******************************************************************************
1504 static LONG
RegNextKey(HKEY hKey
, LPTSTR lpSubKey
, size_t iSubKeyLength
)
1508 LPCTSTR pszOriginalKey
;
1509 TCHAR szKeyName
[256];
1510 HKEY hSubKey
, hBaseKey
;
1514 BOOL bFoundKey
= FALSE
;
1516 /* Try accessing a subkey */
1517 if (RegOpenKeyEx(hKey
, lpSubKey
, 0, KEY_ALL_ACCESS
, &hSubKey
) == ERROR_SUCCESS
)
1519 cbName
= (DWORD
) iSubKeyLength
- _tcslen(lpSubKey
) - 1;
1520 lResult
= RegEnumKeyEx(hSubKey
, 0, lpSubKey
+ _tcslen(lpSubKey
) + 1,
1521 &cbName
, NULL
, NULL
, NULL
, &ft
);
1522 RegCloseKey(hSubKey
);
1524 if (lResult
== ERROR_SUCCESS
)
1526 lpSubKey
[_tcslen(lpSubKey
)] = '\\';
1533 /* Go up and find the next sibling key */
1536 s
= _tcsrchr(lpSubKey
, TEXT('\\'));
1540 pszOriginalKey
= s
+ 1;
1543 RegOpenKeyEx(hKey
, lpSubKey
, 0, KEY_ALL_ACCESS
, &hBaseKey
);
1547 pszOriginalKey
= lpSubKey
;
1556 lResult
= RegEnumKey(hBaseKey
, dwIndex
++, szKeyName
, sizeof(szKeyName
) / sizeof(szKeyName
[0]));
1558 while((lResult
== ERROR_SUCCESS
) && _tcscmp(szKeyName
, pszOriginalKey
));
1560 if (lResult
== ERROR_SUCCESS
)
1562 lResult
= RegEnumKey(hBaseKey
, dwIndex
++, szKeyName
, sizeof(szKeyName
) / sizeof(szKeyName
[0]));
1563 if (lResult
== ERROR_SUCCESS
)
1566 _sntprintf(lpSubKey
+ _tcslen(lpSubKey
), iSubKeyLength
- _tcslen(lpSubKey
), _T("\\%s"), szKeyName
);
1569 RegCloseKey(hBaseKey
);
1574 return bFoundKey
? ERROR_SUCCESS
: ERROR_NO_MORE_ITEMS
;
1577 static BOOL
RegSearchCompare(LPCTSTR s1
, LPCTSTR s2
, DWORD dwSearchFlags
)
1580 if (dwSearchFlags
& RSF_WHOLESTRING
)
1582 if (dwSearchFlags
& RSF_MATCHCASE
)
1583 bResult
= !_tcscmp(s1
, s2
);
1585 bResult
= !_tcsicmp(s1
, s2
);
1589 if (dwSearchFlags
& RSF_MATCHCASE
)
1590 bResult
= (_tcsstr(s1
, s2
) != NULL
);
1593 /* My kingdom for _tcsistr() */
1597 if (!_tcsnicmp(s1
, s2
, _tcslen(s2
)))
1609 LONG
RegSearch(HKEY hKey
, LPTSTR lpSubKey
, size_t iSubKeyLength
,
1610 LPCTSTR pszSearchString
, DWORD dwValueIndex
,
1611 DWORD dwSearchFlags
, BOOL (*pfnCallback
)(LPVOID
), LPVOID lpParam
)
1616 UNREFERENCED_PARAMETER(dwValueIndex
);
1618 if (dwSearchFlags
& (RSF_LOOKATVALUES
| RSF_LOOKATDATA
))
1619 return ERROR_CALL_NOT_IMPLEMENTED
; /* NYI */
1625 if (pfnCallback(lpParam
))
1626 return ERROR_OPERATION_ABORTED
;
1629 lResult
= RegNextKey(hKey
, lpSubKey
, iSubKeyLength
);
1630 if (lResult
!= ERROR_SUCCESS
)
1633 s
= _tcsrchr(lpSubKey
, TEXT('\\'));
1634 s
= s
? s
+ 1 : lpSubKey
;
1636 while(!(dwSearchFlags
& RSF_LOOKATKEYS
) || !RegSearchCompare(s
, pszSearchString
, dwSearchFlags
));
1638 return ERROR_SUCCESS
;
1641 /******************************************************************************
1642 * Key naming and parsing
1645 BOOL
RegKeyGetName(LPTSTR pszDest
, size_t iDestLength
, HKEY hRootKey
, LPCTSTR lpSubKey
)
1649 if (hRootKey
== HKEY_CLASSES_ROOT
)
1650 pszRootKey
= TEXT("HKEY_CLASSES_ROOT");
1651 else if (hRootKey
== HKEY_CURRENT_USER
)
1652 pszRootKey
= TEXT("HKEY_CURRENT_USER");
1653 else if (hRootKey
== HKEY_LOCAL_MACHINE
)
1654 pszRootKey
= TEXT("HKEY_LOCAL_MACHINE");
1655 else if (hRootKey
== HKEY_USERS
)
1656 pszRootKey
= TEXT("HKEY_USERS");
1657 else if (hRootKey
== HKEY_CURRENT_CONFIG
)
1658 pszRootKey
= TEXT("HKEY_CURRENT_CONFIG");
1659 else if (hRootKey
== HKEY_DYN_DATA
)
1660 pszRootKey
= TEXT("HKEY_DYN_DATA");
1665 _sntprintf(pszDest
, iDestLength
, TEXT("%s\\%s"), pszRootKey
, lpSubKey
);
1667 _sntprintf(pszDest
, iDestLength
, TEXT("%s"), pszRootKey
);