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
[] =
35 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
36 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
39 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
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(
462 keyClass
, /* Class */
463 keyPath
, /* Sub Key */
465 NULL
, /* object type */
466 REG_OPTION_NON_VOLATILE
, /* option, REG_OPTION_NON_VOLATILE ... */
467 KEY_ALL_ACCESS
, /* access mask, KEY_ALL_ACCESS */
468 NULL
, /* security attribute */
469 ¤tKeyHandle
, /* result */
470 &dwDisp
); /* disposition, REG_CREATED_NEW_KEY or
471 REG_OPENED_EXISTING_KEY */
473 if (res
== ERROR_SUCCESS
)
474 currentKeyName
= GetMultiByteString(stdInput
);
476 currentKeyHandle
= NULL
;
482 /******************************************************************************
483 * Close the currently opened key.
485 static void closeKey(void)
487 if (currentKeyHandle
)
489 HeapFree(GetProcessHeap(), 0, currentKeyName
);
490 RegCloseKey(currentKeyHandle
);
491 currentKeyHandle
= NULL
;
495 /******************************************************************************
496 * This function is a wrapper for the setValue function. It prepares the
497 * land and cleans the area once completed.
498 * Note: this function modifies the line parameter.
500 * line - registry file unwrapped line. Should have the registry value name and
501 * complete registry value data.
503 static void processSetValue(WCHAR
* line
, BOOL is_unicode
)
505 WCHAR
* val_name
; /* registry value name */
506 WCHAR
* val_data
; /* registry value data */
507 int line_idx
= 0; /* current character under analysis */
511 while ( iswspace(line
[line_idx
]) ) line_idx
++;
512 if (line
[line_idx
] == '@' && line
[line_idx
+ 1] == '=')
514 line
[line_idx
] = '\0';
518 else if (line
[line_idx
] == '\"')
521 val_name
= line
+ line_idx
;
524 if (line
[line_idx
] == '\\') /* skip escaped character */
530 if (line
[line_idx
] == '\"')
532 line
[line_idx
] = '\0';
542 while ( iswspace(line
[line_idx
]) ) line_idx
++;
543 if (line
[line_idx
] != '=')
546 line
[line_idx
] = '\"';
547 lineA
= GetMultiByteString(line
);
548 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", lineA
);
549 HeapFree(GetProcessHeap(), 0, lineA
);
556 char* lineA
= GetMultiByteString(line
);
557 fprintf(stderr
,"Warning! unrecognized line:\n%s\n", lineA
);
558 HeapFree(GetProcessHeap(), 0, lineA
);
561 line_idx
++; /* skip the '=' character */
563 while ( iswspace(line
[line_idx
]) ) line_idx
++;
564 val_data
= line
+ line_idx
;
565 /* trim trailing blanks */
566 line_idx
= lstrlenW(val_data
);
567 while (line_idx
> 0 && iswspace(val_data
[line_idx
-1])) line_idx
--;
568 val_data
[line_idx
] = '\0';
570 REGPROC_unescape_string(val_name
);
571 res
= setValue(val_name
, val_data
, is_unicode
);
572 if ( res
!= ERROR_SUCCESS
)
574 char* val_nameA
= GetMultiByteString(val_name
);
575 char* val_dataA
= GetMultiByteString(val_data
);
576 fprintf(stderr
,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
581 HeapFree(GetProcessHeap(), 0, val_nameA
);
582 HeapFree(GetProcessHeap(), 0, val_dataA
);
586 /******************************************************************************
587 * This function receives the currently read entry and performs the
588 * corresponding action.
589 * isUnicode affects parsing of REG_MULTI_SZ values
591 static void processRegEntry(WCHAR
* stdInput
, BOOL isUnicode
)
594 * We encountered the end of the file, make sure we
595 * close the opened key and exit
597 if (stdInput
== NULL
)
603 if ( stdInput
[0] == L
'[') /* We are reading a new key */
606 closeKey(); /* Close the previous key */
608 /* Get rid of the square brackets */
610 keyEnd
= wcsrchr(stdInput
, L
']');
614 /* delete the key if we encounter '-' at the start of reg key */
615 if ( stdInput
[0] == '-')
617 delete_registry_key(stdInput
+ 1);
619 else if ( openKeyW(stdInput
) != ERROR_SUCCESS
)
621 char* stdInputA
= GetMultiByteString(stdInput
);
622 fprintf(stderr
,"%s: setValue failed to open key %s\n",
623 getAppName(), stdInputA
);
624 HeapFree(GetProcessHeap(), 0, stdInputA
);
627 else if( currentKeyHandle
&&
628 (( stdInput
[0] == '@') || /* reading a default @=data pair */
629 ( stdInput
[0] == '\"'))) /* reading a new value=data pair */
631 processSetValue(stdInput
, isUnicode
);
635 /* Since we are assuming that the file format is valid we must be
636 * reading a blank line which indicates the end of this key processing
642 /******************************************************************************
643 * Processes a registry file.
644 * Correctly processes comments (in # form), line continuation.
647 * in - input stream to read from
649 static void processRegLinesA(FILE *in
)
651 LPSTR line
= NULL
; /* line read from input stream */
652 ULONG lineSize
= REG_VAL_BUF_SIZE
;
654 line
= HeapAlloc(GetProcessHeap(), 0, lineSize
);
655 CHECK_ENOUGH_MEMORY(line
);
659 LPSTR s
; /* The pointer into line for where the current fgets should read */
666 size_t size_remaining
;
668 char *s_eol
; /* various local uses */
670 /* Do we need to expand the buffer ? */
671 assert (s
>= line
&& s
<= line
+ lineSize
);
672 size_remaining
= lineSize
- (s
-line
);
673 if (size_remaining
< 2) /* room for 1 character and the \0 */
676 size_t new_size
= lineSize
+ REG_VAL_BUF_SIZE
;
677 if (new_size
> lineSize
) /* no arithmetic overflow */
678 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, line
, new_size
);
681 CHECK_ENOUGH_MEMORY(new_buffer
);
683 s
= line
+ lineSize
- size_remaining
;
685 size_remaining
= lineSize
- (s
-line
);
688 /* Get as much as possible into the buffer, terminated either by
689 * eof, error, eol or getting the maximum amount. Abort on error.
691 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
693 check
= fgets (s
, size_to_get
, in
);
699 perror ("While reading input");
706 /* It is not clear to me from the definition that the
707 * contents of the buffer are well defined on detecting
708 * an eof without managing to read anything.
713 /* If we didn't read the eol nor the eof go around for the rest */
714 s_eol
= strchr (s
, '\n');
715 if (!feof (in
) && !s_eol
)
717 s
= strchr (s
, '\0');
718 /* It should be s + size_to_get - 1 but this is safer */
722 /* If it is a comment line then discard it and go around again */
729 /* Remove any line feed. Leave s_eol on the \0 */
733 if (s_eol
> line
&& *(s_eol
-1) == '\r')
737 s_eol
= strchr (s
, '\0');
739 /* If there is a concatenating \\ then go around again */
740 if (s_eol
> line
&& *(s_eol
-1) == '\\')
749 while(c
== ' ' || c
== '\t');
753 fprintf(stderr
,"%s: ERROR - invalid continuation.\n",
764 lineW
= GetWideString(line
);
766 break; /* That is the full virtual line */
769 processRegEntry(lineW
, FALSE
);
770 HeapFree(GetProcessHeap(), 0, lineW
);
772 processRegEntry(NULL
, FALSE
);
774 HeapFree(GetProcessHeap(), 0, line
);
777 static void processRegLinesW(FILE *in
)
779 WCHAR
* buf
= NULL
; /* line read from input stream */
780 ULONG lineSize
= REG_VAL_BUF_SIZE
;
781 size_t CharsInBuf
= -1;
783 WCHAR
* s
; /* The pointer into buf for where the current fgets should read */
784 WCHAR
* line
; /* The start of the current line */
786 buf
= HeapAlloc(GetProcessHeap(), 0, lineSize
* sizeof(WCHAR
));
787 CHECK_ENOUGH_MEMORY(buf
);
794 size_t size_remaining
;
796 WCHAR
*s_eol
= NULL
; /* various local uses */
798 /* Do we need to expand the buffer ? */
799 assert (s
>= buf
&& s
<= buf
+ lineSize
);
800 size_remaining
= lineSize
- (s
-buf
);
801 if (size_remaining
< 2) /* room for 1 character and the \0 */
804 size_t new_size
= lineSize
+ (REG_VAL_BUF_SIZE
/ sizeof(WCHAR
));
805 if (new_size
> lineSize
) /* no arithmetic overflow */
806 new_buffer
= HeapReAlloc (GetProcessHeap(), 0, buf
, new_size
* sizeof(WCHAR
));
809 CHECK_ENOUGH_MEMORY(new_buffer
);
812 s
= buf
+ lineSize
- size_remaining
;
814 size_remaining
= lineSize
- (s
-buf
);
817 /* Get as much as possible into the buffer, terminated either by
818 * eof, error or getting the maximum amount. Abort on error.
820 size_to_get
= (size_remaining
> INT_MAX
? INT_MAX
: size_remaining
);
822 CharsInBuf
= fread(s
, sizeof(WCHAR
), size_to_get
- 1, in
);
829 perror ("While reading input");
836 /* It is not clear to me from the definition that the
837 * contents of the buffer are well defined on detecting
838 * an eof without managing to read anything.
843 /* If we didn't read the eol nor the eof go around for the rest */
846 s_eol
= wcschr(line
, '\n');
850 /* Move the stub of the line to the start of the buffer so
851 * we get the maximum space to read into, and so we don't
852 * have to recalculate 'line' if the buffer expands */
853 MoveMemory(buf
, line
, (lstrlenW(line
) + 1) * sizeof(WCHAR
));
855 s
= wcschr(line
, '\0');
859 /* If it is a comment line then discard it and go around again */
866 /* If there is a concatenating \\ then go around again */
867 if ((*(s_eol
-1) == '\\') ||
868 (*(s_eol
-1) == '\r' && *(s_eol
-2) == '\\'))
870 WCHAR
* NextLine
= s_eol
;
872 while(*(NextLine
+1) == ' ' || *(NextLine
+1) == '\t')
877 if(*(s_eol
-1) == '\r')
880 MoveMemory(s_eol
- 1, NextLine
, (CharsInBuf
- (NextLine
- s
) + 1)*sizeof(WCHAR
));
881 CharsInBuf
-= NextLine
- s_eol
+ 1;
886 /* Remove any line feed. Leave s_eol on the \0 */
890 if (s_eol
> buf
&& *(s_eol
-1) == '\r')
897 processRegEntry(line
, TRUE
);
900 continue; /* That is the full virtual line */
904 processRegEntry(NULL
, TRUE
);
906 HeapFree(GetProcessHeap(), 0, buf
);
909 /****************************************************************************
910 * REGPROC_print_error
912 * Print the message for GetLastError
915 static void REGPROC_print_error(void)
921 error_code
= GetLastError ();
922 status
= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
923 NULL
, error_code
, 0, (LPTSTR
) &lpMsgBuf
, 0, NULL
);
926 fprintf(stderr
,"%s: Cannot display message for error %ld, status %ld\n",
927 getAppName(), error_code
, GetLastError());
935 /******************************************************************************
936 * Checks whether the buffer has enough room for the string or required size.
937 * Resizes the buffer if necessary.
940 * buffer - pointer to a buffer for string
941 * len - current length of the buffer in characters.
942 * required_len - length of the string to place to the buffer in characters.
943 * The length does not include the terminating null character.
945 static void REGPROC_resize_char_buffer(WCHAR
**buffer
, DWORD
*len
, DWORD required_len
)
948 if (required_len
> *len
)
952 *buffer
= HeapAlloc(GetProcessHeap(), 0, *len
* sizeof(**buffer
));
954 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *len
* sizeof(**buffer
));
955 CHECK_ENOUGH_MEMORY(*buffer
);
959 /******************************************************************************
960 * Same as REGPROC_resize_char_buffer() but on a regular buffer.
963 * buffer - pointer to a buffer
964 * len - current size of the buffer in bytes
965 * required_size - size of the data to place in the buffer in bytes
967 static void REGPROC_resize_binary_buffer(BYTE
**buffer
, DWORD
*size
, DWORD required_size
)
969 if (required_size
> *size
)
971 *size
= required_size
;
973 *buffer
= HeapAlloc(GetProcessHeap(), 0, *size
);
975 *buffer
= HeapReAlloc(GetProcessHeap(), 0, *buffer
, *size
);
976 CHECK_ENOUGH_MEMORY(*buffer
);
980 /******************************************************************************
981 * Prints string str to file
983 static void REGPROC_export_string(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, WCHAR
*str
, DWORD str_len
)
988 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ 10);
990 /* escaping characters */
992 for (i
= 0; i
< str_len
; i
++)
999 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
1000 (*line_buf
)[pos
++] = '\\';
1001 (*line_buf
)[pos
++] = 'n';
1007 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
+ str_len
+ extra
);
1008 (*line_buf
)[pos
++] = '\\';
1012 (*line_buf
)[pos
++] = c
;
1016 (*line_buf
)[pos
] = '\0';
1020 static void REGPROC_export_binary(WCHAR
**line_buf
, DWORD
*line_buf_size
, DWORD
*line_len
, DWORD type
, BYTE
*value
, DWORD value_size
, BOOL unicode
)
1022 DWORD hex_pos
, data_pos
;
1023 const WCHAR
*hex_prefix
;
1024 const WCHAR hex
[] = {'h','e','x',':',0};
1026 const WCHAR concat
[] = {'\\','\n',' ',' ',0};
1027 DWORD concat_prefix
, concat_len
;
1028 const WCHAR newline
[] = {'\n',0};
1029 CHAR
* value_multibyte
= NULL
;
1031 if (type
== REG_BINARY
)
1037 const WCHAR hex_format
[] = {'h','e','x','(','%','u',')',':',0};
1038 hex_prefix
= hex_buf
;
1039 wsprintfW(hex_buf
, hex_format
, type
);
1040 if ((type
== REG_SZ
|| type
== REG_EXPAND_SZ
|| type
== REG_MULTI_SZ
) && !unicode
)
1042 value_multibyte
= GetMultiByteStringN((WCHAR
*)value
, value_size
/ sizeof(WCHAR
), &value_size
);
1043 value
= (BYTE
*)value_multibyte
;
1047 concat_len
= lstrlenW(concat
);
1050 hex_pos
= *line_len
;
1051 *line_len
+= lstrlenW(hex_prefix
);
1052 data_pos
= *line_len
;
1053 *line_len
+= value_size
* 3;
1054 /* - The 2 spaces that concat places at the start of the
1055 * line effectively reduce the space available for data.
1056 * - If the value name and hex prefix are very long
1057 * ( > REG_FILE_HEX_LINE_LEN) then we may overestimate
1058 * the needed number of lines by one. But that's ok.
1059 * - The trailing linefeed takes the place of a comma so
1060 * it's accounted for already.
1062 *line_len
+= *line_len
/ (REG_FILE_HEX_LINE_LEN
- concat_prefix
) * concat_len
;
1063 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, *line_len
);
1064 lstrcpyW(*line_buf
+ hex_pos
, hex_prefix
);
1067 const WCHAR format
[] = {'%','0','2','x',0};
1070 column
= data_pos
; /* no line wrap yet */
1074 wsprintfW(*line_buf
+ data_pos
, format
, (unsigned int)value
[i
]);
1076 if (++i
== value_size
)
1079 (*line_buf
)[data_pos
++] = ',';
1083 if (column
>= REG_FILE_HEX_LINE_LEN
)
1085 lstrcpyW(*line_buf
+ data_pos
, concat
);
1086 data_pos
+= concat_len
;
1087 column
= concat_prefix
;
1091 lstrcpyW(*line_buf
+ data_pos
, newline
);
1092 HeapFree(GetProcessHeap(), 0, value_multibyte
);
1095 /******************************************************************************
1096 * Writes the given line to a file, in multi-byte or wide characters
1098 static void REGPROC_write_line(FILE *file
, const WCHAR
* str
, BOOL unicode
)
1103 for(i
= 0; str
[i
]; i
++)
1105 if (str
[i
] == L
'\n')
1106 fputwc(L
'\r', file
);
1107 fputwc(str
[i
], file
);
1112 char* strA
= GetMultiByteString(str
);
1114 HeapFree(GetProcessHeap(), 0, strA
);
1118 /******************************************************************************
1119 * Writes contents of the registry key to the specified file stream.
1122 * file - writable file stream to export registry branch to.
1123 * key - registry branch to export.
1124 * reg_key_name_buf - name of the key with registry class.
1125 * Is resized if necessary.
1126 * reg_key_name_size - length of the buffer for the registry class in characters.
1127 * val_name_buf - buffer for storing value name.
1128 * Is resized if necessary.
1129 * val_name_size - length of the buffer for storing value names in characters.
1130 * val_buf - buffer for storing values while extracting.
1131 * Is resized if necessary.
1132 * val_size - size of the buffer for storing values in bytes.
1134 static void export_hkey(FILE *file
, HKEY key
,
1135 WCHAR
**reg_key_name_buf
, DWORD
*reg_key_name_size
,
1136 WCHAR
**val_name_buf
, DWORD
*val_name_size
,
1137 BYTE
**val_buf
, DWORD
*val_size
,
1138 WCHAR
**line_buf
, DWORD
*line_buf_size
,
1141 DWORD max_sub_key_len
;
1142 DWORD max_val_name_len
;
1148 WCHAR key_format
[] = {'\n','[','%','s',']','\n',0};
1150 /* get size information and resize the buffers if necessary */
1151 if (RegQueryInfoKeyW(key
, NULL
, NULL
, NULL
, NULL
,
1152 &max_sub_key_len
, NULL
,
1153 NULL
, &max_val_name_len
, &max_val_size
, NULL
, NULL
1156 REGPROC_print_error();
1158 curr_len
= lstrlenW(*reg_key_name_buf
);
1159 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
,
1160 max_sub_key_len
+ curr_len
+ 1);
1161 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
,
1163 REGPROC_resize_binary_buffer(val_buf
, val_size
, max_val_size
);
1164 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, lstrlenW(*reg_key_name_buf
) + 4);
1165 /* output data for the current key */
1166 wsprintfW(*line_buf
, key_format
, *reg_key_name_buf
);
1167 REGPROC_write_line(file
, *line_buf
, unicode
);
1169 /* print all the values */
1175 DWORD val_name_size1
= *val_name_size
;
1176 DWORD val_size1
= *val_size
;
1177 ret
= RegEnumValueW(key
, i
, *val_name_buf
, &val_name_size1
, NULL
,
1178 &value_type
, *val_buf
, &val_size1
);
1179 if (ret
== ERROR_MORE_DATA
)
1181 /* Increase the size of the buffers and retry */
1182 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, val_name_size1
);
1183 REGPROC_resize_binary_buffer(val_buf
, val_size
, val_size1
);
1185 else if (ret
!= ERROR_SUCCESS
)
1188 if (ret
!= ERROR_NO_MORE_ITEMS
)
1190 REGPROC_print_error();
1198 if ((*val_name_buf
)[0])
1200 const WCHAR val_start
[] = {'"','%','s','"','=',0};
1203 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, *val_name_buf
, lstrlenW(*val_name_buf
));
1204 REGPROC_resize_char_buffer(val_name_buf
, val_name_size
, lstrlenW(*line_buf
) + 1);
1205 lstrcpyW(*val_name_buf
, *line_buf
);
1207 line_len
= 3 + lstrlenW(*val_name_buf
);
1208 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1209 wsprintfW(*line_buf
, val_start
, *val_name_buf
);
1213 const WCHAR std_val
[] = {'@','=',0};
1215 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
);
1216 lstrcpyW(*line_buf
, std_val
);
1223 WCHAR
* wstr
= (WCHAR
*)*val_buf
;
1225 if (val_size1
< sizeof(WCHAR
) || val_size1
% sizeof(WCHAR
) ||
1226 wstr
[val_size1
/ sizeof(WCHAR
) - 1])
1228 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1232 const WCHAR start
[] = {'"',0};
1233 const WCHAR end
[] = {'"','\n',0};
1236 len
= lstrlenW(start
);
1237 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ len
);
1238 lstrcpyW(*line_buf
+ line_len
, start
);
1241 /* At this point we know wstr is '\0'-terminated
1242 * so we can substract 1 from the size
1244 REGPROC_export_string(line_buf
, line_buf_size
, &line_len
, wstr
, val_size1
/ sizeof(WCHAR
) - 1);
1246 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ lstrlenW(end
));
1247 lstrcpyW(*line_buf
+ line_len
, end
);
1254 WCHAR format
[] = {'d','w','o','r','d',':','%','0','8','x','\n',0};
1256 REGPROC_resize_char_buffer(line_buf
, line_buf_size
, line_len
+ 15);
1257 wsprintfW(*line_buf
+ line_len
, format
, *((DWORD
*)*val_buf
));
1263 char* key_nameA
= GetMultiByteString(*reg_key_name_buf
);
1264 char* value_nameA
= GetMultiByteString(*val_name_buf
);
1265 fprintf(stderr
,"%s: warning - unsupported registry format '%ld', "
1266 "treat as binary\n",
1267 getAppName(), value_type
);
1268 fprintf(stderr
,"key name: \"%s\"\n", key_nameA
);
1269 fprintf(stderr
,"value name:\"%s\"\n\n", value_nameA
);
1270 HeapFree(GetProcessHeap(), 0, key_nameA
);
1271 HeapFree(GetProcessHeap(), 0, value_nameA
);
1278 REGPROC_export_binary(line_buf
, line_buf_size
, &line_len
, value_type
, *val_buf
, val_size1
, unicode
);
1280 REGPROC_write_line(file
, *line_buf
, unicode
);
1286 (*reg_key_name_buf
)[curr_len
] = '\\';
1289 DWORD buf_size
= *reg_key_name_size
- curr_len
- 1;
1291 ret
= RegEnumKeyExW(key
, i
, *reg_key_name_buf
+ curr_len
+ 1, &buf_size
,
1292 NULL
, NULL
, NULL
, NULL
);
1293 if (ret
== ERROR_MORE_DATA
)
1295 /* Increase the size of the buffer and retry */
1296 REGPROC_resize_char_buffer(reg_key_name_buf
, reg_key_name_size
, curr_len
+ 1 + buf_size
);
1298 else if (ret
!= ERROR_SUCCESS
)
1301 if (ret
!= ERROR_NO_MORE_ITEMS
)
1303 REGPROC_print_error();
1311 if (RegOpenKeyW(key
, *reg_key_name_buf
+ curr_len
+ 1,
1312 &subkey
) == ERROR_SUCCESS
)
1314 export_hkey(file
, subkey
, reg_key_name_buf
, reg_key_name_size
,
1315 val_name_buf
, val_name_size
, val_buf
, val_size
,
1316 line_buf
, line_buf_size
, unicode
);
1317 RegCloseKey(subkey
);
1321 REGPROC_print_error();
1325 (*reg_key_name_buf
)[curr_len
] = '\0';
1328 /******************************************************************************
1329 * Open file for export.
1331 static FILE *REGPROC_open_export_file(WCHAR
*file_name
, BOOL unicode
)
1336 if (wcsncmp(file_name
, &dash
, 1) == 0)
1341 file
= _wfopen(file_name
, L
"wb");
1343 file
= _wfopen(file_name
, L
"w");
1346 CHAR
* file_nameA
= GetMultiByteString(file_name
);
1348 fprintf(stderr
,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA
);
1349 HeapFree(GetProcessHeap(), 0, file_nameA
);
1355 const BYTE unicode_seq
[] = {0xff,0xfe};
1356 const WCHAR header
[] = L
"Windows Registry Editor Version 5.00\r\n";
1357 fwrite(unicode_seq
, sizeof(BYTE
), COUNT_OF(unicode_seq
), file
);
1358 fwrite(header
, sizeof(WCHAR
), lstrlenW(header
), file
);
1362 fputs("REGEDIT4\n", file
);
1368 /******************************************************************************
1369 * Writes contents of the registry key to the specified file stream.
1372 * file_name - name of a file to export registry branch to.
1373 * reg_key_name - registry branch to export. The whole registry is exported if
1374 * reg_key_name is NULL or contains an empty string.
1376 BOOL
export_registry_key(WCHAR
*file_name
, WCHAR
*reg_key_name
, DWORD format
)
1378 WCHAR
*reg_key_name_buf
;
1379 WCHAR
*val_name_buf
;
1382 DWORD reg_key_name_size
= KEY_MAX_LEN
;
1383 DWORD val_name_size
= KEY_MAX_LEN
;
1384 DWORD val_size
= REG_VAL_BUF_SIZE
;
1385 DWORD line_buf_size
= KEY_MAX_LEN
+ REG_VAL_BUF_SIZE
;
1387 BOOL unicode
= (format
== REG_FORMAT_5
);
1389 reg_key_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1390 reg_key_name_size
* sizeof(*reg_key_name_buf
));
1391 val_name_buf
= HeapAlloc(GetProcessHeap(), 0,
1392 val_name_size
* sizeof(*val_name_buf
));
1393 val_buf
= HeapAlloc(GetProcessHeap(), 0, val_size
);
1394 line_buf
= HeapAlloc(GetProcessHeap(), 0, line_buf_size
* sizeof(*line_buf
));
1395 CHECK_ENOUGH_MEMORY(reg_key_name_buf
&& val_name_buf
&& val_buf
&& line_buf
);
1397 if (reg_key_name
&& reg_key_name
[0])
1400 WCHAR
*branch_name
= NULL
;
1403 REGPROC_resize_char_buffer(®_key_name_buf
, ®_key_name_size
,
1404 lstrlenW(reg_key_name
));
1405 lstrcpyW(reg_key_name_buf
, reg_key_name
);
1407 /* open the specified key */
1408 if (!parseKeyName(reg_key_name
, ®_key_class
, &branch_name
))
1410 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1411 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1412 getAppName(), key_nameA
);
1413 HeapFree(GetProcessHeap(), 0, key_nameA
);
1416 if (!branch_name
[0])
1418 /* no branch - registry class is specified */
1419 file
= REGPROC_open_export_file(file_name
, unicode
);
1420 export_hkey(file
, reg_key_class
,
1421 ®_key_name_buf
, ®_key_name_size
,
1422 &val_name_buf
, &val_name_size
,
1423 &val_buf
, &val_size
, &line_buf
,
1424 &line_buf_size
, unicode
);
1426 else if (RegOpenKeyW(reg_key_class
, branch_name
, &key
) == ERROR_SUCCESS
)
1428 file
= REGPROC_open_export_file(file_name
, unicode
);
1429 export_hkey(file
, key
,
1430 ®_key_name_buf
, ®_key_name_size
,
1431 &val_name_buf
, &val_name_size
,
1432 &val_buf
, &val_size
, &line_buf
,
1433 &line_buf_size
, unicode
);
1438 CHAR
* key_nameA
= GetMultiByteString(reg_key_name
);
1439 fprintf(stderr
,"%s: Can't export. Registry key '%s' does not exist!\n",
1440 getAppName(), key_nameA
);
1441 HeapFree(GetProcessHeap(), 0, key_nameA
);
1442 REGPROC_print_error();
1449 /* export all registry classes */
1450 file
= REGPROC_open_export_file(file_name
, unicode
);
1451 for (i
= 0; i
< REG_CLASS_NUMBER
; i
++)
1453 /* do not export HKEY_CLASSES_ROOT */
1454 if (reg_class_keys
[i
] != HKEY_CLASSES_ROOT
&&
1455 reg_class_keys
[i
] != HKEY_CURRENT_USER
&&
1456 reg_class_keys
[i
] != HKEY_CURRENT_CONFIG
&&
1457 reg_class_keys
[i
] != HKEY_DYN_DATA
)
1459 lstrcpyW(reg_key_name_buf
, reg_class_namesW
[i
]);
1460 export_hkey(file
, reg_class_keys
[i
],
1461 ®_key_name_buf
, ®_key_name_size
,
1462 &val_name_buf
, &val_name_size
,
1463 &val_buf
, &val_size
, &line_buf
,
1464 &line_buf_size
, unicode
);
1473 HeapFree(GetProcessHeap(), 0, reg_key_name
);
1474 HeapFree(GetProcessHeap(), 0, val_name_buf
);
1475 HeapFree(GetProcessHeap(), 0, val_buf
);
1476 HeapFree(GetProcessHeap(), 0, line_buf
);
1480 /******************************************************************************
1481 * Reads contents of the specified file into the registry.
1483 BOOL
import_registry_file(FILE* reg_file
)
1488 if (fread( s
, 2, 1, reg_file
) == 1)
1490 if (s
[0] == 0xff && s
[1] == 0xfe)
1492 processRegLinesW(reg_file
);
1496 fseek(reg_file
, 0, SEEK_SET
);
1497 processRegLinesA(reg_file
);
1505 /******************************************************************************
1506 * Removes the registry key with all subkeys. Parses full key name.
1509 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1510 * empty, points to register key class, does not exist.
1512 void delete_registry_key(WCHAR
*reg_key_name
)
1514 WCHAR
*key_name
= NULL
;
1517 if (!reg_key_name
|| !reg_key_name
[0])
1520 if (!parseKeyName(reg_key_name
, &key_class
, &key_name
))
1522 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1523 fprintf(stderr
,"%s: Incorrect registry class specification in '%s'\n",
1524 getAppName(), reg_key_nameA
);
1525 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1530 char* reg_key_nameA
= GetMultiByteString(reg_key_name
);
1531 fprintf(stderr
,"%s: Can't delete registry class '%s'\n",
1532 getAppName(), reg_key_nameA
);
1533 HeapFree(GetProcessHeap(), 0, reg_key_nameA
);
1537 SHDeleteKey(key_class
, key_name
);