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
26 #define REG_VAL_BUF_SIZE 4096
28 /* maximal number of characters in hexadecimal data line,
29 * including the indentation, but not including the '\' character
31 #define REG_FILE_HEX_LINE_LEN (2 + 25 * 3)
33 static const CHAR
*reg_class_names
[] = {
34 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
35 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
38 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
40 const WCHAR
* reg_class_namesW
[REG_CLASS_NUMBER
] = {
41 L
"HKEY_LOCAL_MACHINE", L
"HKEY_USERS", L
"HKEY_CLASSES_ROOT",
42 L
"HKEY_CURRENT_CONFIG", L
"HKEY_CURRENT_USER", L
"HKEY_DYN_DATA"
45 static HKEY reg_class_keys
[REG_CLASS_NUMBER
] = {
46 HKEY_LOCAL_MACHINE
, HKEY_USERS
, HKEY_CLASSES_ROOT
,
47 HKEY_CURRENT_CONFIG
, HKEY_CURRENT_USER
, HKEY_DYN_DATA
51 #define NOT_ENOUGH_MEMORY 1
54 /* processing macros */
56 /* common check of memory allocation results */
57 #define CHECK_ENOUGH_MEMORY(p) \
60 fprintf(stderr,"%s: file %s, line %d: Not enough memory\n", \
61 getAppName(), __FILE__, __LINE__); \
62 exit(NOT_ENOUGH_MEMORY); \
65 /******************************************************************************
66 * Allocates memory and converts input from multibyte to wide chars
67 * Returned string must be freed by the caller
69 WCHAR
* GetWideString(const char* strA
)
74 int len
= MultiByteToWideChar(CP_ACP
, 0, strA
, -1, NULL
, 0);
76 strW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
77 CHECK_ENOUGH_MEMORY(strW
);
78 MultiByteToWideChar(CP_ACP
, 0, strA
, -1, strW
, len
);
84 /******************************************************************************
85 * Allocates memory and converts input from multibyte to wide chars
86 * Returned string must be freed by the caller
88 static WCHAR
* GetWideStringN(const char* strA
, int chars
, DWORD
*len
)
93 *len
= MultiByteToWideChar(CP_ACP
, 0, strA
, chars
, NULL
, 0);
95 strW
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(WCHAR
));
96 CHECK_ENOUGH_MEMORY(strW
);
97 MultiByteToWideChar(CP_ACP
, 0, strA
, chars
, strW
, *len
);
104 /******************************************************************************
105 * Allocates memory and converts input from wide chars to multibyte
106 * Returned string must be freed by the caller
108 char* GetMultiByteString(const WCHAR
* strW
)
113 int len
= WideCharToMultiByte(CP_ACP
, 0, strW
, -1, NULL
, 0, NULL
, NULL
);
115 strA
= HeapAlloc(GetProcessHeap(), 0, len
);
116 CHECK_ENOUGH_MEMORY(strA
);
117 WideCharToMultiByte(CP_ACP
, 0, strW
, -1, strA
, len
, NULL
, NULL
);
123 /******************************************************************************
124 * Allocates memory and converts input from wide chars to multibyte
125 * Returned string must be freed by the caller
127 static char* GetMultiByteStringN(const WCHAR
* strW
, int chars
, DWORD
* len
)
132 *len
= WideCharToMultiByte(CP_ACP
, 0, strW
, chars
, NULL
, 0, NULL
, NULL
);
134 strA
= HeapAlloc(GetProcessHeap(), 0, *len
);
135 CHECK_ENOUGH_MEMORY(strA
);
136 WideCharToMultiByte(CP_ACP
, 0, strW
, chars
, strA
, *len
, NULL
, NULL
);
143 /******************************************************************************
144 * Converts a hex representation of a DWORD into a DWORD.
146 static BOOL
convertHexToDWord(WCHAR
* str
, DWORD
*dw
)
151 WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, 9, NULL
, NULL
);
152 if (lstrlenW(str
) > 8 || sscanf(buf
, "%lx%c", dw
, &dummy
) != 1) {
153 fprintf(stderr
,"%s: ERROR, invalid hex value\n", getAppName());
159 /******************************************************************************
160 * Converts a hex comma separated values list into a binary string.
162 static BYTE
* convertHexCSVToHex(WCHAR
*str
, DWORD
*size
)
167 /* The worst case is 1 digit + 1 comma per byte */
168 *size
=(lstrlenW(str
)+1)/2;
169 data
=HeapAlloc(GetProcessHeap(), 0, *size
);
170 CHECK_ENOUGH_MEMORY(data
);
179 wc
= wcstoul(s
,&end
, 16);
180 if (end
== s
|| wc
> 0xff || (*end
&& *end
!= L
',')) {
181 char* strA
= GetMultiByteString(s
);
182 fprintf(stderr
,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
184 HeapFree(GetProcessHeap(), 0, data
);
185 HeapFree(GetProcessHeap(), 0, strA
);
197 /******************************************************************************
198 * This function returns the HKEY associated with the data type encoded in the
199 * value. It modifies the input parameter (key value) in order to skip this
200 * "now useless" data type information.
202 * Note: Updated based on the algorithm used in 'server/registry.c'
204 static DWORD
getDataType(LPWSTR
*lpValue
, DWORD
* parse_type
)
206 struct data_type
{ const WCHAR
*tag
; int len
; int type
; int parse_type
; };
208 static const WCHAR quote
[] = {'"'};
209 static const WCHAR str
[] = {'s','t','r',':','"'};
210 static const WCHAR str2
[] = {'s','t','r','(','2',')',':','"'};
211 static const WCHAR hex
[] = {'h','e','x',':'};
212 static const WCHAR dword
[] = {'d','w','o','r','d',':'};
213 static const WCHAR hexp
[] = {'h','e','x','('};
215 static const struct data_type data_types
[] = { /* actual type */ /* type to assume for parsing */
216 { quote
, 1, REG_SZ
, REG_SZ
},
217 { str
, 5, REG_SZ
, REG_SZ
},
218 { str2
, 8, REG_EXPAND_SZ
, REG_SZ
},
219 { hex
, 4, REG_BINARY
, REG_BINARY
},
220 { dword
, 6, REG_DWORD
, REG_DWORD
},
221 { hexp
, 4, -1, REG_BINARY
},
225 const struct data_type
*ptr
;
228 for (ptr
= data_types
; ptr
->tag
; ptr
++) {
229 if (wcsncmp(ptr
->tag
, *lpValue
, ptr
->len
))
233 *parse_type
= ptr
->parse_type
;
239 /* "hex(xx):" is special */
240 type
= (int)wcstoul( *lpValue
, &end
, 16 );
241 if (**lpValue
=='\0' || *end
!=')' || *(end
+1)!=':') {
249 *parse_type
=REG_NONE
;
253 /******************************************************************************
254 * Replaces escape sequences with the characters.
256 static void REGPROC_unescape_string(WCHAR
* str
)
258 int str_idx
= 0; /* current character under analysis */
259 int val_idx
= 0; /* the last character of the unescaped string */
260 int len
= lstrlenW(str
);
261 for (str_idx
= 0; str_idx
< len
; str_idx
++, val_idx
++) {
262 if (str
[str_idx
] == '\\') {
264 switch (str
[str_idx
]) {
270 str
[val_idx
] = str
[str_idx
];
273 fprintf(stderr
,"Warning! Unrecognized escape sequence: \\%c'\n",
275 str
[val_idx
] = str
[str_idx
];
279 str
[val_idx
] = str
[str_idx
];
285 static BOOL
parseKeyName(LPWSTR lpKeyName
, HKEY
*hKey
, LPWSTR
*lpKeyPath
)
287 WCHAR
* lpSlash
= NULL
;
290 if (lpKeyName
== NULL
)
293 for(i
= 0; *(lpKeyName
+ i
) != 0; i
++)
295 if(*(lpKeyName
+i
) == '\\')
297 lpSlash
= lpKeyName
+ i
;
304 len
= lpSlash
-lpKeyName
;
308 len
= lstrlenW(lpKeyName
);
309 lpSlash
= lpKeyName
+len
;
313 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++) {
314 if (CompareStringW(LOCALE_USER_DEFAULT
, 0, lpKeyName
, len
, reg_class_namesW
[i
], len
) == CSTR_EQUAL
&&
315 len
== lstrlenW(reg_class_namesW
[i
])) {
316 *hKey
= reg_class_keys
[i
];
324 if (*lpSlash
!= '\0')
326 *lpKeyPath
= lpSlash
;
330 /* Globals used by the setValue() & co */
331 static LPSTR currentKeyName
;
332 static HKEY currentKeyHandle
= NULL
;
334 /******************************************************************************
335 * Sets the value with name val_name to the data in val_data for the currently
339 * val_name - name of the registry value
340 * val_data - registry value data
342 static LONG
setValue(WCHAR
* val_name
, WCHAR
* val_data
, BOOL is_unicode
)
345 DWORD dwDataType
, dwParseType
;
348 WCHAR del
[] = {'-',0};
350 if ( (val_name
== NULL
) || (val_data
== NULL
) )
351 return ERROR_INVALID_PARAMETER
;
353 if (lstrcmpW(val_data
, del
) == 0)
355 res
=RegDeleteValueW(currentKeyHandle
,val_name
);
356 return (res
== ERROR_FILE_NOT_FOUND
? ERROR_SUCCESS
: res
);
359 /* Get the data type stored into the value field */
360 dwDataType
= getDataType(&val_data
, &dwParseType
);
362 if (dwParseType
== REG_SZ
) /* no conversion for string */
364 REGPROC_unescape_string(val_data
);
365 /* Compute dwLen after REGPROC_unescape_string because it may
366 * have changed the string length and we don't want to store
367 * the extra garbage in the registry.
369 dwLen
= lstrlenW(val_data
);
370 if (dwLen
>0 && val_data
[dwLen
-1]=='"')
373 val_data
[dwLen
]='\0';
375 lpbData
= (BYTE
*) val_data
;
376 dwLen
++; /* include terminating null */
377 dwLen
= dwLen
* sizeof(WCHAR
); /* size is in bytes */
379 else if (dwParseType
== REG_DWORD
) /* Convert the dword types */
381 if (!convertHexToDWord(val_data
, &dwData
))
382 return ERROR_INVALID_DATA
;
383 lpbData
= (BYTE
*)&dwData
;
384 dwLen
= sizeof(dwData
);
386 else if (dwParseType
== REG_BINARY
) /* Convert the binary data */
388 lpbData
= convertHexCSVToHex(val_data
, &dwLen
);
390 return ERROR_INVALID_DATA
;
392 if((dwDataType
== REG_MULTI_SZ
|| dwDataType
== REG_EXPAND_SZ
) && !is_unicode
)
394 LPBYTE tmp
= lpbData
;
395 lpbData
= (LPBYTE
)GetWideStringN((char*)lpbData
, dwLen
, &dwLen
);
396 dwLen
*= sizeof(WCHAR
);
397 HeapFree(GetProcessHeap(), 0, tmp
);
400 else /* unknown format */
402 fprintf(stderr
,"%s: ERROR, unknown data format\n", getAppName());
403 return ERROR_INVALID_DATA
;
406 res
= RegSetValueExW(
413 if (dwParseType
== REG_BINARY
)
414 HeapFree(GetProcessHeap(), 0, lpbData
);
418 /******************************************************************************
419 * A helper function for processRegEntry() that opens the current key.
420 * That key must be closed by calling closeKey().
422 static LONG
openKeyW(WCHAR
* stdInput
)
430 if (stdInput
== NULL
)
431 return ERROR_INVALID_PARAMETER
;
433 /* Get the registry class */
434 if (!parseKeyName(stdInput
, &keyClass
, &keyPath
))
435 return ERROR_INVALID_PARAMETER
;
437 res
= RegCreateKeyExW(
438 keyClass
, /* Class */
439 keyPath
, /* Sub Key */
441 NULL
, /* object type */
442 REG_OPTION_NON_VOLATILE
, /* option, REG_OPTION_NON_VOLATILE ... */
443 KEY_ALL_ACCESS
, /* access mask, KEY_ALL_ACCESS */
444 NULL
, /* security attribute */
445 ¤tKeyHandle
, /* result */
446 &dwDisp
); /* disposition, REG_CREATED_NEW_KEY or
447 REG_OPENED_EXISTING_KEY */
449 if (res
== ERROR_SUCCESS
)
450 currentKeyName
= GetMultiByteString(stdInput
);
452 currentKeyHandle
= NULL
;
458 /******************************************************************************
459 * Close the currently opened key.
461 static void closeKey(void)
463 if (currentKeyHandle
)
465 HeapFree(GetProcessHeap(), 0, currentKeyName
);
466 RegCloseKey(currentKeyHandle
);
467 currentKeyHandle
= NULL
;
471 /******************************************************************************
472 * This function is a wrapper for the setValue function. It prepares the
473 * land and cleans the area once completed.
474 * Note: this function modifies the line parameter.
476 * line - registry file unwrapped line. Should have the registry value name and
477 * complete registry value data.
479 static void processSetValue(WCHAR
* line
, BOOL is_unicode
)
481 WCHAR
* val_name
; /* registry value name */
482 WCHAR
* val_data
; /* registry value data */
483 int line_idx
= 0; /* current character under analysis */
487 while ( iswspace(line
[line_idx
]) ) line_idx
++;
488 if (line
[line_idx
] == '@' && line
[line_idx
+ 1] == '=') {
489 line
[line_idx
] = '\0';
492 } else if (line
[line_idx
] == '\"') {
494 val_name
= line
+ line_idx
;
496 if (line
[line_idx
] == '\\') /* skip escaped character */
500 if (line
[line_idx
] == '\"') {
501 line
[line_idx
] = '\0';
509 while ( iswspace(line
[line_idx
]) ) line_idx
++;
510 if (line
[line_idx
] != '=') {
512 line
[line_idx
] = '\"';
513 lineA
= GetMultiByteString(line
);
514 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", lineA
);
515 HeapFree(GetProcessHeap(), 0, lineA
);
520 char* lineA
= GetMultiByteString(line
);
521 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", lineA
);
522 HeapFree(GetProcessHeap(), 0, lineA
);
525 line_idx
++; /* skip the '=' character */
527 while ( iswspace(line
[line_idx
]) ) line_idx
++;
528 val_data
= line
+ line_idx
;
529 /* trim trailing blanks */
530 line_idx
= lstrlenW(val_data
);
531 while (line_idx
> 0 && iswspace(val_data
[line_idx
-1])) line_idx
--;
532 val_data
[line_idx
] = '\0';
534 REGPROC_unescape_string(val_name
);
535 res
= setValue(val_name
, val_data
, is_unicode
);
536 if ( res
!= ERROR_SUCCESS
)
538 char* val_nameA
= GetMultiByteString(val_name
);
539 char* val_dataA
= GetMultiByteString(val_data
);
540 fprintf(stderr
,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
545 HeapFree(GetProcessHeap(), 0, val_nameA
);
546 HeapFree(GetProcessHeap(), 0, val_dataA
);
550 /******************************************************************************
551 * This function receives the currently read entry and performs the
552 * corresponding action.
553 * isUnicode affects parsing of REG_MULTI_SZ values
555 static void processRegEntry(WCHAR
* stdInput
, BOOL isUnicode
)
558 * We encountered the end of the file, make sure we
559 * close the opened key and exit
561 if (stdInput
== NULL
) {
566 if ( stdInput
[0] == L
'[') /* We are reading a new key */
569 closeKey(); /* Close the previous key */
571 /* Get rid of the square brackets */
573 keyEnd
= wcsrchr(stdInput
, L
']');
577 /* delete the key if we encounter '-' at the start of reg key */
578 if ( stdInput
[0] == '-')
580 delete_registry_key(stdInput
+ 1);
581 } else if ( openKeyW(stdInput
) != ERROR_SUCCESS
)
583 char* stdInputA
= GetMultiByteString(stdInput
);
584 fprintf(stderr
,"%s: setValue failed to open key %s\n",
585 getAppName(), stdInputA
);
586 HeapFree(GetProcessHeap(), 0, stdInputA
);
588 } else if( currentKeyHandle
&&
589 (( stdInput
[0] == '@') || /* reading a default @=data pair */
590 ( stdInput
[0] == '\"'))) /* reading a new value=data pair */
592 processSetValue(stdInput
, isUnicode
);
595 /* Since we are assuming that the file format is valid we must be
596 * reading a blank line which indicates the end of this key processing
602 /******************************************************************************
603 * Processes a registry file.
604 * Correctly processes comments (in # form), line continuation.
607 * in - input stream to read from
609 static void processRegLinesA(FILE *in
)
611 LPSTR line
= NULL
; /* line read from input stream */
612 ULONG lineSize
= REG_VAL_BUF_SIZE
;
614 line
= HeapAlloc(GetProcessHeap(), 0, lineSize
);
615 CHECK_ENOUGH_MEMORY(line
);
618 LPSTR s
; /* The pointer into line for where the current fgets should read */
624 size_t size_remaining
;
626 char *s_eol
; /* various local uses */
628 /* Do we need to expand the buffer ? */
629 assert (s
>= line
&& s
<= line
+ lineSize
);
630 size_remaining
= lineSize
- (s
-line
);
631 if (size_remaining
< 2) /* room for 1 character and the \0 */
634 size_t new_size
= lineSize
+ REG_VAL_BUF_SIZE
;
635 if (new_size
> lineSize
) /* no arithmetic overflow */
636 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, line
, new_size
);
639 CHECK_ENOUGH_MEMORY(new_buffer
);
641 s
= line
+ lineSize
- size_remaining
;
643 size_remaining
= lineSize
- (s
-line
);
646 /* Get as much as possible into the buffer, terminated either by
647 * eof, error, eol or getting the maximum amount. Abort on error.
649 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
651 check
= fgets (s
, size_to_get
, in
);
655 perror ("While reading input");
660 /* It is not clear to me from the definition that the
661 * contents of the buffer are well defined on detecting
662 * an eof without managing to read anything.
667 /* If we didn't read the eol nor the eof go around for the rest */
668 s_eol
= strchr (s
, '\n');
669 if (!feof (in
) && !s_eol
) {
670 s
= strchr (s
, '\0');
671 /* It should be s + size_to_get - 1 but this is safer */
675 /* If it is a comment line then discard it and go around again */
676 if (line
[0] == '#') {
681 /* Remove any line feed. Leave s_eol on the \0 */
684 if (s_eol
> line
&& *(s_eol
-1) == '\r')
687 s_eol
= strchr (s
, '\0');
689 /* If there is a concatenating \\ then go around again */
690 if (s_eol
> line
&& *(s_eol
-1) == '\\') {
697 } while(c
== ' ' || c
== '\t');
701 fprintf(stderr
,"%s: ERROR - invalid continuation.\n",
712 lineW
= GetWideString(line
);
714 break; /* That is the full virtual line */
717 processRegEntry(lineW
, FALSE
);
718 HeapFree(GetProcessHeap(), 0, lineW
);
720 processRegEntry(NULL
, FALSE
);
722 HeapFree(GetProcessHeap(), 0, line
);
725 static void processRegLinesW(FILE *in
)
727 WCHAR
* buf
= NULL
; /* line read from input stream */
728 ULONG lineSize
= REG_VAL_BUF_SIZE
;
729 size_t CharsInBuf
= -1;
731 WCHAR
* s
; /* The pointer into buf for where the current fgets should read */
732 WCHAR
* line
; /* The start of the current line */
734 buf
= HeapAlloc(GetProcessHeap(), 0, lineSize
* sizeof(WCHAR
));
735 CHECK_ENOUGH_MEMORY(buf
);
741 size_t size_remaining
;
743 WCHAR
*s_eol
= NULL
; /* various local uses */
745 /* Do we need to expand the buffer ? */
746 assert (s
>= buf
&& s
<= buf
+ lineSize
);
747 size_remaining
= lineSize
- (s
-buf
);
748 if (size_remaining
< 2) /* room for 1 character and the \0 */
751 size_t new_size
= lineSize
+ (REG_VAL_BUF_SIZE
/ sizeof(WCHAR
));
752 if (new_size
> lineSize
) /* no arithmetic overflow */
753 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, buf
, new_size
* sizeof(WCHAR
));
756 CHECK_ENOUGH_MEMORY(new_buffer
);
759 s
= buf
+ lineSize
- size_remaining
;
761 size_remaining
= lineSize
- (s
-buf
);
764 /* Get as much as possible into the buffer, terminated either by
765 * eof, error or getting the maximum amount. Abort on error.
767 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
769 CharsInBuf
= fread(s
, sizeof(WCHAR
), size_to_get
- 1, in
);
772 if (CharsInBuf
== 0) {
774 perror ("While reading input");
779 /* It is not clear to me from the definition that the
780 * contents of the buffer are well defined on detecting
781 * an eof without managing to read anything.
786 /* If we didn't read the eol nor the eof go around for the rest */
789 s_eol
= wcschr(line
, '\n');
792 /* Move the stub of the line to the start of the buffer so
793 * we get the maximum space to read into, and so we don't
794 * have to recalculate 'line' if the buffer expands */
795 MoveMemory(buf
, line
, (lstrlenW(line
) + 1) * sizeof(WCHAR
));
797 s
= wcschr(line
, '\0');
801 /* If it is a comment line then discard it and go around again */
807 /* If there is a concatenating \\ then go around again */
808 if ((*(s_eol
-1) == '\\') ||
809 (*(s_eol
-1) == '\r' && *(s_eol
-2) == '\\')) {
810 WCHAR
* NextLine
= s_eol
;
812 while(*(NextLine
+1) == ' ' || *(NextLine
+1) == '\t')
817 if(*(s_eol
-1) == '\r')
820 MoveMemory(s_eol
- 1, NextLine
, (CharsInBuf
- (NextLine
- s
) + 1)*sizeof(WCHAR
));
821 CharsInBuf
-= NextLine
- s_eol
+ 1;
826 /* Remove any line feed. Leave s_eol on the \0 */
829 if (s_eol
> buf
&& *(s_eol
-1) == '\r')
836 processRegEntry(line
, TRUE
);
839 continue; /* That is the full virtual line */
843 processRegEntry(NULL
, TRUE
);
845 HeapFree(GetProcessHeap(), 0, buf
);
848 /****************************************************************************
849 * REGPROC_print_error
851 * Print the message for GetLastError
854 static void REGPROC_print_error(void)
860 error_code
= GetLastError ();
861 status
= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
862 NULL
, error_code
, 0, (LPTSTR
) &lpMsgBuf
, 0, NULL
);
864 fprintf(stderr
,"%s: Cannot display message for error %ld, status %ld\n",
865 getAppName(), error_code
, GetLastError());
873 /******************************************************************************
874 * Checks whether the buffer has enough room for the string or required size.
875 * Resizes the buffer if necessary.
878 * buffer - pointer to a buffer for string
879 * len - current length of the buffer in characters.
880 * required_len - length of the string to place to the buffer in characters.
881 * The length does not include the terminating null character.
883 static void REGPROC_resize_char_buffer(WCHAR
**buffer
, DWORD
*len
, DWORD required_len
)
886 if (required_len
> *len
) {
889 *buffer
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(**buffer
));
891 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *len
* sizeof(**buffer
));
892 CHECK_ENOUGH_MEMORY(*buffer
);
896 /******************************************************************************
897 * Same as REGPROC_resize_char_buffer() but on a regular buffer.
900 * buffer - pointer to a buffer
901 * len - current size of the buffer in bytes
902 * required_size - size of the data to place in the buffer in bytes
904 static void REGPROC_resize_binary_buffer(BYTE
**buffer
, DWORD
*size
, DWORD required_size
)
906 if (required_size
> *size
) {
907 *size
= required_size
;
909 *buffer
= HeapAlloc(GetProcessHeap(), 0, *size
);
911 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *size
);
912 CHECK_ENOUGH_MEMORY(*buffer
);
916 /******************************************************************************
917 * Prints string str to file
919 static void REGPROC_export_string(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, WCHAR
*str
, DWORD str_len
)
924 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ 10);
926 /* escaping characters */
928 for (i
= 0; i
< str_len
; i
++) {
933 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
934 (*line_buf
)[pos
++] = '\\';
935 (*line_buf
)[pos
++] = 'n';
941 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
942 (*line_buf
)[pos
++] = '\\';
946 (*line_buf
)[pos
++] = c
;
950 (*line_buf
)[pos
] = '\0';
954 static void REGPROC_export_binary(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, DWORD type
, BYTE
*value
, DWORD value_size
, BOOL unicode
)
956 DWORD hex_pos
, data_pos
;
957 const WCHAR
*hex_prefix
;
958 const WCHAR hex
[] = {'h','e','x',':',0};
960 const WCHAR concat
[] = {'\\','\n',' ',' ',0};
961 DWORD concat_prefix
, concat_len
;
962 const WCHAR newline
[] = {'\n',0};
963 CHAR
* value_multibyte
= NULL
;
965 if (type
== REG_BINARY
) {
968 const WCHAR hex_format
[] = {'h','e','x','(','%','u',')',':',0};
969 hex_prefix
= hex_buf
;
970 wsprintfW(hex_buf
, hex_format
, type
);
971 if ((type
== REG_SZ
|| type
== REG_EXPAND_SZ
|| type
== REG_MULTI_SZ
) && !unicode
)
973 value_multibyte
= GetMultiByteStringN((WCHAR
*)value
, value_size
/ sizeof(WCHAR
), &value_size
);
974 value
= (BYTE
*)value_multibyte
;
978 concat_len
= lstrlenW(concat
);
982 *line_len
+= lstrlenW(hex_prefix
);
983 data_pos
= *line_len
;
984 *line_len
+= value_size
* 3;
985 /* - The 2 spaces that concat places at the start of the
986 * line effectively reduce the space available for data.
987 * - If the value name and hex prefix are very long
988 * ( > REG_FILE_HEX_LINE_LEN) then we may overestimate
989 * the needed number of lines by one. But that's ok.
990 * - The trailing linefeed takes the place of a comma so
991 * it's accounted for already.
993 *line_len
+= *line_len
/ (REG_FILE_HEX_LINE_LEN
- concat_prefix
) * concat_len
;
994 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
);
995 lstrcpyW(*line_buf
+ hex_pos
, hex_prefix
);
998 const WCHAR format
[] = {'%','0','2','x',0};
1001 column
= data_pos
; /* no line wrap yet */
1005 wsprintfW(*line_buf
+ data_pos
, format
, (unsigned int)value
[i
]);
1007 if (++i
== value_size
)
1010 (*line_buf
)[data_pos
++] = ',';
1014 if (column
>= REG_FILE_HEX_LINE_LEN
) {
1015 lstrcpyW(*line_buf
+ data_pos
, concat
);
1016 data_pos
+= concat_len
;
1017 column
= concat_prefix
;
1021 lstrcpyW(*line_buf
+ data_pos
, newline
);
1022 HeapFree(GetProcessHeap(), 0, value_multibyte
);
1025 /******************************************************************************
1026 * Writes the given line to a file, in multi-byte or wide characters
1028 static void REGPROC_write_line(FILE *file
, const WCHAR
* str
, BOOL unicode
)
1033 for(i
= 0; str
[i
]; i
++)
1035 if (str
[i
] == L
'\n')
1036 fputwc(L
'\r', file
);
1037 fputwc(str
[i
], file
);
1042 char* strA
= GetMultiByteString(str
);
1044 HeapFree(GetProcessHeap(), 0, strA
);
1048 /******************************************************************************
1049 * Writes contents of the registry key to the specified file stream.
1052 * file - writable file stream to export registry branch to.
1053 * key - registry branch to export.
1054 * reg_key_name_buf - name of the key with registry class.
1055 * Is resized if necessary.
1056 * reg_key_name_size - length of the buffer for the registry class in characters.
1057 * val_name_buf - buffer for storing value name.
1058 * Is resized if necessary.
1059 * val_name_size - length of the buffer for storing value names in characters.
1060 * val_buf - buffer for storing values while extracting.
1061 * Is resized if necessary.
1062 * val_size - size of the buffer for storing values in bytes.
1064 static void export_hkey(FILE *file
, HKEY key
,
1065 WCHAR
**reg_key_name_buf
, DWORD
*reg_key_name_size
,
1066 WCHAR
**val_name_buf
, DWORD
*val_name_size
,
1067 BYTE
**val_buf
, DWORD
*val_size
,
1068 WCHAR
**line_buf
, DWORD
*line_buf_size
,
1071 DWORD max_sub_key_len
;
1072 DWORD max_val_name_len
;
1078 WCHAR key_format
[] = {'\n','[','%','s',']','\n',0};
1080 /* get size information and resize the buffers if necessary */
1081 if (RegQueryInfoKeyW(key
, NULL
, NULL
, NULL
, NULL
,
1082 &max_sub_key_len
, NULL
,
1083 NULL
, &max_val_name_len
, &max_val_size
, NULL
, NULL
1084 ) != ERROR_SUCCESS
) {
1085 REGPROC_print_error();
1087 curr_len
= lstrlenW(*reg_key_name_buf
);
1088 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
,
1089 max_sub_key_len
+ curr_len
+ 1);
1090 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
,
1092 REGPROC_resize_binary_buffer(val_buf
, val_size
, max_val_size
);
1093 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, lstrlenW(*reg_key_name_buf
) + 4);
1094 /* output data for the current key */
1095 wsprintfW(*line_buf
, key_format
, *reg_key_name_buf
);
1096 REGPROC_write_line(file
, *line_buf
, unicode
);
1098 /* print all the values */
1103 DWORD val_name_size1
= *val_name_size
;
1104 DWORD val_size1
= *val_size
;
1105 ret
= RegEnumValueW(key
, i
, *val_name_buf
, &val_name_size1
, NULL
,
1106 &value_type
, *val_buf
, &val_size1
);
1107 if (ret
== ERROR_MORE_DATA
) {
1108 /* Increase the size of the buffers and retry */
1109 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, val_name_size1
);
1110 REGPROC_resize_binary_buffer(val_buf
, val_size
, val_size1
);
1111 } else if (ret
!= ERROR_SUCCESS
) {
1113 if (ret
!= ERROR_NO_MORE_ITEMS
) {
1114 REGPROC_print_error();
1120 if ((*val_name_buf
)[0]) {
1121 const WCHAR val_start
[] = {'"','%','s','"','=',0};
1124 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, *val_name_buf
, lstrlenW(*val_name_buf
));
1125 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, lstrlenW(*line_buf
) + 1);
1126 lstrcpyW(*val_name_buf
, *line_buf
);
1128 line_len
= 3 + lstrlenW(*val_name_buf
);
1129 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1130 wsprintfW(*line_buf
, val_start
, *val_name_buf
);
1132 const WCHAR std_val
[] = {'@','=',0};
1134 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1135 lstrcpyW(*line_buf
, std_val
);
1138 switch (value_type
) {
1141 WCHAR
* wstr
= (WCHAR
*)*val_buf
;
1143 if (val_size1
< sizeof(WCHAR
) || val_size1
% sizeof(WCHAR
) ||
1144 wstr
[val_size1
/ sizeof(WCHAR
) - 1]) {
1145 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1147 const WCHAR start
[] = {'"',0};
1148 const WCHAR end
[] = {'"','\n',0};
1151 len
= lstrlenW(start
);
1152 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ len
);
1153 lstrcpyW(*line_buf
+ line_len
, start
);
1156 /* At this point we know wstr is '\0'-terminated
1157 * so we can substract 1 from the size
1159 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, wstr
, val_size1
/ sizeof(WCHAR
) - 1);
1161 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ lstrlenW(end
));
1162 lstrcpyW(*line_buf
+ line_len
, end
);
1169 WCHAR format
[] = {'d','w','o','r','d',':','%','0','8','x','\n',0};
1171 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ 15);
1172 wsprintfW(*line_buf
+ line_len
, format
, *((DWORD
*)*val_buf
));
1178 char* key_nameA
= GetMultiByteString(*reg_key_name_buf
);
1179 char* value_nameA
= GetMultiByteString(*val_name_buf
);
1180 fprintf(stderr
,"%s: warning - unsupported registry format '%ld', "
1181 "treat as binary\n",
1182 getAppName(), value_type
);
1183 fprintf(stderr
,"key name: \"%s\"\n", key_nameA
);
1184 fprintf(stderr
,"value name:\"%s\"\n\n", value_nameA
);
1185 HeapFree(GetProcessHeap(), 0, key_nameA
);
1186 HeapFree(GetProcessHeap(), 0, value_nameA
);
1193 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1195 REGPROC_write_line(file
, *line_buf
, unicode
);
1201 (*reg_key_name_buf
)[curr_len
] = '\\';
1203 DWORD buf_size
= *reg_key_name_size
- curr_len
- 1;
1205 ret
= RegEnumKeyExW(key
, i
, *reg_key_name_buf
+ curr_len
+ 1, &buf_size
,
1206 NULL
, NULL
, NULL
, NULL
);
1207 if (ret
== ERROR_MORE_DATA
) {
1208 /* Increase the size of the buffer and retry */
1209 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
, curr_len
+ 1 + buf_size
);
1210 } else if (ret
!= ERROR_SUCCESS
) {
1212 if (ret
!= ERROR_NO_MORE_ITEMS
) {
1213 REGPROC_print_error();
1219 if (RegOpenKeyW(key
, *reg_key_name_buf
+ curr_len
+ 1,
1220 &subkey
) == ERROR_SUCCESS
) {
1221 export_hkey(file
, subkey
, reg_key_name_buf
, reg_key_name_size
,
1222 val_name_buf
, val_name_size
, val_buf
, val_size
,
1223 line_buf
, line_buf_size
, unicode
);
1224 RegCloseKey(subkey
);
1226 REGPROC_print_error();
1230 (*reg_key_name_buf
)[curr_len
] = '\0';
1233 /******************************************************************************
1234 * Open file for export.
1236 static FILE *REGPROC_open_export_file(WCHAR
*file_name
, BOOL unicode
)
1241 if (wcsncmp(file_name
, &dash
, 1) == 0)
1246 file
= _wfopen(file_name
, L
"wb");
1248 file
= _wfopen(file_name
, L
"w");
1250 CHAR
* file_nameA
= GetMultiByteString(file_name
);
1252 fprintf(stderr
,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA
);
1253 HeapFree(GetProcessHeap(), 0, file_nameA
);
1259 const BYTE unicode_seq
[] = {0xff,0xfe};
1260 const WCHAR header
[] = L
"Windows Registry Editor Version 5.00\r\n";
1261 fwrite(unicode_seq
, sizeof(BYTE
), COUNT_OF(unicode_seq
), file
);
1262 fwrite(header
, sizeof(WCHAR
), lstrlenW(header
), file
);
1266 fputs("REGEDIT4\n", file
);
1272 /******************************************************************************
1273 * Writes contents of the registry key to the specified file stream.
1276 * file_name - name of a file to export registry branch to.
1277 * reg_key_name - registry branch to export. The whole registry is exported if
1278 * reg_key_name is NULL or contains an empty string.
1280 BOOL
export_registry_key(WCHAR
*file_name
, WCHAR
*reg_key_name
, DWORD format
)
1282 WCHAR
*reg_key_name_buf
;
1283 WCHAR
*val_name_buf
;
1286 DWORD reg_key_name_size
= KEY_MAX_LEN
;
1287 DWORD val_name_size
= KEY_MAX_LEN
;
1288 DWORD val_size
= REG_VAL_BUF_SIZE
;
1289 DWORD line_buf_size
= KEY_MAX_LEN
+ REG_VAL_BUF_SIZE
;
1291 BOOL unicode
= (format
== REG_FORMAT_5
);
1293 reg_key_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1294 reg_key_name_size
* sizeof(*reg_key_name_buf
));
1295 val_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1296 val_name_size
* sizeof(*val_name_buf
));
1297 val_buf
= HeapAlloc(GetProcessHeap(), 0, val_size
);
1298 line_buf
= HeapAlloc(GetProcessHeap(), 0, line_buf_size
* sizeof(*line_buf
));
1299 CHECK_ENOUGH_MEMORY(reg_key_name_buf
&& val_name_buf
&& val_buf
&& line_buf
);
1301 if (reg_key_name
&& reg_key_name
[0]) {
1303 WCHAR
*branch_name
= NULL
;
1306 REGPROC_resize_char_buffer(®_key_name_buf
, ®_key_name_size
,
1307 lstrlenW(reg_key_name
));
1308 lstrcpyW(reg_key_name_buf
, reg_key_name
);
1310 /* open the specified key */
1311 if (!parseKeyName(reg_key_name
, ®_key_class
, &branch_name
)) {
1312 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1313 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1314 getAppName(), key_nameA
);
1315 HeapFree(GetProcessHeap(), 0, key_nameA
);
1318 if (!branch_name
[0]) {
1319 /* no branch - registry class is specified */
1320 file
= REGPROC_open_export_file(file_name
, unicode
);
1321 export_hkey(file
, reg_key_class
,
1322 ®_key_name_buf
, ®_key_name_size
,
1323 &val_name_buf
, &val_name_size
,
1324 &val_buf
, &val_size
, &line_buf
,
1325 &line_buf_size
, unicode
);
1326 } else if (RegOpenKeyW(reg_key_class
, branch_name
, &key
) == ERROR_SUCCESS
) {
1327 file
= REGPROC_open_export_file(file_name
, unicode
);
1328 export_hkey(file
, key
,
1329 ®_key_name_buf
, ®_key_name_size
,
1330 &val_name_buf
, &val_name_size
,
1331 &val_buf
, &val_size
, &line_buf
,
1332 &line_buf_size
, unicode
);
1335 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1336 fprintf(stderr
,"%s: Can't export. Registry key '%s' does not exist!\n",
1337 getAppName(), key_nameA
);
1338 HeapFree(GetProcessHeap(), 0, key_nameA
);
1339 REGPROC_print_error();
1344 /* export all registry classes */
1345 file
= REGPROC_open_export_file(file_name
, unicode
);
1346 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++) {
1347 /* do not export HKEY_CLASSES_ROOT */
1348 if (reg_class_keys
[i
] != HKEY_CLASSES_ROOT
&&
1349 reg_class_keys
[i
] != HKEY_CURRENT_USER
&&
1350 reg_class_keys
[i
] != HKEY_CURRENT_CONFIG
&&
1351 reg_class_keys
[i
] != HKEY_DYN_DATA
) {
1352 lstrcpyW(reg_key_name_buf
, reg_class_namesW
[i
]);
1353 export_hkey(file
, reg_class_keys
[i
],
1354 ®_key_name_buf
, ®_key_name_size
,
1355 &val_name_buf
, &val_name_size
,
1356 &val_buf
, &val_size
, &line_buf
,
1357 &line_buf_size
, unicode
);
1365 HeapFree(GetProcessHeap(), 0, reg_key_name
);
1366 HeapFree(GetProcessHeap(), 0, val_name_buf
);
1367 HeapFree(GetProcessHeap(), 0, val_buf
);
1368 HeapFree(GetProcessHeap(), 0, line_buf
);
1372 /******************************************************************************
1373 * Reads contents of the specified file into the registry.
1375 BOOL
import_registry_file(FILE* reg_file
)
1380 if (fread( s
, 2, 1, reg_file
) == 1)
1382 if (s
[0] == 0xff && s
[1] == 0xfe)
1384 processRegLinesW(reg_file
);
1387 fseek(reg_file
, 0, SEEK_SET
);
1388 processRegLinesA(reg_file
);
1396 /******************************************************************************
1397 * Removes the registry key with all subkeys. Parses full key name.
1400 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1401 * empty, points to register key class, does not exist.
1403 void delete_registry_key(WCHAR
*reg_key_name
)
1405 WCHAR
*key_name
= NULL
;
1408 if (!reg_key_name
|| !reg_key_name
[0])
1411 if (!parseKeyName(reg_key_name
, &key_class
, &key_name
)) {
1412 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1413 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1414 getAppName(), reg_key_nameA
);
1415 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1419 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1420 fprintf(stderr
,"%s: Can't delete registry class '%s'\n",
1421 getAppName(), reg_key_nameA
);
1422 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1426 SHDeleteKey(key_class
, key_name
);