2 * Registry processing routines. Routines, common for registry
3 * processing frontends.
5 * Copyright 1999 Sylvain St-Germain
6 * Copyright 2002 Andriy Palamarchuk
7 * Copyright 2008 Alexander N. Sørnes <alex@thehandofagony.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
33 #include <wine/unicode.h>
36 #define REG_VAL_BUF_SIZE 4096
38 /* maximal number of characters in hexadecimal data line,
39 * including the indentation, but not including the '\' character
41 #define REG_FILE_HEX_LINE_LEN (2 + 25 * 3)
43 extern const WCHAR
* reg_class_namesW
[];
45 static HKEY reg_class_keys
[] = {
46 HKEY_LOCAL_MACHINE
, HKEY_USERS
, HKEY_CLASSES_ROOT
,
47 HKEY_CURRENT_CONFIG
, HKEY_CURRENT_USER
, HKEY_DYN_DATA
50 #define REG_CLASS_NUMBER (sizeof(reg_class_keys) / sizeof(reg_class_keys[0]))
53 #define NOT_ENOUGH_MEMORY 1
56 /* processing macros */
58 /* common check of memory allocation results */
59 #define CHECK_ENOUGH_MEMORY(p) \
62 fprintf(stderr,"%s: file %s, line %d: Not enough memory\n", \
63 getAppName(), __FILE__, __LINE__); \
64 exit(NOT_ENOUGH_MEMORY); \
67 /******************************************************************************
68 * Allocates memory and converts input from multibyte to wide chars
69 * Returned string must be freed by the caller
71 WCHAR
* GetWideString(const char* strA
)
76 int len
= MultiByteToWideChar(CP_ACP
, 0, strA
, -1, NULL
, 0);
78 strW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
79 CHECK_ENOUGH_MEMORY(strW
);
80 MultiByteToWideChar(CP_ACP
, 0, strA
, -1, strW
, len
);
86 /******************************************************************************
87 * Allocates memory and converts input from multibyte to wide chars
88 * Returned string must be freed by the caller
90 static WCHAR
* GetWideStringN(const char* strA
, int chars
, DWORD
*len
)
95 *len
= MultiByteToWideChar(CP_ACP
, 0, strA
, chars
, NULL
, 0);
97 strW
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(WCHAR
));
98 CHECK_ENOUGH_MEMORY(strW
);
99 MultiByteToWideChar(CP_ACP
, 0, strA
, chars
, strW
, *len
);
106 /******************************************************************************
107 * Allocates memory and converts input from wide chars to multibyte
108 * Returned string must be freed by the caller
110 char* GetMultiByteString(const WCHAR
* strW
)
115 int len
= WideCharToMultiByte(CP_ACP
, 0, strW
, -1, NULL
, 0, NULL
, NULL
);
117 strA
= HeapAlloc(GetProcessHeap(), 0, len
);
118 CHECK_ENOUGH_MEMORY(strA
);
119 WideCharToMultiByte(CP_ACP
, 0, strW
, -1, strA
, len
, NULL
, NULL
);
125 /******************************************************************************
126 * Allocates memory and converts input from wide chars to multibyte
127 * Returned string must be freed by the caller
129 static char* GetMultiByteStringN(const WCHAR
* strW
, int chars
, DWORD
* len
)
134 *len
= WideCharToMultiByte(CP_ACP
, 0, strW
, chars
, NULL
, 0, NULL
, NULL
);
136 strA
= HeapAlloc(GetProcessHeap(), 0, *len
);
137 CHECK_ENOUGH_MEMORY(strA
);
138 WideCharToMultiByte(CP_ACP
, 0, strW
, chars
, strA
, *len
, NULL
, NULL
);
145 /******************************************************************************
146 * Converts a hex representation of a DWORD into a DWORD.
148 static BOOL
convertHexToDWord(WCHAR
* str
, DWORD
*dw
)
153 WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, 9, NULL
, NULL
);
154 if (lstrlenW(str
) > 8 || sscanf(buf
, "%x%c", dw
, &dummy
) != 1) {
155 fprintf(stderr
,"%s: ERROR, invalid hex value\n", getAppName());
161 /******************************************************************************
162 * Converts a hex comma separated values list into a binary string.
164 static BYTE
* convertHexCSVToHex(WCHAR
*str
, DWORD
*size
)
169 /* The worst case is 1 digit + 1 comma per byte */
170 *size
=(lstrlenW(str
)+1)/2;
171 data
=HeapAlloc(GetProcessHeap(), 0, *size
);
172 CHECK_ENOUGH_MEMORY(data
);
181 wc
= strtoulW(s
,&end
,16);
182 if (end
== s
|| wc
> 0xff || (*end
&& *end
!= ',')) {
183 char* strA
= GetMultiByteString(s
);
184 fprintf(stderr
,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
186 HeapFree(GetProcessHeap(), 0, data
);
187 HeapFree(GetProcessHeap(), 0, strA
);
199 /******************************************************************************
200 * This function returns the HKEY associated with the data type encoded in the
201 * value. It modifies the input parameter (key value) in order to skip this
202 * "now useless" data type information.
204 * Note: Updated based on the algorithm used in 'server/registry.c'
206 static DWORD
getDataType(LPWSTR
*lpValue
, DWORD
* parse_type
)
208 struct data_type
{ const WCHAR
*tag
; int len
; int type
; int parse_type
; };
210 static const WCHAR quote
[] = {'"'};
211 static const WCHAR str
[] = {'s','t','r',':','"'};
212 static const WCHAR str2
[] = {'s','t','r','(','2',')',':','"'};
213 static const WCHAR hex
[] = {'h','e','x',':'};
214 static const WCHAR dword
[] = {'d','w','o','r','d',':'};
215 static const WCHAR hexp
[] = {'h','e','x','('};
217 static const struct data_type data_types
[] = { /* actual type */ /* type to assume for parsing */
218 { quote
, 1, REG_SZ
, REG_SZ
},
219 { str
, 5, REG_SZ
, REG_SZ
},
220 { str2
, 8, REG_EXPAND_SZ
, REG_SZ
},
221 { hex
, 4, REG_BINARY
, REG_BINARY
},
222 { dword
, 6, REG_DWORD
, REG_DWORD
},
223 { hexp
, 4, -1, REG_BINARY
},
227 const struct data_type
*ptr
;
230 for (ptr
= data_types
; ptr
->tag
; ptr
++) {
231 if (strncmpW( ptr
->tag
, *lpValue
, ptr
->len
))
235 *parse_type
= ptr
->parse_type
;
241 /* "hex(xx):" is special */
242 type
= (int)strtoulW( *lpValue
, &end
, 16 );
243 if (**lpValue
=='\0' || *end
!=')' || *(end
+1)!=':') {
251 *parse_type
=REG_NONE
;
255 /******************************************************************************
256 * Replaces escape sequences with the characters.
258 static int REGPROC_unescape_string(WCHAR
* str
)
260 int str_idx
= 0; /* current character under analysis */
261 int val_idx
= 0; /* the last character of the unescaped string */
262 int len
= lstrlenW(str
);
263 for (str_idx
= 0; str_idx
< len
; str_idx
++, val_idx
++) {
264 if (str
[str_idx
] == '\\') {
266 switch (str
[str_idx
]) {
278 str
[val_idx
] = str
[str_idx
];
281 fprintf(stderr
,"Warning! Unrecognized escape sequence: \\%c'\n",
283 str
[val_idx
] = str
[str_idx
];
287 str
[val_idx
] = str
[str_idx
];
294 static BOOL
parseKeyName(LPWSTR lpKeyName
, HKEY
*hKey
, LPWSTR
*lpKeyPath
)
296 WCHAR
* lpSlash
= NULL
;
299 if (lpKeyName
== NULL
)
302 for(i
= 0; *(lpKeyName
+i
) != 0; i
++)
304 if(*(lpKeyName
+i
) == '\\')
306 lpSlash
= lpKeyName
+i
;
313 len
= lpSlash
-lpKeyName
;
317 len
= lstrlenW(lpKeyName
);
318 lpSlash
= lpKeyName
+len
;
322 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++) {
323 if (CompareStringW(LOCALE_USER_DEFAULT
, 0, lpKeyName
, len
, reg_class_namesW
[i
], -1) == CSTR_EQUAL
&&
324 len
== lstrlenW(reg_class_namesW
[i
])) {
325 *hKey
= reg_class_keys
[i
];
334 if (*lpSlash
!= '\0')
336 *lpKeyPath
= lpSlash
;
340 /* Globals used by the setValue() & co */
341 static LPSTR currentKeyName
;
342 static HKEY currentKeyHandle
= NULL
;
344 /******************************************************************************
345 * Sets the value with name val_name to the data in val_data for the currently
349 * val_name - name of the registry value
350 * val_data - registry value data
352 static LONG
setValue(WCHAR
* val_name
, WCHAR
* val_data
, BOOL is_unicode
)
355 DWORD dwDataType
, dwParseType
;
358 WCHAR del
[] = {'-',0};
360 if ( (val_name
== NULL
) || (val_data
== NULL
) )
361 return ERROR_INVALID_PARAMETER
;
363 if (lstrcmpW(val_data
, del
) == 0)
365 res
=RegDeleteValueW(currentKeyHandle
,val_name
);
366 return (res
== ERROR_FILE_NOT_FOUND
? ERROR_SUCCESS
: res
);
369 /* Get the data type stored into the value field */
370 dwDataType
= getDataType(&val_data
, &dwParseType
);
372 if (dwParseType
== REG_SZ
) /* no conversion for string */
374 dwLen
= REGPROC_unescape_string(val_data
);
375 if(!dwLen
|| val_data
[dwLen
-1] != '"')
376 return ERROR_INVALID_DATA
;
377 val_data
[dwLen
-1] = '\0'; /* remove last quotes */
378 lpbData
= (BYTE
*) val_data
;
379 dwLen
++; /* include terminating null */
380 dwLen
= dwLen
* sizeof(WCHAR
); /* size is in bytes */
382 else if (dwParseType
== REG_DWORD
) /* Convert the dword types */
384 if (!convertHexToDWord(val_data
, &dwData
))
385 return ERROR_INVALID_DATA
;
386 lpbData
= (BYTE
*)&dwData
;
387 dwLen
= sizeof(dwData
);
389 else if (dwParseType
== REG_BINARY
) /* Convert the binary data */
391 lpbData
= convertHexCSVToHex(val_data
, &dwLen
);
393 return ERROR_INVALID_DATA
;
395 if((dwDataType
== REG_MULTI_SZ
|| dwDataType
== REG_EXPAND_SZ
) && !is_unicode
)
397 LPBYTE tmp
= lpbData
;
398 lpbData
= (LPBYTE
)GetWideStringN((char*)lpbData
, dwLen
, &dwLen
);
399 dwLen
*= sizeof(WCHAR
);
400 HeapFree(GetProcessHeap(), 0, tmp
);
403 else /* unknown format */
405 fprintf(stderr
,"%s: ERROR, unknown data format\n", getAppName());
406 return ERROR_INVALID_DATA
;
409 res
= RegSetValueExW(
416 if (dwParseType
== REG_BINARY
)
417 HeapFree(GetProcessHeap(), 0, lpbData
);
421 /******************************************************************************
422 * A helper function for processRegEntry() that opens the current key.
423 * That key must be closed by calling closeKey().
425 static LONG
openKeyW(WCHAR
* stdInput
)
433 if (stdInput
== NULL
)
434 return ERROR_INVALID_PARAMETER
;
436 /* Get the registry class */
437 if (!parseKeyName(stdInput
, &keyClass
, &keyPath
))
438 return ERROR_INVALID_PARAMETER
;
440 res
= RegCreateKeyExW(
441 keyClass
, /* Class */
442 keyPath
, /* Sub Key */
444 NULL
, /* object type */
445 REG_OPTION_NON_VOLATILE
, /* option, REG_OPTION_NON_VOLATILE ... */
446 KEY_ALL_ACCESS
, /* access mask, KEY_ALL_ACCESS */
447 NULL
, /* security attribute */
448 ¤tKeyHandle
, /* result */
449 &dwDisp
); /* disposition, REG_CREATED_NEW_KEY or
450 REG_OPENED_EXISTING_KEY */
452 if (res
== ERROR_SUCCESS
)
453 currentKeyName
= GetMultiByteString(stdInput
);
455 currentKeyHandle
= NULL
;
461 /******************************************************************************
462 * Close the currently opened key.
464 static void closeKey(void)
466 if (currentKeyHandle
)
468 HeapFree(GetProcessHeap(), 0, currentKeyName
);
469 RegCloseKey(currentKeyHandle
);
470 currentKeyHandle
= NULL
;
474 /******************************************************************************
475 * This function is a wrapper for the setValue function. It prepares the
476 * land and cleans the area once completed.
477 * Note: this function modifies the line parameter.
479 * line - registry file unwrapped line. Should have the registry value name and
480 * complete registry value data.
482 static void processSetValue(WCHAR
* line
, BOOL is_unicode
)
484 WCHAR
* val_name
; /* registry value name */
485 WCHAR
* val_data
; /* registry value data */
486 int line_idx
= 0; /* current character under analysis */
490 while ( isspaceW(line
[line_idx
]) ) line_idx
++;
491 if (line
[line_idx
] == '@' && line
[line_idx
+ 1] == '=') {
492 line
[line_idx
] = '\0';
495 } else if (line
[line_idx
] == '\"') {
497 val_name
= line
+ line_idx
;
498 while (line
[line_idx
]) {
499 if (line
[line_idx
] == '\\') /* skip escaped character */
503 if (line
[line_idx
] == '\"') {
504 line
[line_idx
] = '\0';
512 while ( isspaceW(line
[line_idx
]) ) line_idx
++;
513 if (!line
[line_idx
]) {
514 fprintf(stderr
, "%s: warning: unexpected EOL\n", getAppName());
517 if (line
[line_idx
] != '=') {
519 line
[line_idx
] = '\"';
520 lineA
= GetMultiByteString(line
);
521 fprintf(stderr
,"%s: warning: unrecognized line: '%s'\n", getAppName(), lineA
);
522 HeapFree(GetProcessHeap(), 0, lineA
);
527 char* lineA
= GetMultiByteString(line
);
528 fprintf(stderr
,"%s: warning: unrecognized line: '%s'\n", getAppName(), lineA
);
529 HeapFree(GetProcessHeap(), 0, lineA
);
532 line_idx
++; /* skip the '=' character */
534 while ( isspaceW(line
[line_idx
]) ) line_idx
++;
535 val_data
= line
+ line_idx
;
536 /* trim trailing blanks */
537 line_idx
= strlenW(val_data
);
538 while (line_idx
> 0 && isspaceW(val_data
[line_idx
-1])) line_idx
--;
539 val_data
[line_idx
] = '\0';
541 REGPROC_unescape_string(val_name
);
542 res
= setValue(val_name
, val_data
, is_unicode
);
543 if ( res
!= ERROR_SUCCESS
)
545 char* val_nameA
= GetMultiByteString(val_name
);
546 char* val_dataA
= GetMultiByteString(val_data
);
547 fprintf(stderr
,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
552 HeapFree(GetProcessHeap(), 0, val_nameA
);
553 HeapFree(GetProcessHeap(), 0, val_dataA
);
557 /******************************************************************************
558 * This function receives the currently read entry and performs the
559 * corresponding action.
560 * isUnicode affects parsing of REG_MULTI_SZ values
562 static void processRegEntry(WCHAR
* stdInput
, BOOL isUnicode
)
565 * We encountered the end of the file, make sure we
566 * close the opened key and exit
568 if (stdInput
== NULL
) {
573 if ( stdInput
[0] == '[') /* We are reading a new key */
576 closeKey(); /* Close the previous key */
578 /* Get rid of the square brackets */
580 keyEnd
= strrchrW(stdInput
, ']');
584 /* delete the key if we encounter '-' at the start of reg key */
585 if ( stdInput
[0] == '-')
587 delete_registry_key(stdInput
+ 1);
588 } else if ( openKeyW(stdInput
) != ERROR_SUCCESS
)
590 char* stdInputA
= GetMultiByteString(stdInput
);
591 fprintf(stderr
,"%s: setValue failed to open key %s\n",
592 getAppName(), stdInputA
);
593 HeapFree(GetProcessHeap(), 0, stdInputA
);
595 } else if( currentKeyHandle
&&
596 (( stdInput
[0] == '@') || /* reading a default @=data pair */
597 ( stdInput
[0] == '\"'))) /* reading a new value=data pair */
599 processSetValue(stdInput
, isUnicode
);
602 /* Since we are assuming that the file format is valid we must be
603 * reading a blank line which indicates the end of this key processing
609 /******************************************************************************
610 * Processes a registry file.
611 * Correctly processes comments (in # and ; form), line continuation.
614 * in - input stream to read from
615 * first_chars - beginning of stream, read due to Unicode check
617 static void processRegLinesA(FILE *in
, char* first_chars
)
619 LPSTR line
= NULL
; /* line read from input stream */
620 ULONG lineSize
= REG_VAL_BUF_SIZE
;
622 line
= HeapAlloc(GetProcessHeap(), 0, lineSize
);
623 CHECK_ENOUGH_MEMORY(line
);
624 memcpy(line
, first_chars
, 2);
627 LPSTR s
; /* The pointer into line for where the current fgets should read */
638 size_t size_remaining
;
640 char *s_eol
; /* various local uses */
642 /* Do we need to expand the buffer ? */
643 assert (s
>= line
&& s
<= line
+ lineSize
);
644 size_remaining
= lineSize
- (s
-line
);
645 if (size_remaining
< 2) /* room for 1 character and the \0 */
648 size_t new_size
= lineSize
+ REG_VAL_BUF_SIZE
;
649 if (new_size
> lineSize
) /* no arithmetic overflow */
650 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, line
, new_size
);
653 CHECK_ENOUGH_MEMORY(new_buffer
);
655 s
= line
+ lineSize
- size_remaining
;
657 size_remaining
= lineSize
- (s
-line
);
660 /* Get as much as possible into the buffer, terminated either by
661 * eof, error, eol or getting the maximum amount. Abort on error.
663 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
665 /* get a single line. note that `i' must be one past the last
666 * meaningful character in `s' when this loop exits */
667 for(i
= 0; i
< size_to_get
-1; ++i
){
674 perror("While reading input");
681 /* read the next character iff it's \n */
682 if(i
+2 >= size_to_get
){
683 /* buffer too short, so put back the EOL char to
703 /* If we didn't read the eol nor the eof go around for the rest */
704 s_eol
= strpbrk (s
, "\r\n");
705 if (!feof (in
) && !s_eol
) {
706 s
= strchr (s
, '\0');
710 /* If it is a comment line then discard it and go around again */
711 if (line
[0] == '#' || line
[0] == ';') {
716 /* Remove any line feed. Leave s_eol on the first \0 */
718 if (*s_eol
== '\r' && *(s_eol
+1) == '\n')
722 s_eol
= strchr (s
, '\0');
724 /* If there is a concatenating \\ then go around again */
725 if (s_eol
> line
&& *(s_eol
-1) == '\\') {
732 } while(c
== ' ' || c
== '\t');
736 fprintf(stderr
,"%s: ERROR - invalid continuation.\n",
747 lineW
= GetWideString(line
);
749 break; /* That is the full virtual line */
752 processRegEntry(lineW
, FALSE
);
753 HeapFree(GetProcessHeap(), 0, lineW
);
755 processRegEntry(NULL
, FALSE
);
757 HeapFree(GetProcessHeap(), 0, line
);
760 static void processRegLinesW(FILE *in
)
762 WCHAR
* buf
= NULL
; /* line read from input stream */
763 ULONG lineSize
= REG_VAL_BUF_SIZE
;
764 size_t CharsInBuf
= -1;
766 WCHAR
* s
; /* The pointer into buf for where the current fgets should read */
767 WCHAR
* line
; /* The start of the current line */
769 buf
= HeapAlloc(GetProcessHeap(), 0, lineSize
* sizeof(WCHAR
));
770 CHECK_ENOUGH_MEMORY(buf
);
776 size_t size_remaining
;
778 WCHAR
*s_eol
= NULL
; /* various local uses */
780 /* Do we need to expand the buffer ? */
781 assert (s
>= buf
&& s
<= buf
+ lineSize
);
782 size_remaining
= lineSize
- (s
-buf
);
783 if (size_remaining
< 2) /* room for 1 character and the \0 */
786 size_t new_size
= lineSize
+ (REG_VAL_BUF_SIZE
/ sizeof(WCHAR
));
787 if (new_size
> lineSize
) /* no arithmetic overflow */
788 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, buf
, new_size
* sizeof(WCHAR
));
791 CHECK_ENOUGH_MEMORY(new_buffer
);
794 s
= buf
+ lineSize
- size_remaining
;
796 size_remaining
= lineSize
- (s
-buf
);
799 /* Get as much as possible into the buffer, terminated either by
800 * eof, error or getting the maximum amount. Abort on error.
802 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
804 CharsInBuf
= fread(s
, sizeof(WCHAR
), size_to_get
- 1, in
);
807 if (CharsInBuf
== 0) {
809 perror ("While reading input");
814 /* It is not clear to me from the definition that the
815 * contents of the buffer are well defined on detecting
816 * an eof without managing to read anything.
821 /* If we didn't read the eol nor the eof go around for the rest */
824 const WCHAR line_endings
[] = {'\r','\n',0};
825 s_eol
= strpbrkW(line
, line_endings
);
828 /* Move the stub of the line to the start of the buffer so
829 * we get the maximum space to read into, and so we don't
830 * have to recalculate 'line' if the buffer expands */
831 MoveMemory(buf
, line
, (strlenW(line
)+1) * sizeof(WCHAR
));
833 s
= strchrW(line
, '\0');
837 /* If it is a comment line then discard it and go around again */
838 if (*line
== '#' || *line
== ';') {
839 if (*s_eol
== '\r' && *(s_eol
+1) == '\n')
846 /* If there is a concatenating \\ then go around again */
847 if (*(s_eol
-1) == '\\') {
848 WCHAR
* NextLine
= s_eol
+ 1;
850 if(*s_eol
== '\r' && *(s_eol
+1) == '\n')
853 while(*(NextLine
+1) == ' ' || *(NextLine
+1) == '\t')
856 MoveMemory(s_eol
- 1, NextLine
, (CharsInBuf
- (NextLine
- s
) + 1)*sizeof(WCHAR
));
857 CharsInBuf
-= NextLine
- s_eol
+ 1;
862 /* Remove any line feed. Leave s_eol on the last \0 */
863 if (*s_eol
== '\r' && *(s_eol
+ 1) == '\n')
867 processRegEntry(line
, TRUE
);
870 continue; /* That is the full virtual line */
874 processRegEntry(NULL
, TRUE
);
876 HeapFree(GetProcessHeap(), 0, buf
);
879 /****************************************************************************
880 * REGPROC_print_error
882 * Print the message for GetLastError
885 static void REGPROC_print_error(void)
891 error_code
= GetLastError ();
892 status
= FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
893 NULL
, error_code
, 0, (LPSTR
) &lpMsgBuf
, 0, NULL
);
895 fprintf(stderr
,"%s: Cannot display message for error %d, status %d\n",
896 getAppName(), error_code
, GetLastError());
904 /******************************************************************************
905 * Checks whether the buffer has enough room for the string or required size.
906 * Resizes the buffer if necessary.
909 * buffer - pointer to a buffer for string
910 * len - current length of the buffer in characters.
911 * required_len - length of the string to place to the buffer in characters.
912 * The length does not include the terminating null character.
914 static void REGPROC_resize_char_buffer(WCHAR
**buffer
, DWORD
*len
, DWORD required_len
)
917 if (required_len
> *len
) {
920 *buffer
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(**buffer
));
922 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *len
* sizeof(**buffer
));
923 CHECK_ENOUGH_MEMORY(*buffer
);
927 /******************************************************************************
928 * Same as REGPROC_resize_char_buffer() but on a regular buffer.
931 * buffer - pointer to a buffer
932 * len - current size of the buffer in bytes
933 * required_size - size of the data to place in the buffer in bytes
935 static void REGPROC_resize_binary_buffer(BYTE
**buffer
, DWORD
*size
, DWORD required_size
)
937 if (required_size
> *size
) {
938 *size
= required_size
;
940 *buffer
= HeapAlloc(GetProcessHeap(), 0, *size
);
942 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *size
);
943 CHECK_ENOUGH_MEMORY(*buffer
);
947 /******************************************************************************
948 * Prints string str to file
950 static void REGPROC_export_string(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, WCHAR
*str
, DWORD str_len
)
955 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ 10);
957 /* escaping characters */
959 for (i
= 0; i
< str_len
; i
++) {
964 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
965 (*line_buf
)[pos
++] = '\\';
966 (*line_buf
)[pos
++] = 'n';
971 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
972 (*line_buf
)[pos
++] = '\\';
973 (*line_buf
)[pos
++] = 'r';
979 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
980 (*line_buf
)[pos
++] = '\\';
984 (*line_buf
)[pos
++] = c
;
988 (*line_buf
)[pos
] = '\0';
992 static void REGPROC_export_binary(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, DWORD type
, BYTE
*value
, DWORD value_size
, BOOL unicode
)
994 DWORD hex_pos
, data_pos
;
995 const WCHAR
*hex_prefix
;
996 const WCHAR hex
[] = {'h','e','x',':',0};
998 const WCHAR concat
[] = {'\\','\r','\n',' ',' ',0};
999 DWORD concat_prefix
, concat_len
;
1000 const WCHAR newline
[] = {'\r','\n',0};
1001 CHAR
* value_multibyte
= NULL
;
1003 if (type
== REG_BINARY
) {
1006 const WCHAR hex_format
[] = {'h','e','x','(','%','x',')',':',0};
1007 hex_prefix
= hex_buf
;
1008 sprintfW(hex_buf
, hex_format
, type
);
1009 if ((type
== REG_SZ
|| type
== REG_EXPAND_SZ
|| type
== REG_MULTI_SZ
) && !unicode
)
1011 value_multibyte
= GetMultiByteStringN((WCHAR
*)value
, value_size
/ sizeof(WCHAR
), &value_size
);
1012 value
= (BYTE
*)value_multibyte
;
1016 concat_len
= lstrlenW(concat
);
1019 hex_pos
= *line_len
;
1020 *line_len
+= lstrlenW(hex_prefix
);
1021 data_pos
= *line_len
;
1022 *line_len
+= value_size
* 3;
1023 /* - The 2 spaces that concat places at the start of the
1024 * line effectively reduce the space available for data.
1025 * - If the value name and hex prefix are very long
1026 * ( > REG_FILE_HEX_LINE_LEN) or *line_len divides
1027 * without a remainder then we may overestimate
1028 * the needed number of lines by one. But that's ok.
1029 * - The trailing '\r' takes the place of a comma so
1030 * we only need to add 1 for the trailing '\n'
1032 *line_len
+= *line_len
/ (REG_FILE_HEX_LINE_LEN
- concat_prefix
) * concat_len
+ 1;
1033 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
);
1034 lstrcpyW(*line_buf
+ hex_pos
, hex_prefix
);
1037 const WCHAR format
[] = {'%','0','2','x',0};
1040 column
= data_pos
; /* no line wrap yet */
1044 sprintfW(*line_buf
+ data_pos
, format
, (unsigned int)value
[i
]);
1046 if (++i
== value_size
)
1049 (*line_buf
)[data_pos
++] = ',';
1053 if (column
>= REG_FILE_HEX_LINE_LEN
) {
1054 lstrcpyW(*line_buf
+ data_pos
, concat
);
1055 data_pos
+= concat_len
;
1056 column
= concat_prefix
;
1060 lstrcpyW(*line_buf
+ data_pos
, newline
);
1061 HeapFree(GetProcessHeap(), 0, value_multibyte
);
1064 /******************************************************************************
1065 * Writes the given line to a file, in multi-byte or wide characters
1067 static void REGPROC_write_line(FILE *file
, const WCHAR
* str
, BOOL unicode
)
1071 fwrite(str
, sizeof(WCHAR
), lstrlenW(str
), file
);
1074 char* strA
= GetMultiByteString(str
);
1076 HeapFree(GetProcessHeap(), 0, strA
);
1080 /******************************************************************************
1081 * Writes contents of the registry key to the specified file stream.
1084 * file - writable file stream to export registry branch to.
1085 * key - registry branch to export.
1086 * reg_key_name_buf - name of the key with registry class.
1087 * Is resized if necessary.
1088 * reg_key_name_size - length of the buffer for the registry class in characters.
1089 * val_name_buf - buffer for storing value name.
1090 * Is resized if necessary.
1091 * val_name_size - length of the buffer for storing value names in characters.
1092 * val_buf - buffer for storing values while extracting.
1093 * Is resized if necessary.
1094 * val_size - size of the buffer for storing values in bytes.
1096 static void export_hkey(FILE *file
, HKEY key
,
1097 WCHAR
**reg_key_name_buf
, DWORD
*reg_key_name_size
,
1098 WCHAR
**val_name_buf
, DWORD
*val_name_size
,
1099 BYTE
**val_buf
, DWORD
*val_size
,
1100 WCHAR
**line_buf
, DWORD
*line_buf_size
,
1103 DWORD max_sub_key_len
;
1104 DWORD max_val_name_len
;
1110 WCHAR key_format
[] = {'\r','\n','[','%','s',']','\r','\n',0};
1112 /* get size information and resize the buffers if necessary */
1113 if (RegQueryInfoKeyW(key
, NULL
, NULL
, NULL
, NULL
,
1114 &max_sub_key_len
, NULL
,
1115 NULL
, &max_val_name_len
, &max_val_size
, NULL
, NULL
1116 ) != ERROR_SUCCESS
) {
1117 REGPROC_print_error();
1119 curr_len
= strlenW(*reg_key_name_buf
);
1120 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
,
1121 max_sub_key_len
+ curr_len
+ 1);
1122 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
,
1124 REGPROC_resize_binary_buffer(val_buf
, val_size
, max_val_size
);
1125 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, lstrlenW(*reg_key_name_buf
) + 4);
1126 /* output data for the current key */
1127 sprintfW(*line_buf
, key_format
, *reg_key_name_buf
);
1128 REGPROC_write_line(file
, *line_buf
, unicode
);
1130 /* print all the values */
1135 DWORD val_name_size1
= *val_name_size
;
1136 DWORD val_size1
= *val_size
;
1137 ret
= RegEnumValueW(key
, i
, *val_name_buf
, &val_name_size1
, NULL
,
1138 &value_type
, *val_buf
, &val_size1
);
1139 if (ret
== ERROR_MORE_DATA
) {
1140 /* Increase the size of the buffers and retry */
1141 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, val_name_size1
);
1142 REGPROC_resize_binary_buffer(val_buf
, val_size
, val_size1
);
1143 } else if (ret
!= ERROR_SUCCESS
) {
1145 if (ret
!= ERROR_NO_MORE_ITEMS
) {
1146 REGPROC_print_error();
1152 if ((*val_name_buf
)[0]) {
1153 const WCHAR val_start
[] = {'"','%','s','"','=',0};
1156 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, *val_name_buf
, lstrlenW(*val_name_buf
));
1157 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, lstrlenW(*line_buf
) + 1);
1158 lstrcpyW(*val_name_buf
, *line_buf
);
1160 line_len
= 3 + lstrlenW(*val_name_buf
);
1161 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1162 sprintfW(*line_buf
, val_start
, *val_name_buf
);
1164 const WCHAR std_val
[] = {'@','=',0};
1166 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1167 lstrcpyW(*line_buf
, std_val
);
1170 switch (value_type
) {
1173 WCHAR
* wstr
= (WCHAR
*)*val_buf
;
1175 if (val_size1
< sizeof(WCHAR
) || val_size1
% sizeof(WCHAR
) ||
1176 wstr
[val_size1
/ sizeof(WCHAR
) - 1]) {
1177 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1179 const WCHAR start
[] = {'"',0};
1180 const WCHAR end
[] = {'"','\r','\n',0};
1183 len
= lstrlenW(start
);
1184 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ len
);
1185 lstrcpyW(*line_buf
+ line_len
, start
);
1188 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, wstr
, lstrlenW(wstr
));
1190 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ lstrlenW(end
));
1191 lstrcpyW(*line_buf
+ line_len
, end
);
1198 WCHAR format
[] = {'d','w','o','r','d',':','%','0','8','x','\r','\n',0};
1200 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ 15);
1201 sprintfW(*line_buf
+ line_len
, format
, *((DWORD
*)*val_buf
));
1207 char* key_nameA
= GetMultiByteString(*reg_key_name_buf
);
1208 char* value_nameA
= GetMultiByteString(*val_name_buf
);
1209 fprintf(stderr
,"%s: warning - unsupported registry format '%d', "
1210 "treat as binary\n",
1211 getAppName(), value_type
);
1212 fprintf(stderr
,"key name: \"%s\"\n", key_nameA
);
1213 fprintf(stderr
,"value name:\"%s\"\n\n", value_nameA
);
1214 HeapFree(GetProcessHeap(), 0, key_nameA
);
1215 HeapFree(GetProcessHeap(), 0, value_nameA
);
1222 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1224 REGPROC_write_line(file
, *line_buf
, unicode
);
1230 (*reg_key_name_buf
)[curr_len
] = '\\';
1232 DWORD buf_size
= *reg_key_name_size
- curr_len
- 1;
1234 ret
= RegEnumKeyExW(key
, i
, *reg_key_name_buf
+ curr_len
+ 1, &buf_size
,
1235 NULL
, NULL
, NULL
, NULL
);
1236 if (ret
== ERROR_MORE_DATA
) {
1237 /* Increase the size of the buffer and retry */
1238 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
, curr_len
+ 1 + buf_size
);
1239 } else if (ret
!= ERROR_SUCCESS
) {
1241 if (ret
!= ERROR_NO_MORE_ITEMS
) {
1242 REGPROC_print_error();
1248 if (RegOpenKeyW(key
, *reg_key_name_buf
+ curr_len
+ 1,
1249 &subkey
) == ERROR_SUCCESS
) {
1250 export_hkey(file
, subkey
, reg_key_name_buf
, reg_key_name_size
,
1251 val_name_buf
, val_name_size
, val_buf
, val_size
,
1252 line_buf
, line_buf_size
, unicode
);
1253 RegCloseKey(subkey
);
1255 REGPROC_print_error();
1259 (*reg_key_name_buf
)[curr_len
] = '\0';
1262 /******************************************************************************
1263 * Open file in binary mode for export.
1265 static FILE *REGPROC_open_export_file(WCHAR
*file_name
, BOOL unicode
)
1270 if (strncmpW(file_name
,&dash
,1)==0) {
1272 _setmode(_fileno(file
), _O_BINARY
);
1275 CHAR
* file_nameA
= GetMultiByteString(file_name
);
1276 file
= fopen(file_nameA
, "wb");
1279 fprintf(stderr
,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA
);
1280 HeapFree(GetProcessHeap(), 0, file_nameA
);
1283 HeapFree(GetProcessHeap(), 0, file_nameA
);
1287 const BYTE unicode_seq
[] = {0xff,0xfe};
1288 const WCHAR header
[] = {'W','i','n','d','o','w','s',' ','R','e','g','i','s','t','r','y',' ','E','d','i','t','o','r',' ','V','e','r','s','i','o','n',' ','5','.','0','0','\r','\n'};
1289 fwrite(unicode_seq
, sizeof(BYTE
), sizeof(unicode_seq
)/sizeof(unicode_seq
[0]), file
);
1290 fwrite(header
, sizeof(WCHAR
), sizeof(header
)/sizeof(header
[0]), file
);
1293 fputs("REGEDIT4\r\n", file
);
1299 /******************************************************************************
1300 * Writes contents of the registry key to the specified file stream.
1303 * file_name - name of a file to export registry branch to.
1304 * reg_key_name - registry branch to export. The whole registry is exported if
1305 * reg_key_name is NULL or contains an empty string.
1307 BOOL
export_registry_key(WCHAR
*file_name
, WCHAR
*reg_key_name
, DWORD format
)
1309 WCHAR
*reg_key_name_buf
;
1310 WCHAR
*val_name_buf
;
1313 DWORD reg_key_name_size
= KEY_MAX_LEN
;
1314 DWORD val_name_size
= KEY_MAX_LEN
;
1315 DWORD val_size
= REG_VAL_BUF_SIZE
;
1316 DWORD line_buf_size
= KEY_MAX_LEN
+ REG_VAL_BUF_SIZE
;
1318 BOOL unicode
= (format
== REG_FORMAT_5
);
1320 reg_key_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1321 reg_key_name_size
* sizeof(*reg_key_name_buf
));
1322 val_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1323 val_name_size
* sizeof(*val_name_buf
));
1324 val_buf
= HeapAlloc(GetProcessHeap(), 0, val_size
);
1325 line_buf
= HeapAlloc(GetProcessHeap(), 0, line_buf_size
* sizeof(*line_buf
));
1326 CHECK_ENOUGH_MEMORY(reg_key_name_buf
&& val_name_buf
&& val_buf
&& line_buf
);
1328 if (reg_key_name
&& reg_key_name
[0]) {
1330 WCHAR
*branch_name
= NULL
;
1333 REGPROC_resize_char_buffer(®_key_name_buf
, ®_key_name_size
,
1334 lstrlenW(reg_key_name
));
1335 lstrcpyW(reg_key_name_buf
, reg_key_name
);
1337 /* open the specified key */
1338 if (!parseKeyName(reg_key_name
, ®_key_class
, &branch_name
)) {
1339 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1340 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1341 getAppName(), key_nameA
);
1342 HeapFree(GetProcessHeap(), 0, key_nameA
);
1345 if (!branch_name
[0]) {
1346 /* no branch - registry class is specified */
1347 file
= REGPROC_open_export_file(file_name
, unicode
);
1348 export_hkey(file
, reg_key_class
,
1349 ®_key_name_buf
, ®_key_name_size
,
1350 &val_name_buf
, &val_name_size
,
1351 &val_buf
, &val_size
, &line_buf
,
1352 &line_buf_size
, unicode
);
1353 } else if (RegOpenKeyW(reg_key_class
, branch_name
, &key
) == ERROR_SUCCESS
) {
1354 file
= REGPROC_open_export_file(file_name
, unicode
);
1355 export_hkey(file
, key
,
1356 ®_key_name_buf
, ®_key_name_size
,
1357 &val_name_buf
, &val_name_size
,
1358 &val_buf
, &val_size
, &line_buf
,
1359 &line_buf_size
, unicode
);
1362 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1363 fprintf(stderr
,"%s: Can't export. Registry key '%s' does not exist!\n",
1364 getAppName(), key_nameA
);
1365 HeapFree(GetProcessHeap(), 0, key_nameA
);
1366 REGPROC_print_error();
1371 /* export all registry classes */
1372 file
= REGPROC_open_export_file(file_name
, unicode
);
1373 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++) {
1374 /* do not export HKEY_CLASSES_ROOT */
1375 if (reg_class_keys
[i
] != HKEY_CLASSES_ROOT
&&
1376 reg_class_keys
[i
] != HKEY_CURRENT_USER
&&
1377 reg_class_keys
[i
] != HKEY_CURRENT_CONFIG
&&
1378 reg_class_keys
[i
] != HKEY_DYN_DATA
) {
1379 lstrcpyW(reg_key_name_buf
, reg_class_namesW
[i
]);
1380 export_hkey(file
, reg_class_keys
[i
],
1381 ®_key_name_buf
, ®_key_name_size
,
1382 &val_name_buf
, &val_name_size
,
1383 &val_buf
, &val_size
, &line_buf
,
1384 &line_buf_size
, unicode
);
1392 HeapFree(GetProcessHeap(), 0, reg_key_name
);
1393 HeapFree(GetProcessHeap(), 0, val_name_buf
);
1394 HeapFree(GetProcessHeap(), 0, val_buf
);
1395 HeapFree(GetProcessHeap(), 0, line_buf
);
1399 /******************************************************************************
1400 * Reads contents of the specified file into the registry.
1402 BOOL
import_registry_file(FILE* reg_file
)
1407 if (fread( s
, 2, 1, reg_file
) == 1)
1409 if (s
[0] == 0xff && s
[1] == 0xfe)
1411 processRegLinesW(reg_file
);
1414 processRegLinesA(reg_file
, (char*)s
);
1422 /******************************************************************************
1423 * Removes the registry key with all subkeys. Parses full key name.
1426 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1427 * empty, points to register key class, does not exist.
1429 void delete_registry_key(WCHAR
*reg_key_name
)
1431 WCHAR
*key_name
= NULL
;
1434 if (!reg_key_name
|| !reg_key_name
[0])
1437 if (!parseKeyName(reg_key_name
, &key_class
, &key_name
)) {
1438 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1439 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1440 getAppName(), reg_key_nameA
);
1441 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1445 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1446 fprintf(stderr
,"%s: Can't delete registry class '%s'\n",
1447 getAppName(), reg_key_nameA
);
1448 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1452 RegDeleteTreeW(key_class
, key_name
);