2 * Registry processing routines. Routines, common for registry
3 * processing frontends.
5 * Copyright (C) 1999 Sylvain St-Germain
6 * Copyright (C) 2002 Andriy Palamarchuk
7 * Copyright (C) 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
[] =
35 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
36 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
39 #define REG_CLASS_NUMBER (COUNT_OF(reg_class_names))
41 const WCHAR
* reg_class_namesW
[REG_CLASS_NUMBER
] =
43 L
"HKEY_LOCAL_MACHINE", L
"HKEY_USERS", L
"HKEY_CLASSES_ROOT",
44 L
"HKEY_CURRENT_CONFIG", L
"HKEY_CURRENT_USER", L
"HKEY_DYN_DATA"
47 static HKEY reg_class_keys
[REG_CLASS_NUMBER
] =
49 HKEY_LOCAL_MACHINE
, HKEY_USERS
, HKEY_CLASSES_ROOT
,
50 HKEY_CURRENT_CONFIG
, HKEY_CURRENT_USER
, HKEY_DYN_DATA
54 #define NOT_ENOUGH_MEMORY 1
57 /* processing macros */
59 /* common check of memory allocation results */
60 #define CHECK_ENOUGH_MEMORY(p) \
63 fprintf(stderr,"%S: file %s, line %d: Not enough memory\n", \
64 getAppName(), __FILE__, __LINE__); \
65 exit(NOT_ENOUGH_MEMORY); \
68 /******************************************************************************
69 * Allocates memory and converts input from multibyte to wide chars
70 * Returned string must be freed by the caller
72 WCHAR
* GetWideString(const char* strA
)
77 int len
= MultiByteToWideChar(CP_ACP
, 0, strA
, -1, NULL
, 0);
79 strW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
80 CHECK_ENOUGH_MEMORY(strW
);
81 MultiByteToWideChar(CP_ACP
, 0, strA
, -1, strW
, len
);
87 /******************************************************************************
88 * Allocates memory and converts input from multibyte to wide chars
89 * Returned string must be freed by the caller
91 static WCHAR
* GetWideStringN(const char* strA
, int chars
, DWORD
*len
)
96 *len
= MultiByteToWideChar(CP_ACP
, 0, strA
, chars
, NULL
, 0);
98 strW
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(WCHAR
));
99 CHECK_ENOUGH_MEMORY(strW
);
100 MultiByteToWideChar(CP_ACP
, 0, strA
, chars
, strW
, *len
);
107 /******************************************************************************
108 * Allocates memory and converts input from wide chars to multibyte
109 * Returned string must be freed by the caller
111 char* GetMultiByteString(const WCHAR
* strW
)
116 int len
= WideCharToMultiByte(CP_ACP
, 0, strW
, -1, NULL
, 0, NULL
, NULL
);
118 strA
= HeapAlloc(GetProcessHeap(), 0, len
);
119 CHECK_ENOUGH_MEMORY(strA
);
120 WideCharToMultiByte(CP_ACP
, 0, strW
, -1, strA
, len
, NULL
, NULL
);
126 /******************************************************************************
127 * Allocates memory and converts input from wide chars to multibyte
128 * Returned string must be freed by the caller
130 static char* GetMultiByteStringN(const WCHAR
* strW
, int chars
, DWORD
* len
)
135 *len
= WideCharToMultiByte(CP_ACP
, 0, strW
, chars
, NULL
, 0, NULL
, NULL
);
137 strA
= HeapAlloc(GetProcessHeap(), 0, *len
);
138 CHECK_ENOUGH_MEMORY(strA
);
139 WideCharToMultiByte(CP_ACP
, 0, strW
, chars
, strA
, *len
, NULL
, NULL
);
146 /******************************************************************************
147 * Converts a hex representation of a DWORD into a DWORD.
149 static BOOL
convertHexToDWord(WCHAR
* str
, DWORD
*dw
)
154 WideCharToMultiByte(CP_ACP
, 0, str
, -1, buf
, 9, NULL
, NULL
);
155 if (lstrlenW(str
) > 8 || sscanf(buf
, "%lx%c", dw
, &dummy
) != 1)
157 fprintf(stderr
,"%S: ERROR, invalid hex value\n", getAppName());
163 /******************************************************************************
164 * Converts a hex comma separated values list into a binary string.
166 static BYTE
* convertHexCSVToHex(WCHAR
*str
, DWORD
*size
)
171 /* The worst case is 1 digit + 1 comma per byte */
172 *size
=(lstrlenW(str
)+1)/2;
173 data
=HeapAlloc(GetProcessHeap(), 0, *size
);
174 CHECK_ENOUGH_MEMORY(data
);
184 wc
= wcstoul(s
,&end
, 16);
185 if (end
== s
|| wc
> 0xff || (*end
&& *end
!= L
','))
187 char* strA
= GetMultiByteString(s
);
188 fprintf(stderr
,"%S: ERROR converting CSV hex stream. Invalid value at '%s'\n",
190 HeapFree(GetProcessHeap(), 0, data
);
191 HeapFree(GetProcessHeap(), 0, strA
);
203 /******************************************************************************
204 * This function returns the HKEY associated with the data type encoded in the
205 * value. It modifies the input parameter (key value) in order to skip this
206 * "now useless" data type information.
208 * Note: Updated based on the algorithm used in 'server/registry.c'
210 static DWORD
getDataType(LPWSTR
*lpValue
, DWORD
* parse_type
)
220 static const WCHAR quote
[] = {'"'};
221 static const WCHAR str
[] = {'s','t','r',':','"'};
222 static const WCHAR str2
[] = {'s','t','r','(','2',')',':','"'};
223 static const WCHAR hex
[] = {'h','e','x',':'};
224 static const WCHAR dword
[] = {'d','w','o','r','d',':'};
225 static const WCHAR hexp
[] = {'h','e','x','('};
227 static const struct data_type data_types
[] = { /* actual type */ /* type to assume for parsing */
228 { quote
, 1, REG_SZ
, REG_SZ
},
229 { str
, 5, REG_SZ
, REG_SZ
},
230 { str2
, 8, REG_EXPAND_SZ
, REG_SZ
},
231 { hex
, 4, REG_BINARY
, REG_BINARY
},
232 { dword
, 6, REG_DWORD
, REG_DWORD
},
233 { hexp
, 4, -1, REG_BINARY
},
237 const struct data_type
*ptr
;
240 for (ptr
= data_types
; ptr
->tag
; ptr
++)
242 if (wcsncmp(ptr
->tag
, *lpValue
, ptr
->len
))
246 *parse_type
= ptr
->parse_type
;
253 /* "hex(xx):" is special */
254 type
= (int)wcstoul( *lpValue
, &end
, 16 );
255 if (**lpValue
=='\0' || *end
!=')' || *(end
+1)!=':')
266 *parse_type
=REG_NONE
;
270 /******************************************************************************
271 * Replaces escape sequences with the characters.
273 static void REGPROC_unescape_string(WCHAR
* str
)
275 int str_idx
= 0; /* current character under analysis */
276 int val_idx
= 0; /* the last character of the unescaped string */
277 int len
= lstrlenW(str
);
278 for (str_idx
= 0; str_idx
< len
; str_idx
++, val_idx
++)
280 if (str
[str_idx
] == '\\')
283 switch (str
[str_idx
])
290 str
[val_idx
] = str
[str_idx
];
293 fprintf(stderr
,"Warning! Unrecognized escape sequence: \\%C'\n",
295 str
[val_idx
] = str
[str_idx
];
301 str
[val_idx
] = str
[str_idx
];
307 static BOOL
parseKeyName(LPWSTR lpKeyName
, HKEY
*hKey
, LPWSTR
*lpKeyPath
)
309 WCHAR
* lpSlash
= NULL
;
312 if (lpKeyName
== NULL
)
315 for(i
= 0; *(lpKeyName
+ i
) != 0; i
++)
317 if(*(lpKeyName
+i
) == '\\')
319 lpSlash
= lpKeyName
+ i
;
326 len
= lpSlash
-lpKeyName
;
330 len
= lstrlenW(lpKeyName
);
331 lpSlash
= lpKeyName
+len
;
335 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++)
337 if (CompareStringW(LOCALE_USER_DEFAULT
, 0, lpKeyName
, len
, reg_class_namesW
[i
], len
) == CSTR_EQUAL
&&
338 len
== lstrlenW(reg_class_namesW
[i
]))
340 *hKey
= reg_class_keys
[i
];
348 if (*lpSlash
!= '\0')
350 *lpKeyPath
= lpSlash
;
354 /* Globals used by the setValue() & co */
355 static LPSTR currentKeyName
;
356 static HKEY currentKeyHandle
= NULL
;
358 /******************************************************************************
359 * Sets the value with name val_name to the data in val_data for the currently
363 * val_name - name of the registry value
364 * val_data - registry value data
366 static LONG
setValue(WCHAR
* val_name
, WCHAR
* val_data
, BOOL is_unicode
)
369 DWORD dwDataType
, dwParseType
;
372 WCHAR del
[] = {'-',0};
374 if ( (val_name
== NULL
) || (val_data
== NULL
) )
375 return ERROR_INVALID_PARAMETER
;
377 if (lstrcmpW(val_data
, del
) == 0)
379 res
=RegDeleteValueW(currentKeyHandle
,val_name
);
380 return (res
== ERROR_FILE_NOT_FOUND
? ERROR_SUCCESS
: res
);
383 /* Get the data type stored into the value field */
384 dwDataType
= getDataType(&val_data
, &dwParseType
);
386 if (dwParseType
== REG_SZ
) /* no conversion for string */
388 REGPROC_unescape_string(val_data
);
389 /* Compute dwLen after REGPROC_unescape_string because it may
390 * have changed the string length and we don't want to store
391 * the extra garbage in the registry.
393 dwLen
= lstrlenW(val_data
);
394 if (dwLen
>0 && val_data
[dwLen
-1]=='"')
397 val_data
[dwLen
]='\0';
399 lpbData
= (BYTE
*) val_data
;
400 dwLen
++; /* include terminating null */
401 dwLen
= dwLen
* sizeof(WCHAR
); /* size is in bytes */
403 else if (dwParseType
== REG_DWORD
) /* Convert the dword types */
405 if (!convertHexToDWord(val_data
, &dwData
))
406 return ERROR_INVALID_DATA
;
407 lpbData
= (BYTE
*)&dwData
;
408 dwLen
= sizeof(dwData
);
410 else if (dwParseType
== REG_BINARY
) /* Convert the binary data */
412 lpbData
= convertHexCSVToHex(val_data
, &dwLen
);
414 return ERROR_INVALID_DATA
;
416 if((dwDataType
== REG_MULTI_SZ
|| dwDataType
== REG_EXPAND_SZ
) && !is_unicode
)
418 LPBYTE tmp
= lpbData
;
419 lpbData
= (LPBYTE
)GetWideStringN((char*)lpbData
, dwLen
, &dwLen
);
420 dwLen
*= sizeof(WCHAR
);
421 HeapFree(GetProcessHeap(), 0, tmp
);
424 else /* unknown format */
426 fprintf(stderr
,"%S: ERROR, unknown data format\n", getAppName());
427 return ERROR_INVALID_DATA
;
430 res
= RegSetValueExW(
437 if (dwParseType
== REG_BINARY
)
438 HeapFree(GetProcessHeap(), 0, lpbData
);
442 /******************************************************************************
443 * A helper function for processRegEntry() that opens the current key.
444 * That key must be closed by calling closeKey().
446 static LONG
openKeyW(WCHAR
* stdInput
)
454 if (stdInput
== NULL
)
455 return ERROR_INVALID_PARAMETER
;
457 /* Get the registry class */
458 if (!parseKeyName(stdInput
, &keyClass
, &keyPath
))
459 return ERROR_INVALID_PARAMETER
;
461 res
= RegCreateKeyExW(keyClass
, /* Class */
462 keyPath
, /* Sub Key */
464 NULL
, /* object type */
465 REG_OPTION_NON_VOLATILE
, /* option, REG_OPTION_NON_VOLATILE ... */
466 KEY_ALL_ACCESS
, /* access mask, KEY_ALL_ACCESS */
467 NULL
, /* security attribute */
468 ¤tKeyHandle
, /* result */
469 &dwDisp
); /* disposition, REG_CREATED_NEW_KEY or
470 REG_OPENED_EXISTING_KEY */
472 if (res
== ERROR_SUCCESS
)
473 currentKeyName
= GetMultiByteString(stdInput
);
475 currentKeyHandle
= NULL
;
481 /******************************************************************************
482 * Close the currently opened key.
484 static void closeKey(void)
486 if (currentKeyHandle
)
488 HeapFree(GetProcessHeap(), 0, currentKeyName
);
489 RegCloseKey(currentKeyHandle
);
490 currentKeyHandle
= NULL
;
494 /******************************************************************************
495 * This function is a wrapper for the setValue function. It prepares the
496 * land and cleans the area once completed.
497 * Note: this function modifies the line parameter.
499 * line - registry file unwrapped line. Should have the registry value name and
500 * complete registry value data.
502 static void processSetValue(WCHAR
* line
, BOOL is_unicode
)
504 WCHAR
* val_name
; /* registry value name */
505 WCHAR
* val_data
; /* registry value data */
506 int line_idx
= 0; /* current character under analysis */
510 while ( iswspace(line
[line_idx
]) ) line_idx
++;
511 if (line
[line_idx
] == '@' && line
[line_idx
+ 1] == '=')
513 line
[line_idx
] = '\0';
517 else if (line
[line_idx
] == '\"')
520 val_name
= line
+ line_idx
;
523 if (line
[line_idx
] == '\\') /* skip escaped character */
529 if (line
[line_idx
] == '\"')
531 line
[line_idx
] = '\0';
541 while ( iswspace(line
[line_idx
]) ) line_idx
++;
542 if (line
[line_idx
] != '=')
545 line
[line_idx
] = '\"';
546 lineA
= GetMultiByteString(line
);
547 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", lineA
);
548 HeapFree(GetProcessHeap(), 0, lineA
);
555 char* lineA
= GetMultiByteString(line
);
556 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", lineA
);
557 HeapFree(GetProcessHeap(), 0, lineA
);
560 line_idx
++; /* skip the '=' character */
562 while ( iswspace(line
[line_idx
]) ) line_idx
++;
563 val_data
= line
+ line_idx
;
564 /* trim trailing blanks */
565 line_idx
= lstrlenW(val_data
);
566 while (line_idx
> 0 && iswspace(val_data
[line_idx
-1])) line_idx
--;
567 val_data
[line_idx
] = '\0';
569 REGPROC_unescape_string(val_name
);
570 res
= setValue(val_name
, val_data
, is_unicode
);
571 if ( res
!= ERROR_SUCCESS
)
573 char* val_nameA
= GetMultiByteString(val_name
);
574 char* val_dataA
= GetMultiByteString(val_data
);
575 fprintf(stderr
,"%S: ERROR Key %s not created. Value: %s, Data: %s\n",
580 HeapFree(GetProcessHeap(), 0, val_nameA
);
581 HeapFree(GetProcessHeap(), 0, val_dataA
);
585 /******************************************************************************
586 * This function receives the currently read entry and performs the
587 * corresponding action.
588 * isUnicode affects parsing of REG_MULTI_SZ values
590 static void processRegEntry(WCHAR
* stdInput
, BOOL isUnicode
)
593 * We encountered the end of the file, make sure we
594 * close the opened key and exit
596 if (stdInput
== NULL
)
602 if ( stdInput
[0] == L
'[') /* We are reading a new key */
605 closeKey(); /* Close the previous key */
607 /* Get rid of the square brackets */
609 keyEnd
= wcsrchr(stdInput
, L
']');
613 /* delete the key if we encounter '-' at the start of reg key */
614 if ( stdInput
[0] == '-')
616 delete_registry_key(stdInput
+ 1);
618 else if ( openKeyW(stdInput
) != ERROR_SUCCESS
)
620 char* stdInputA
= GetMultiByteString(stdInput
);
621 fprintf(stderr
,"%S: setValue failed to open key %s\n",
622 getAppName(), stdInputA
);
623 HeapFree(GetProcessHeap(), 0, stdInputA
);
626 else if( currentKeyHandle
&&
627 (( stdInput
[0] == '@') || /* reading a default @=data pair */
628 ( stdInput
[0] == '\"'))) /* reading a new value=data pair */
630 processSetValue(stdInput
, isUnicode
);
634 /* Since we are assuming that the file format is valid we must be
635 * reading a blank line which indicates the end of this key processing
641 /******************************************************************************
642 * Processes a registry file.
643 * Correctly processes comments (in # form), line continuation.
646 * in - input stream to read from
648 static void processRegLinesA(FILE *in
)
650 LPSTR line
= NULL
; /* line read from input stream */
651 ULONG lineSize
= REG_VAL_BUF_SIZE
;
653 line
= HeapAlloc(GetProcessHeap(), 0, lineSize
);
654 CHECK_ENOUGH_MEMORY(line
);
658 LPSTR s
; /* The pointer into line for where the current fgets should read */
665 size_t size_remaining
;
667 char *s_eol
; /* various local uses */
669 /* Do we need to expand the buffer ? */
670 assert (s
>= line
&& s
<= line
+ lineSize
);
671 size_remaining
= lineSize
- (s
-line
);
672 if (size_remaining
< 2) /* room for 1 character and the \0 */
675 size_t new_size
= lineSize
+ REG_VAL_BUF_SIZE
;
676 if (new_size
> lineSize
) /* no arithmetic overflow */
677 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, line
, new_size
);
680 CHECK_ENOUGH_MEMORY(new_buffer
);
682 s
= line
+ lineSize
- size_remaining
;
684 size_remaining
= lineSize
- (s
-line
);
687 /* Get as much as possible into the buffer, terminated either by
688 * eof, error, eol or getting the maximum amount. Abort on error.
690 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
692 check
= fgets (s
, size_to_get
, in
);
698 perror ("While reading input");
705 /* It is not clear to me from the definition that the
706 * contents of the buffer are well defined on detecting
707 * an eof without managing to read anything.
712 /* If we didn't read the eol nor the eof go around for the rest */
713 s_eol
= strchr (s
, '\n');
714 if (!feof (in
) && !s_eol
)
716 s
= strchr (s
, '\0');
717 /* It should be s + size_to_get - 1 but this is safer */
721 /* If it is a comment line then discard it and go around again */
728 /* Remove any line feed. Leave s_eol on the \0 */
732 if (s_eol
> line
&& *(s_eol
-1) == '\r')
736 s_eol
= strchr (s
, '\0');
738 /* If there is a concatenating \\ then go around again */
739 if (s_eol
> line
&& *(s_eol
-1) == '\\')
748 while(c
== ' ' || c
== '\t');
752 fprintf(stderr
,"%S: ERROR - invalid continuation.\n",
763 lineW
= GetWideString(line
);
765 break; /* That is the full virtual line */
768 processRegEntry(lineW
, FALSE
);
769 HeapFree(GetProcessHeap(), 0, lineW
);
771 processRegEntry(NULL
, FALSE
);
773 HeapFree(GetProcessHeap(), 0, line
);
776 static void processRegLinesW(FILE *in
)
778 WCHAR
* buf
= NULL
; /* line read from input stream */
779 ULONG lineSize
= REG_VAL_BUF_SIZE
;
780 size_t CharsInBuf
= -1;
782 WCHAR
* s
; /* The pointer into buf for where the current fgets should read */
783 WCHAR
* line
; /* The start of the current line */
785 buf
= HeapAlloc(GetProcessHeap(), 0, lineSize
* sizeof(WCHAR
));
786 CHECK_ENOUGH_MEMORY(buf
);
793 size_t size_remaining
;
795 WCHAR
*s_eol
= NULL
; /* various local uses */
797 /* Do we need to expand the buffer ? */
798 assert (s
>= buf
&& s
<= buf
+ lineSize
);
799 size_remaining
= lineSize
- (s
-buf
);
800 if (size_remaining
< 2) /* room for 1 character and the \0 */
803 size_t new_size
= lineSize
+ (REG_VAL_BUF_SIZE
/ sizeof(WCHAR
));
804 if (new_size
> lineSize
) /* no arithmetic overflow */
805 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, buf
, new_size
* sizeof(WCHAR
));
808 CHECK_ENOUGH_MEMORY(new_buffer
);
811 s
= buf
+ lineSize
- size_remaining
;
813 size_remaining
= lineSize
- (s
-buf
);
816 /* Get as much as possible into the buffer, terminated either by
817 * eof, error or getting the maximum amount. Abort on error.
819 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
821 CharsInBuf
= fread(s
, sizeof(WCHAR
), size_to_get
- 1, in
);
828 perror ("While reading input");
835 /* It is not clear to me from the definition that the
836 * contents of the buffer are well defined on detecting
837 * an eof without managing to read anything.
842 /* If we didn't read the eol nor the eof go around for the rest */
845 s_eol
= wcschr(line
, '\n');
849 /* Move the stub of the line to the start of the buffer so
850 * we get the maximum space to read into, and so we don't
851 * have to recalculate 'line' if the buffer expands */
852 MoveMemory(buf
, line
, (lstrlenW(line
) + 1) * sizeof(WCHAR
));
854 s
= wcschr(line
, '\0');
858 /* If it is a comment line then discard it and go around again */
865 /* If there is a concatenating \\ then go around again */
866 if ((*(s_eol
-1) == '\\') ||
867 (*(s_eol
-1) == '\r' && *(s_eol
-2) == '\\'))
869 WCHAR
* NextLine
= s_eol
;
871 while(*(NextLine
+1) == ' ' || *(NextLine
+1) == '\t')
876 if(*(s_eol
-1) == '\r')
879 MoveMemory(s_eol
- 1, NextLine
, (CharsInBuf
- (NextLine
- s
) + 1)*sizeof(WCHAR
));
880 CharsInBuf
-= NextLine
- s_eol
+ 1;
885 /* Remove any line feed. Leave s_eol on the \0 */
889 if (s_eol
> buf
&& *(s_eol
-1) == '\r')
896 processRegEntry(line
, TRUE
);
899 continue; /* That is the full virtual line */
903 processRegEntry(NULL
, TRUE
);
905 HeapFree(GetProcessHeap(), 0, buf
);
908 /****************************************************************************
909 * REGPROC_print_error
911 * Print the message for GetLastError
914 static void REGPROC_print_error(void)
920 error_code
= GetLastError ();
921 status
= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
922 NULL
, error_code
, 0, (LPTSTR
) &lpMsgBuf
, 0, NULL
);
925 fprintf(stderr
,"%S: Cannot display message for error %ld, status %ld\n",
926 getAppName(), error_code
, GetLastError());
934 /******************************************************************************
935 * Checks whether the buffer has enough room for the string or required size.
936 * Resizes the buffer if necessary.
939 * buffer - pointer to a buffer for string
940 * len - current length of the buffer in characters.
941 * required_len - length of the string to place to the buffer in characters.
942 * The length does not include the terminating null character.
944 static void REGPROC_resize_char_buffer(WCHAR
**buffer
, DWORD
*len
, DWORD required_len
)
947 if (required_len
> *len
)
951 *buffer
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(**buffer
));
953 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *len
* sizeof(**buffer
));
954 CHECK_ENOUGH_MEMORY(*buffer
);
958 /******************************************************************************
959 * Same as REGPROC_resize_char_buffer() but on a regular buffer.
962 * buffer - pointer to a buffer
963 * len - current size of the buffer in bytes
964 * required_size - size of the data to place in the buffer in bytes
966 static void REGPROC_resize_binary_buffer(BYTE
**buffer
, DWORD
*size
, DWORD required_size
)
968 if (required_size
> *size
)
970 *size
= required_size
;
972 *buffer
= HeapAlloc(GetProcessHeap(), 0, *size
);
974 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *size
);
975 CHECK_ENOUGH_MEMORY(*buffer
);
979 /******************************************************************************
980 * Prints string str to file
982 static void REGPROC_export_string(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, WCHAR
*str
, DWORD str_len
)
987 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ 10);
989 /* escaping characters */
991 for (i
= 0; i
< str_len
; i
++)
998 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
999 (*line_buf
)[pos
++] = '\\';
1000 (*line_buf
)[pos
++] = 'n';
1006 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
1007 (*line_buf
)[pos
++] = '\\';
1011 (*line_buf
)[pos
++] = c
;
1015 (*line_buf
)[pos
] = '\0';
1019 static void REGPROC_export_binary(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, DWORD type
, BYTE
*value
, DWORD value_size
, BOOL unicode
)
1021 DWORD hex_pos
, data_pos
;
1022 const WCHAR
*hex_prefix
;
1023 const WCHAR hex
[] = {'h','e','x',':',0};
1025 const WCHAR concat
[] = {'\\','\n',' ',' ',0};
1026 DWORD concat_prefix
, concat_len
;
1027 const WCHAR newline
[] = {'\n',0};
1028 CHAR
* value_multibyte
= NULL
;
1030 if (type
== REG_BINARY
)
1036 const WCHAR hex_format
[] = {'h','e','x','(','%','u',')',':',0};
1037 hex_prefix
= hex_buf
;
1038 wsprintfW(hex_buf
, hex_format
, type
);
1039 if ((type
== REG_SZ
|| type
== REG_EXPAND_SZ
|| type
== REG_MULTI_SZ
) && !unicode
)
1041 value_multibyte
= GetMultiByteStringN((WCHAR
*)value
, value_size
/ sizeof(WCHAR
), &value_size
);
1042 value
= (BYTE
*)value_multibyte
;
1046 concat_len
= lstrlenW(concat
);
1049 hex_pos
= *line_len
;
1050 *line_len
+= lstrlenW(hex_prefix
);
1051 data_pos
= *line_len
;
1052 *line_len
+= value_size
* 3;
1053 /* - The 2 spaces that concat places at the start of the
1054 * line effectively reduce the space available for data.
1055 * - If the value name and hex prefix are very long
1056 * ( > REG_FILE_HEX_LINE_LEN) then we may overestimate
1057 * the needed number of lines by one. But that's ok.
1058 * - The trailing linefeed takes the place of a comma so
1059 * it's accounted for already.
1061 *line_len
+= *line_len
/ (REG_FILE_HEX_LINE_LEN
- concat_prefix
) * concat_len
;
1062 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
);
1063 lstrcpyW(*line_buf
+ hex_pos
, hex_prefix
);
1066 const WCHAR format
[] = {'%','0','2','x',0};
1069 column
= data_pos
; /* no line wrap yet */
1073 wsprintfW(*line_buf
+ data_pos
, format
, (unsigned int)value
[i
]);
1075 if (++i
== value_size
)
1078 (*line_buf
)[data_pos
++] = ',';
1082 if (column
>= REG_FILE_HEX_LINE_LEN
)
1084 lstrcpyW(*line_buf
+ data_pos
, concat
);
1085 data_pos
+= concat_len
;
1086 column
= concat_prefix
;
1090 lstrcpyW(*line_buf
+ data_pos
, newline
);
1091 HeapFree(GetProcessHeap(), 0, value_multibyte
);
1094 /******************************************************************************
1095 * Writes the given line to a file, in multi-byte or wide characters
1097 static void REGPROC_write_line(FILE *file
, const WCHAR
* str
, BOOL unicode
)
1102 for(i
= 0; str
[i
]; i
++)
1104 if (str
[i
] == L
'\n')
1105 fputwc(L
'\r', file
);
1106 fputwc(str
[i
], file
);
1111 char* strA
= GetMultiByteString(str
);
1113 HeapFree(GetProcessHeap(), 0, strA
);
1117 /******************************************************************************
1118 * Writes contents of the registry key to the specified file stream.
1121 * file - writable file stream to export registry branch to.
1122 * key - registry branch to export.
1123 * reg_key_name_buf - name of the key with registry class.
1124 * Is resized if necessary.
1125 * reg_key_name_size - length of the buffer for the registry class in characters.
1126 * val_name_buf - buffer for storing value name.
1127 * Is resized if necessary.
1128 * val_name_size - length of the buffer for storing value names in characters.
1129 * val_buf - buffer for storing values while extracting.
1130 * Is resized if necessary.
1131 * val_size - size of the buffer for storing values in bytes.
1133 static void export_hkey(FILE *file
, HKEY key
,
1134 WCHAR
**reg_key_name_buf
, DWORD
*reg_key_name_size
,
1135 WCHAR
**val_name_buf
, DWORD
*val_name_size
,
1136 BYTE
**val_buf
, DWORD
*val_size
,
1137 WCHAR
**line_buf
, DWORD
*line_buf_size
,
1140 DWORD max_sub_key_len
;
1141 DWORD max_val_name_len
;
1147 WCHAR key_format
[] = {'\n','[','%','s',']','\n',0};
1149 /* get size information and resize the buffers if necessary */
1150 if (RegQueryInfoKeyW(key
, NULL
, NULL
, NULL
, NULL
,
1151 &max_sub_key_len
, NULL
,
1152 NULL
, &max_val_name_len
, &max_val_size
, NULL
, NULL
1155 REGPROC_print_error();
1157 curr_len
= lstrlenW(*reg_key_name_buf
);
1158 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
,
1159 max_sub_key_len
+ curr_len
+ 1);
1160 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
,
1162 REGPROC_resize_binary_buffer(val_buf
, val_size
, max_val_size
);
1163 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, lstrlenW(*reg_key_name_buf
) + 4);
1164 /* output data for the current key */
1165 wsprintfW(*line_buf
, key_format
, *reg_key_name_buf
);
1166 REGPROC_write_line(file
, *line_buf
, unicode
);
1168 /* print all the values */
1174 DWORD val_name_size1
= *val_name_size
;
1175 DWORD val_size1
= *val_size
;
1176 ret
= RegEnumValueW(key
, i
, *val_name_buf
, &val_name_size1
, NULL
,
1177 &value_type
, *val_buf
, &val_size1
);
1178 if (ret
== ERROR_MORE_DATA
)
1180 /* Increase the size of the buffers and retry */
1181 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, val_name_size1
);
1182 REGPROC_resize_binary_buffer(val_buf
, val_size
, val_size1
);
1184 else if (ret
!= ERROR_SUCCESS
)
1187 if (ret
!= ERROR_NO_MORE_ITEMS
)
1189 REGPROC_print_error();
1197 if ((*val_name_buf
)[0])
1199 const WCHAR val_start
[] = {'"','%','s','"','=',0};
1202 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, *val_name_buf
, lstrlenW(*val_name_buf
));
1203 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, lstrlenW(*line_buf
) + 1);
1204 lstrcpyW(*val_name_buf
, *line_buf
);
1206 line_len
= 3 + lstrlenW(*val_name_buf
);
1207 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1208 wsprintfW(*line_buf
, val_start
, *val_name_buf
);
1212 const WCHAR std_val
[] = {'@','=',0};
1214 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1215 lstrcpyW(*line_buf
, std_val
);
1222 WCHAR
* wstr
= (WCHAR
*)*val_buf
;
1224 if (val_size1
< sizeof(WCHAR
) || val_size1
% sizeof(WCHAR
) ||
1225 wstr
[val_size1
/ sizeof(WCHAR
) - 1])
1227 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1231 const WCHAR start
[] = {'"',0};
1232 const WCHAR end
[] = {'"','\n',0};
1235 len
= lstrlenW(start
);
1236 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ len
);
1237 lstrcpyW(*line_buf
+ line_len
, start
);
1240 /* At this point we know wstr is '\0'-terminated
1241 * so we can substract 1 from the size
1243 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, wstr
, val_size1
/ sizeof(WCHAR
) - 1);
1245 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ lstrlenW(end
));
1246 lstrcpyW(*line_buf
+ line_len
, end
);
1253 WCHAR format
[] = {'d','w','o','r','d',':','%','0','8','x','\n',0};
1255 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ 15);
1256 wsprintfW(*line_buf
+ line_len
, format
, *((DWORD
*)*val_buf
));
1262 char* key_nameA
= GetMultiByteString(*reg_key_name_buf
);
1263 char* value_nameA
= GetMultiByteString(*val_name_buf
);
1264 fprintf(stderr
,"%S: warning - unsupported registry format '%ld', "
1265 "treat as binary\n",
1266 getAppName(), value_type
);
1267 fprintf(stderr
,"key name: \"%s\"\n", key_nameA
);
1268 fprintf(stderr
,"value name:\"%s\"\n\n", value_nameA
);
1269 HeapFree(GetProcessHeap(), 0, key_nameA
);
1270 HeapFree(GetProcessHeap(), 0, value_nameA
);
1277 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1279 REGPROC_write_line(file
, *line_buf
, unicode
);
1285 (*reg_key_name_buf
)[curr_len
] = '\\';
1288 DWORD buf_size
= *reg_key_name_size
- curr_len
- 1;
1290 ret
= RegEnumKeyExW(key
, i
, *reg_key_name_buf
+ curr_len
+ 1, &buf_size
,
1291 NULL
, NULL
, NULL
, NULL
);
1292 if (ret
== ERROR_MORE_DATA
)
1294 /* Increase the size of the buffer and retry */
1295 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
, curr_len
+ 1 + buf_size
);
1297 else if (ret
!= ERROR_SUCCESS
)
1300 if (ret
!= ERROR_NO_MORE_ITEMS
)
1302 REGPROC_print_error();
1310 if (RegOpenKeyW(key
, *reg_key_name_buf
+ curr_len
+ 1,
1311 &subkey
) == ERROR_SUCCESS
)
1313 export_hkey(file
, subkey
, reg_key_name_buf
, reg_key_name_size
,
1314 val_name_buf
, val_name_size
, val_buf
, val_size
,
1315 line_buf
, line_buf_size
, unicode
);
1316 RegCloseKey(subkey
);
1320 REGPROC_print_error();
1324 (*reg_key_name_buf
)[curr_len
] = '\0';
1327 /******************************************************************************
1328 * Open file for export.
1330 static FILE *REGPROC_open_export_file(WCHAR
*file_name
, BOOL unicode
)
1335 if (wcsncmp(file_name
, &dash
, 1) == 0)
1340 file
= _wfopen(file_name
, L
"wb");
1342 file
= _wfopen(file_name
, L
"w");
1345 CHAR
* file_nameA
= GetMultiByteString(file_name
);
1347 fprintf(stderr
,"%S: Can't open file \"%s\"\n", getAppName(), file_nameA
);
1348 HeapFree(GetProcessHeap(), 0, file_nameA
);
1354 const BYTE unicode_seq
[] = {0xff,0xfe};
1355 const WCHAR header
[] = L
"Windows Registry Editor Version 5.00\r\n";
1356 fwrite(unicode_seq
, sizeof(BYTE
), COUNT_OF(unicode_seq
), file
);
1357 fwrite(header
, sizeof(WCHAR
), lstrlenW(header
), file
);
1361 fputs("REGEDIT4\n", file
);
1367 /******************************************************************************
1368 * Writes contents of the registry key to the specified file stream.
1371 * file_name - name of a file to export registry branch to.
1372 * reg_key_name - registry branch to export. The whole registry is exported if
1373 * reg_key_name is NULL or contains an empty string.
1375 BOOL
export_registry_key(WCHAR
*file_name
, WCHAR
*reg_key_name
, DWORD format
)
1377 WCHAR
*reg_key_name_buf
;
1378 WCHAR
*val_name_buf
;
1381 DWORD reg_key_name_size
= KEY_MAX_LEN
;
1382 DWORD val_name_size
= KEY_MAX_LEN
;
1383 DWORD val_size
= REG_VAL_BUF_SIZE
;
1384 DWORD line_buf_size
= KEY_MAX_LEN
+ REG_VAL_BUF_SIZE
;
1386 BOOL unicode
= (format
== REG_FORMAT_5
);
1388 reg_key_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1389 reg_key_name_size
* sizeof(*reg_key_name_buf
));
1390 val_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1391 val_name_size
* sizeof(*val_name_buf
));
1392 val_buf
= HeapAlloc(GetProcessHeap(), 0, val_size
);
1393 line_buf
= HeapAlloc(GetProcessHeap(), 0, line_buf_size
* sizeof(*line_buf
));
1394 CHECK_ENOUGH_MEMORY(reg_key_name_buf
&& val_name_buf
&& val_buf
&& line_buf
);
1396 if (reg_key_name
&& reg_key_name
[0])
1399 WCHAR
*branch_name
= NULL
;
1402 REGPROC_resize_char_buffer(®_key_name_buf
, ®_key_name_size
,
1403 lstrlenW(reg_key_name
));
1404 lstrcpyW(reg_key_name_buf
, reg_key_name
);
1406 /* open the specified key */
1407 if (!parseKeyName(reg_key_name
, ®_key_class
, &branch_name
))
1409 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1410 fprintf(stderr
,"%S: Incorrect registry class specification in '%s'\n",
1411 getAppName(), key_nameA
);
1412 HeapFree(GetProcessHeap(), 0, key_nameA
);
1415 if (!branch_name
[0])
1417 /* no branch - registry class is specified */
1418 file
= REGPROC_open_export_file(file_name
, unicode
);
1419 export_hkey(file
, reg_key_class
,
1420 ®_key_name_buf
, ®_key_name_size
,
1421 &val_name_buf
, &val_name_size
,
1422 &val_buf
, &val_size
, &line_buf
,
1423 &line_buf_size
, unicode
);
1425 else if (RegOpenKeyW(reg_key_class
, branch_name
, &key
) == ERROR_SUCCESS
)
1427 file
= REGPROC_open_export_file(file_name
, unicode
);
1428 export_hkey(file
, key
,
1429 ®_key_name_buf
, ®_key_name_size
,
1430 &val_name_buf
, &val_name_size
,
1431 &val_buf
, &val_size
, &line_buf
,
1432 &line_buf_size
, unicode
);
1437 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1438 fprintf(stderr
,"%S: Can't export. Registry key '%s' does not exist!\n",
1439 getAppName(), key_nameA
);
1440 HeapFree(GetProcessHeap(), 0, key_nameA
);
1441 REGPROC_print_error();
1448 /* export all registry classes */
1449 file
= REGPROC_open_export_file(file_name
, unicode
);
1450 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++)
1452 /* do not export HKEY_CLASSES_ROOT */
1453 if (reg_class_keys
[i
] != HKEY_CLASSES_ROOT
&&
1454 reg_class_keys
[i
] != HKEY_CURRENT_USER
&&
1455 reg_class_keys
[i
] != HKEY_CURRENT_CONFIG
&&
1456 reg_class_keys
[i
] != HKEY_DYN_DATA
)
1458 lstrcpyW(reg_key_name_buf
, reg_class_namesW
[i
]);
1459 export_hkey(file
, reg_class_keys
[i
],
1460 ®_key_name_buf
, ®_key_name_size
,
1461 &val_name_buf
, &val_name_size
,
1462 &val_buf
, &val_size
, &line_buf
,
1463 &line_buf_size
, unicode
);
1472 HeapFree(GetProcessHeap(), 0, reg_key_name
);
1473 HeapFree(GetProcessHeap(), 0, val_name_buf
);
1474 HeapFree(GetProcessHeap(), 0, val_buf
);
1475 HeapFree(GetProcessHeap(), 0, line_buf
);
1479 /******************************************************************************
1480 * Reads contents of the specified file into the registry.
1482 BOOL
import_registry_file(FILE* reg_file
)
1487 if (fread( s
, 2, 1, reg_file
) == 1)
1489 if (s
[0] == 0xff && s
[1] == 0xfe)
1491 processRegLinesW(reg_file
);
1495 fseek(reg_file
, 0, SEEK_SET
);
1496 processRegLinesA(reg_file
);
1504 /******************************************************************************
1505 * Removes the registry key with all subkeys. Parses full key name.
1508 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1509 * empty, points to register key class, does not exist.
1511 void delete_registry_key(WCHAR
*reg_key_name
)
1513 WCHAR
*key_name
= NULL
;
1516 if (!reg_key_name
|| !reg_key_name
[0])
1519 if (!parseKeyName(reg_key_name
, &key_class
, &key_name
))
1521 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1522 fprintf(stderr
,"%S: Incorrect registry class specification in '%s'\n",
1523 getAppName(), reg_key_nameA
);
1524 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1529 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1530 fprintf(stderr
,"%S: Can't delete registry class '%s'\n",
1531 getAppName(), reg_key_nameA
);
1532 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1536 SHDeleteKey(key_class
, key_name
);