regedit: Simplify parseKeyName.
[wine.git] / programs / regedit / regproc.c
blob1672f224ca53265142fac25be7bea09dca6548ec
1 /*
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
24 #include <limits.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <fcntl.h>
28 #include <io.h>
29 #include <windows.h>
30 #include <winnt.h>
31 #include <winreg.h>
32 #include <assert.h>
33 #include <wine/unicode.h>
34 #include <wine/debug.h>
35 #include "regproc.h"
37 #define REG_VAL_BUF_SIZE 4096
39 /* maximal number of characters in hexadecimal data line,
40 * including the indentation, but not including the '\' character
42 #define REG_FILE_HEX_LINE_LEN (2 + 25 * 3)
44 extern const WCHAR* reg_class_namesW[];
46 static HKEY reg_class_keys[] = {
47 HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
48 HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
51 #define ARRAY_SIZE(A) (sizeof(A)/sizeof(*A))
53 /* return values */
54 #define NOT_ENOUGH_MEMORY 1
56 /* processing macros */
58 /* common check of memory allocation results */
59 #define CHECK_ENOUGH_MEMORY(p) \
60 if (!(p)) \
61 { \
62 output_message(STRING_OUT_OF_MEMORY, __FILE__, __LINE__); \
63 exit(NOT_ENOUGH_MEMORY); \
66 /******************************************************************************
67 * Allocates memory and converts input from multibyte to wide chars
68 * Returned string must be freed by the caller
70 static WCHAR* GetWideString(const char* strA)
72 if(strA)
74 WCHAR* strW;
75 int len = MultiByteToWideChar(CP_ACP, 0, strA, -1, NULL, 0);
77 strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
78 CHECK_ENOUGH_MEMORY(strW);
79 MultiByteToWideChar(CP_ACP, 0, strA, -1, strW, len);
80 return strW;
82 return NULL;
85 /******************************************************************************
86 * Allocates memory and converts input from multibyte to wide chars
87 * Returned string must be freed by the caller
89 static WCHAR* GetWideStringN(const char* strA, int chars, DWORD *len)
91 if(strA)
93 WCHAR* strW;
94 *len = MultiByteToWideChar(CP_ACP, 0, strA, chars, NULL, 0);
96 strW = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(WCHAR));
97 CHECK_ENOUGH_MEMORY(strW);
98 MultiByteToWideChar(CP_ACP, 0, strA, chars, strW, *len);
99 return strW;
101 *len = 0;
102 return NULL;
105 /******************************************************************************
106 * Allocates memory and converts input from wide chars to multibyte
107 * Returned string must be freed by the caller
109 char* GetMultiByteString(const WCHAR* strW)
111 if(strW)
113 char* strA;
114 int len = WideCharToMultiByte(CP_ACP, 0, strW, -1, NULL, 0, NULL, NULL);
116 strA = HeapAlloc(GetProcessHeap(), 0, len);
117 CHECK_ENOUGH_MEMORY(strA);
118 WideCharToMultiByte(CP_ACP, 0, strW, -1, strA, len, NULL, NULL);
119 return strA;
121 return NULL;
124 /******************************************************************************
125 * Allocates memory and converts input from wide chars to multibyte
126 * Returned string must be freed by the caller
128 static char* GetMultiByteStringN(const WCHAR* strW, int chars, DWORD* len)
130 if(strW)
132 char* strA;
133 *len = WideCharToMultiByte(CP_ACP, 0, strW, chars, NULL, 0, NULL, NULL);
135 strA = HeapAlloc(GetProcessHeap(), 0, *len);
136 CHECK_ENOUGH_MEMORY(strA);
137 WideCharToMultiByte(CP_ACP, 0, strW, chars, strA, *len, NULL, NULL);
138 return strA;
140 *len = 0;
141 return NULL;
144 /******************************************************************************
145 * Converts a hex representation of a DWORD into a DWORD.
147 static BOOL convertHexToDWord(WCHAR* str, DWORD *dw)
149 WCHAR *p, *end;
150 int count = 0;
152 while (*str == ' ' || *str == '\t') str++;
153 if (!*str) goto error;
155 p = str;
156 while (isxdigitW(*p))
158 count++;
159 p++;
161 if (count > 8) goto error;
163 end = p;
164 while (*p == ' ' || *p == '\t') p++;
165 if (*p && *p != ';') goto error;
167 *end = 0;
168 *dw = strtoulW(str, &end, 16);
169 return TRUE;
171 error:
172 output_message(STRING_INVALID_HEX);
173 return FALSE;
176 /******************************************************************************
177 * Converts a hex comma separated values list into a binary string.
179 static BYTE* convertHexCSVToHex(WCHAR *str, DWORD *size)
181 WCHAR *s;
182 BYTE *d, *data;
184 /* The worst case is 1 digit + 1 comma per byte */
185 *size=(lstrlenW(str)+1)/2;
186 data=HeapAlloc(GetProcessHeap(), 0, *size);
187 CHECK_ENOUGH_MEMORY(data);
189 s = str;
190 d = data;
191 *size=0;
192 while (*s != '\0') {
193 UINT wc;
194 WCHAR *end;
196 wc = strtoulW(s,&end,16);
197 if (end == s || wc > 0xff || (*end && *end != ',')) {
198 output_message(STRING_CSV_HEX_ERROR, s);
199 HeapFree(GetProcessHeap(), 0, data);
200 return NULL;
202 *d++ =(BYTE)wc;
203 (*size)++;
204 if (*end) end++;
205 s = end;
208 return data;
211 #define REG_UNKNOWN_TYPE 99
213 /******************************************************************************
214 * This function returns the HKEY associated with the data type encoded in the
215 * value. It modifies the input parameter (key value) in order to skip this
216 * "now useless" data type information.
218 * Note: Updated based on the algorithm used in 'server/registry.c'
220 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
222 struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
224 static const WCHAR quote[] = {'"'};
225 static const WCHAR hex[] = {'h','e','x',':'};
226 static const WCHAR dword[] = {'d','w','o','r','d',':'};
227 static const WCHAR hexp[] = {'h','e','x','('};
229 static const struct data_type data_types[] = {
230 /* tag len type parse type */
231 { quote, 1, REG_SZ, REG_SZ },
232 { hex, 4, REG_BINARY, REG_BINARY },
233 { dword, 6, REG_DWORD, REG_DWORD },
234 { hexp, 4, -1, REG_BINARY }, /* REG_NONE, REG_EXPAND_SZ, REG_MULTI_SZ */
235 { NULL, 0, 0, 0 }
238 const struct data_type *ptr;
239 int type;
241 for (ptr = data_types; ptr->tag; ptr++) {
242 if (strncmpW( ptr->tag, *lpValue, ptr->len ))
243 continue;
245 /* Found! */
246 *parse_type = ptr->parse_type;
247 type=ptr->type;
248 *lpValue+=ptr->len;
249 if (type == -1) {
250 WCHAR* end;
252 /* "hex(xx):" is special */
253 type = (int)strtoulW( *lpValue , &end, 16 );
254 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
255 type=REG_NONE;
256 } else {
257 *lpValue = end + 2;
260 return type;
262 *parse_type = REG_UNKNOWN_TYPE;
263 return REG_UNKNOWN_TYPE;
266 /******************************************************************************
267 * Replaces escape sequences with the characters.
269 static int REGPROC_unescape_string(WCHAR* str)
271 int str_idx = 0; /* current character under analysis */
272 int val_idx = 0; /* the last character of the unescaped string */
273 int len = lstrlenW(str);
274 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
275 if (str[str_idx] == '\\') {
276 str_idx++;
277 switch (str[str_idx]) {
278 case 'n':
279 str[val_idx] = '\n';
280 break;
281 case 'r':
282 str[val_idx] = '\r';
283 break;
284 case '0':
285 str[val_idx] = '\0';
286 break;
287 case '\\':
288 case '"':
289 str[val_idx] = str[str_idx];
290 break;
291 default:
292 output_message(STRING_ESCAPE_SEQUENCE, str[str_idx]);
293 str[val_idx] = str[str_idx];
294 break;
296 } else {
297 str[val_idx] = str[str_idx];
300 str[val_idx] = '\0';
301 return val_idx;
304 static HKEY parseKeyName(LPWSTR lpKeyName, LPWSTR *lpKeyPath)
306 unsigned int i;
308 if (lpKeyName == NULL)
309 return 0;
311 *lpKeyPath = strchrW(lpKeyName, '\\');
312 if (*lpKeyPath) (*lpKeyPath)++;
314 for (i = 0; i < ARRAY_SIZE(reg_class_keys); i++)
316 int len = lstrlenW(reg_class_namesW[i]);
317 if (!strncmpW(lpKeyName, reg_class_namesW[i], len) &&
318 (lpKeyName[len] == 0 || lpKeyName[len] == '\\'))
320 return reg_class_keys[i];
324 return 0;
327 /* Globals used by the setValue() & co */
328 static WCHAR *currentKeyName;
329 static HKEY currentKeyHandle = NULL;
331 /* Registry data types */
332 static const WCHAR type_none[] = {'R','E','G','_','N','O','N','E',0};
333 static const WCHAR type_sz[] = {'R','E','G','_','S','Z',0};
334 static const WCHAR type_expand_sz[] = {'R','E','G','_','E','X','P','A','N','D','_','S','Z',0};
335 static const WCHAR type_binary[] = {'R','E','G','_','B','I','N','A','R','Y',0};
336 static const WCHAR type_dword[] = {'R','E','G','_','D','W','O','R','D',0};
337 static const WCHAR type_dword_le[] = {'R','E','G','_','D','W','O','R','D','_','L','I','T','T','L','E','_','E','N','D','I','A','N',0};
338 static const WCHAR type_dword_be[] = {'R','E','G','_','D','W','O','R','D','_','B','I','G','_','E','N','D','I','A','N',0};
339 static const WCHAR type_multi_sz[] = {'R','E','G','_','M','U','L','T','I','_','S','Z',0};
341 static const struct
343 DWORD type;
344 const WCHAR *name;
346 type_rels[] =
348 {REG_NONE, type_none},
349 {REG_SZ, type_sz},
350 {REG_EXPAND_SZ, type_expand_sz},
351 {REG_BINARY, type_binary},
352 {REG_DWORD, type_dword},
353 {REG_DWORD_LITTLE_ENDIAN, type_dword_le},
354 {REG_DWORD_BIG_ENDIAN, type_dword_be},
355 {REG_MULTI_SZ, type_multi_sz},
358 static const WCHAR *reg_type_to_wchar(DWORD type)
360 int i, array_size = ARRAY_SIZE(type_rels);
362 for (i = 0; i < array_size; i++)
364 if (type == type_rels[i].type)
365 return type_rels[i].name;
367 return NULL;
370 /******************************************************************************
371 * Sets the value with name val_name to the data in val_data for the currently
372 * opened key.
374 * Parameters:
375 * val_name - name of the registry value
376 * val_data - registry value data
378 static LONG setValue(WCHAR* val_name, WCHAR* val_data, BOOL is_unicode)
380 LONG res;
381 DWORD dwDataType, dwParseType;
382 LPBYTE lpbData;
383 DWORD dwData, dwLen;
384 WCHAR del[] = {'-',0};
386 if ( (val_name == NULL) || (val_data == NULL) )
387 return ERROR_INVALID_PARAMETER;
389 if (lstrcmpW(val_data, del) == 0)
391 res=RegDeleteValueW(currentKeyHandle,val_name);
392 return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
395 /* Get the data type stored into the value field */
396 dwDataType = getDataType(&val_data, &dwParseType);
398 if (dwParseType == REG_SZ) /* no conversion for string */
400 dwLen = REGPROC_unescape_string(val_data);
401 if(!dwLen || val_data[dwLen-1] != '"')
402 return ERROR_INVALID_DATA;
403 val_data[dwLen-1] = '\0'; /* remove last quotes */
404 lpbData = (BYTE*) val_data;
405 dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
407 else if (dwParseType == REG_DWORD) /* Convert the dword types */
409 if (!convertHexToDWord(val_data, &dwData))
410 return ERROR_INVALID_DATA;
411 lpbData = (BYTE*)&dwData;
412 dwLen = sizeof(dwData);
414 else if (dwParseType == REG_BINARY) /* Convert the binary data */
416 lpbData = convertHexCSVToHex(val_data, &dwLen);
417 if (!lpbData)
418 return ERROR_INVALID_DATA;
420 if((dwDataType == REG_MULTI_SZ || dwDataType == REG_EXPAND_SZ) && !is_unicode)
422 LPBYTE tmp = lpbData;
423 lpbData = (LPBYTE)GetWideStringN((char*)lpbData, dwLen, &dwLen);
424 dwLen *= sizeof(WCHAR);
425 HeapFree(GetProcessHeap(), 0, tmp);
428 else /* unknown format */
430 if (dwDataType == REG_UNKNOWN_TYPE)
432 WCHAR buf[32];
433 LoadStringW(GetModuleHandleW(NULL), STRING_UNKNOWN_TYPE, buf, ARRAY_SIZE(buf));
434 output_message(STRING_UNKNOWN_DATA_FORMAT, buf);
436 else
437 output_message(STRING_UNKNOWN_DATA_FORMAT, reg_type_to_wchar(dwDataType));
439 return ERROR_INVALID_DATA;
442 res = RegSetValueExW(
443 currentKeyHandle,
444 val_name,
445 0, /* Reserved */
446 dwDataType,
447 lpbData,
448 dwLen);
449 if (dwParseType == REG_BINARY)
450 HeapFree(GetProcessHeap(), 0, lpbData);
451 return res;
454 /******************************************************************************
455 * A helper function for processRegEntry() that opens the current key.
456 * That key must be closed by calling closeKey().
458 static LONG openKeyW(WCHAR* stdInput)
460 HKEY keyClass;
461 WCHAR* keyPath;
462 DWORD dwDisp;
463 LONG res;
465 /* Sanity checks */
466 if (stdInput == NULL)
467 return ERROR_INVALID_PARAMETER;
469 /* Get the registry class */
470 if (!(keyClass = parseKeyName(stdInput, &keyPath)))
471 return ERROR_INVALID_PARAMETER;
473 res = RegCreateKeyExW(
474 keyClass, /* Class */
475 keyPath, /* Sub Key */
476 0, /* MUST BE 0 */
477 NULL, /* object type */
478 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
479 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
480 NULL, /* security attribute */
481 &currentKeyHandle, /* result */
482 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
483 REG_OPENED_EXISTING_KEY */
485 if (res == ERROR_SUCCESS)
487 currentKeyName = HeapAlloc(GetProcessHeap(), 0, (strlenW(stdInput) + 1) * sizeof(WCHAR));
488 CHECK_ENOUGH_MEMORY(currentKeyName);
489 strcpyW(currentKeyName, stdInput);
491 else
492 currentKeyHandle = NULL;
494 return res;
498 /******************************************************************************
499 * Close the currently opened key.
501 static void closeKey(void)
503 if (currentKeyHandle)
505 HeapFree(GetProcessHeap(), 0, currentKeyName);
506 RegCloseKey(currentKeyHandle);
507 currentKeyHandle = NULL;
511 /******************************************************************************
512 * This function is a wrapper for the setValue function. It prepares the
513 * land and cleans the area once completed.
514 * Note: this function modifies the line parameter.
516 * line - registry file unwrapped line. Should have the registry value name and
517 * complete registry value data.
519 static void processSetValue(WCHAR* line, BOOL is_unicode)
521 WCHAR* val_name; /* registry value name */
522 WCHAR* val_data; /* registry value data */
523 int line_idx = 0; /* current character under analysis */
524 LONG res;
526 /* get value name */
527 while ( isspaceW(line[line_idx]) ) line_idx++;
528 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
529 line[line_idx] = '\0';
530 val_name = line;
531 line_idx++;
532 } else if (line[line_idx] == '\"') {
533 line_idx++;
534 val_name = line + line_idx;
535 while (line[line_idx]) {
536 if (line[line_idx] == '\\') /* skip escaped character */
538 line_idx += 2;
539 } else {
540 if (line[line_idx] == '\"') {
541 line[line_idx] = '\0';
542 line_idx++;
543 break;
544 } else {
545 line_idx++;
549 while ( isspaceW(line[line_idx]) ) line_idx++;
550 if (!line[line_idx]) {
551 output_message(STRING_UNEXPECTED_EOL, line);
552 return;
554 if (line[line_idx] != '=') {
555 line[line_idx] = '\"';
556 output_message(STRING_UNRECOGNIZED_LINE, line);
557 return;
560 } else {
561 output_message(STRING_UNRECOGNIZED_LINE, line);
562 return;
564 line_idx++; /* skip the '=' character */
566 while ( isspaceW(line[line_idx]) ) line_idx++;
567 val_data = line + line_idx;
568 /* trim trailing blanks */
569 line_idx = strlenW(val_data);
570 while (line_idx > 0 && isspaceW(val_data[line_idx-1])) line_idx--;
571 val_data[line_idx] = '\0';
573 REGPROC_unescape_string(val_name);
574 res = setValue(val_name, val_data, is_unicode);
575 if ( res != ERROR_SUCCESS )
576 output_message(STRING_SETVALUE_FAILED, val_name, currentKeyName);
579 /******************************************************************************
580 * This function receives the currently read entry and performs the
581 * corresponding action.
582 * isUnicode affects parsing of REG_MULTI_SZ values
584 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
586 if ( stdInput[0] == '[') /* We are reading a new key */
588 WCHAR* keyEnd;
589 closeKey(); /* Close the previous key */
591 /* Get rid of the square brackets */
592 stdInput++;
593 keyEnd = strrchrW(stdInput, ']');
594 if (keyEnd)
595 *keyEnd='\0';
597 /* delete the key if we encounter '-' at the start of reg key */
598 if (stdInput[0] == '-')
599 delete_registry_key(stdInput + 1);
600 else if (openKeyW(stdInput) != ERROR_SUCCESS)
601 output_message(STRING_OPEN_KEY_FAILED, stdInput);
602 } else if( currentKeyHandle &&
603 (( stdInput[0] == '@') || /* reading a default @=data pair */
604 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
606 processSetValue(stdInput, isUnicode);
610 /* version for Windows 3.1 */
611 static void processRegEntry31(WCHAR *line)
613 int key_end = 0;
614 WCHAR *value;
615 int res;
617 static WCHAR empty[] = {0};
618 static WCHAR hkcr[] = {'H','K','E','Y','_','C','L','A','S','S','E','S','_','R','O','O','T'};
620 if (strncmpW(line, hkcr, sizeof(hkcr) / sizeof(WCHAR))) return;
622 /* get key name */
623 while (line[key_end] && !isspaceW(line[key_end])) key_end++;
625 value = line + key_end;
626 while (isspaceW(value[0])) value++;
628 if (value[0] == '=') value++;
629 if (value[0] == ' ') value++; /* at most one space is skipped */
631 line[key_end] = '\0';
632 if (openKeyW(line) != ERROR_SUCCESS)
633 output_message(STRING_OPEN_KEY_FAILED, line);
635 res = RegSetValueExW(
636 currentKeyHandle,
637 empty,
638 0, /* Reserved */
639 REG_SZ,
640 (BYTE *)value,
641 (strlenW(value) + 1) * sizeof(WCHAR));
642 if (res != ERROR_SUCCESS)
643 output_message(STRING_SETVALUE_FAILED, empty, currentKeyName);
645 closeKey();
648 enum reg_versions {
649 REG_VERSION_31,
650 REG_VERSION_40,
651 REG_VERSION_50,
652 REG_VERSION_FUZZY,
653 REG_VERSION_INVALID
656 static enum reg_versions parse_file_header(WCHAR *s)
658 static const WCHAR header_31[] = {'R','E','G','E','D','I','T',0};
659 static const WCHAR header_40[] = {'R','E','G','E','D','I','T','4',0};
660 static const WCHAR header_50[] = {'W','i','n','d','o','w','s',' ',
661 'R','e','g','i','s','t','r','y',' ','E','d','i','t','o','r',' ',
662 'V','e','r','s','i','o','n',' ','5','.','0','0',0};
664 while (*s && (*s == ' ' || *s == '\t')) s++;
666 if (!strcmpW(s, header_31))
667 return REG_VERSION_31;
669 if (!strcmpW(s, header_40))
670 return REG_VERSION_40;
672 if (!strcmpW(s, header_50))
673 return REG_VERSION_50;
675 /* The Windows version accepts registry file headers beginning with "REGEDIT" and ending
676 * with other characters, as long as "REGEDIT" appears at the start of the line. For example,
677 * "REGEDIT 4", "REGEDIT9" and "REGEDIT4FOO" are all treated as valid file headers.
678 * In all such cases, however, the contents of the registry file are not imported.
680 if (!strncmpW(s, header_31, 7)) /* "REGEDIT" without NUL */
681 return REG_VERSION_FUZZY;
683 return REG_VERSION_INVALID;
686 static char *get_lineA(FILE *fp)
688 static size_t size;
689 static char *buf, *next;
690 char *line;
692 if (!fp)
694 if (size) HeapFree(GetProcessHeap(), 0, buf);
695 size = 0;
696 return NULL;
699 if (!size)
701 size = REG_VAL_BUF_SIZE;
702 buf = HeapAlloc(GetProcessHeap(), 0, size);
703 CHECK_ENOUGH_MEMORY(buf);
704 *buf = 0;
705 next = buf;
707 line = next;
709 while (next)
711 char *p = strpbrk(line, "\r\n");
712 if (!p)
714 size_t len, count;
715 len = strlen(next);
716 memmove(buf, next, len + 1);
717 if (size - len < 3)
719 char *new_buf = HeapReAlloc(GetProcessHeap(), 0, buf, size * 2);
720 CHECK_ENOUGH_MEMORY(new_buf);
721 buf = new_buf;
722 size *= 2;
724 if (!(count = fread(buf + len, 1, size - len - 1, fp)))
726 next = NULL;
727 return buf;
729 buf[len + count] = 0;
730 next = buf;
731 line = buf;
732 continue;
734 next = p + 1;
735 if (*p == '\r' && *(p + 1) == '\n') next++;
736 *p = 0;
737 if (p > buf && *(p - 1) == '\\')
739 while (*next == ' ' || *next == '\t') next++;
740 memmove(p - 1, next, strlen(next) + 1);
741 next = line;
742 continue;
744 while (*line == ' ' || *line == '\t') line++;
745 if (*line == ';' || *line == '#')
747 line = next;
748 continue;
750 return line;
752 HeapFree(GetProcessHeap(), 0, buf);
753 size = 0;
754 return NULL;
757 static BOOL processRegLinesA(FILE *fp, char *two_chars)
759 char *line, *header;
760 WCHAR *lineW;
761 int reg_version;
763 line = get_lineA(fp);
765 header = HeapAlloc(GetProcessHeap(), 0, strlen(line) + 3);
766 CHECK_ENOUGH_MEMORY(header);
767 strcpy(header, two_chars);
768 strcpy(header + 2, line);
770 lineW = GetWideString(header);
771 HeapFree(GetProcessHeap(), 0, header);
773 reg_version = parse_file_header(lineW);
774 HeapFree(GetProcessHeap(), 0, lineW);
775 if (reg_version == REG_VERSION_FUZZY || reg_version == REG_VERSION_INVALID)
777 get_lineA(NULL); /* Reset static variables */
778 return reg_version == REG_VERSION_FUZZY;
781 while ((line = get_lineA(fp)))
783 lineW = GetWideString(line);
785 if (reg_version == REG_VERSION_31)
786 processRegEntry31(lineW);
787 else
788 processRegEntry(lineW, FALSE);
790 HeapFree(GetProcessHeap(), 0, lineW);
793 closeKey();
794 return TRUE;
797 static WCHAR *get_lineW(FILE *fp)
799 static size_t size;
800 static WCHAR *buf, *next;
801 WCHAR *line;
803 if (!fp)
805 if (size) HeapFree(GetProcessHeap(), 0, buf);
806 size = 0;
807 return NULL;
810 if (!size)
812 size = REG_VAL_BUF_SIZE;
813 buf = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
814 CHECK_ENOUGH_MEMORY(buf);
815 *buf = 0;
816 next = buf;
818 line = next;
820 while (next)
822 static const WCHAR line_endings[] = {'\r','\n',0};
823 WCHAR *p = strpbrkW(line, line_endings);
824 if (!p)
826 size_t len, count;
827 len = strlenW(next);
828 memmove(buf, next, (len + 1) * sizeof(WCHAR));
829 if (size - len < 3)
831 WCHAR *new_buf = HeapReAlloc(GetProcessHeap(), 0, buf, (size * 2) * sizeof(WCHAR));
832 CHECK_ENOUGH_MEMORY(new_buf);
833 buf = new_buf;
834 size *= 2;
836 if (!(count = fread(buf + len, sizeof(WCHAR), size - len - 1, fp)))
838 next = NULL;
839 return buf;
841 buf[len + count] = 0;
842 next = buf;
843 line = buf;
844 continue;
846 next = p + 1;
847 if (*p == '\r' && *(p + 1) == '\n') next++;
848 *p = 0;
849 if (p > buf && *(p - 1) == '\\')
851 while (*next == ' ' || *next == '\t') next++;
852 memmove(p - 1, next, (strlenW(next) + 1) * sizeof(WCHAR));
853 next = line;
854 continue;
856 while (*line == ' ' || *line == '\t') line++;
857 if (*line == ';' || *line == '#')
859 line = next;
860 continue;
862 return line;
864 HeapFree( GetProcessHeap(), 0, buf );
865 size = 0;
866 return NULL;
869 static BOOL processRegLinesW(FILE *fp)
871 WCHAR *line;
872 int reg_version;
874 line = get_lineW(fp);
875 reg_version = parse_file_header(line);
876 if (reg_version == REG_VERSION_FUZZY || reg_version == REG_VERSION_INVALID)
878 get_lineW(NULL); /* Reset static variables */
879 return reg_version == REG_VERSION_FUZZY;
882 while ((line = get_lineW(fp)))
883 processRegEntry(line, TRUE);
885 closeKey();
886 return TRUE;
889 /******************************************************************************
890 * Checks whether the buffer has enough room for the string or required size.
891 * Resizes the buffer if necessary.
893 * Parameters:
894 * buffer - pointer to a buffer for string
895 * len - current length of the buffer in characters.
896 * required_len - length of the string to place to the buffer in characters.
897 * The length does not include the terminating null character.
899 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
901 required_len++;
902 if (required_len > *len) {
903 *len = required_len;
904 if (!*buffer)
905 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
906 else
907 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
908 CHECK_ENOUGH_MEMORY(*buffer);
912 /******************************************************************************
913 * Same as REGPROC_resize_char_buffer() but on a regular buffer.
915 * Parameters:
916 * buffer - pointer to a buffer
917 * len - current size of the buffer in bytes
918 * required_size - size of the data to place in the buffer in bytes
920 static void REGPROC_resize_binary_buffer(BYTE **buffer, DWORD *size, DWORD required_size)
922 if (required_size > *size) {
923 *size = required_size;
924 if (!*buffer)
925 *buffer = HeapAlloc(GetProcessHeap(), 0, *size);
926 else
927 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *size);
928 CHECK_ENOUGH_MEMORY(*buffer);
932 /******************************************************************************
933 * Prints string str to file
935 static void REGPROC_export_string(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, WCHAR *str, DWORD str_len)
937 DWORD i, pos;
938 DWORD extra = 0;
940 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + 10);
942 /* escaping characters */
943 pos = *line_len;
944 for (i = 0; i < str_len; i++) {
945 WCHAR c = str[i];
946 switch (c) {
947 case '\n':
948 extra++;
949 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
950 (*line_buf)[pos++] = '\\';
951 (*line_buf)[pos++] = 'n';
952 break;
954 case '\r':
955 extra++;
956 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
957 (*line_buf)[pos++] = '\\';
958 (*line_buf)[pos++] = 'r';
959 break;
961 case '\\':
962 case '"':
963 extra++;
964 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
965 (*line_buf)[pos++] = '\\';
966 /* Fall through */
968 default:
969 (*line_buf)[pos++] = c;
970 break;
973 (*line_buf)[pos] = '\0';
974 *line_len = pos;
977 static void REGPROC_export_binary(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, DWORD type, BYTE *value, DWORD value_size, BOOL unicode)
979 DWORD hex_pos, data_pos;
980 const WCHAR *hex_prefix;
981 const WCHAR hex[] = {'h','e','x',':',0};
982 WCHAR hex_buf[17];
983 const WCHAR concat[] = {'\\','\r','\n',' ',' ',0};
984 DWORD concat_prefix, concat_len;
985 const WCHAR newline[] = {'\r','\n',0};
986 CHAR* value_multibyte = NULL;
988 if (type == REG_BINARY) {
989 hex_prefix = hex;
990 } else {
991 const WCHAR hex_format[] = {'h','e','x','(','%','x',')',':',0};
992 hex_prefix = hex_buf;
993 sprintfW(hex_buf, hex_format, type);
994 if ((type == REG_SZ || type == REG_EXPAND_SZ || type == REG_MULTI_SZ) && !unicode)
996 value_multibyte = GetMultiByteStringN((WCHAR*)value, value_size / sizeof(WCHAR), &value_size);
997 value = (BYTE*)value_multibyte;
1001 concat_len = lstrlenW(concat);
1002 concat_prefix = 2;
1004 hex_pos = *line_len;
1005 *line_len += lstrlenW(hex_prefix);
1006 data_pos = *line_len;
1007 *line_len += value_size * 3;
1008 /* - The 2 spaces that concat places at the start of the
1009 * line effectively reduce the space available for data.
1010 * - If the value name and hex prefix are very long
1011 * ( > REG_FILE_HEX_LINE_LEN) or *line_len divides
1012 * without a remainder then we may overestimate
1013 * the needed number of lines by one. But that's ok.
1014 * - The trailing '\r' takes the place of a comma so
1015 * we only need to add 1 for the trailing '\n'
1017 *line_len += *line_len / (REG_FILE_HEX_LINE_LEN - concat_prefix) * concat_len + 1;
1018 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len);
1019 lstrcpyW(*line_buf + hex_pos, hex_prefix);
1020 if (value_size)
1022 const WCHAR format[] = {'%','0','2','x',0};
1023 DWORD i, column;
1025 column = data_pos; /* no line wrap yet */
1026 i = 0;
1027 while (1)
1029 sprintfW(*line_buf + data_pos, format, (unsigned int)value[i]);
1030 data_pos += 2;
1031 if (++i == value_size)
1032 break;
1034 (*line_buf)[data_pos++] = ',';
1035 column += 3;
1037 /* wrap the line */
1038 if (column >= REG_FILE_HEX_LINE_LEN) {
1039 lstrcpyW(*line_buf + data_pos, concat);
1040 data_pos += concat_len;
1041 column = concat_prefix;
1045 lstrcpyW(*line_buf + data_pos, newline);
1046 HeapFree(GetProcessHeap(), 0, value_multibyte);
1049 /******************************************************************************
1050 * Writes the given line to a file, in multi-byte or wide characters
1052 static void REGPROC_write_line(FILE *file, const WCHAR* str, BOOL unicode)
1054 if(unicode)
1056 fwrite(str, sizeof(WCHAR), lstrlenW(str), file);
1057 } else
1059 char* strA = GetMultiByteString(str);
1060 fputs(strA, file);
1061 HeapFree(GetProcessHeap(), 0, strA);
1065 /******************************************************************************
1066 * Writes contents of the registry key to the specified file stream.
1068 * Parameters:
1069 * file - writable file stream to export registry branch to.
1070 * key - registry branch to export.
1071 * reg_key_name_buf - name of the key with registry class.
1072 * Is resized if necessary.
1073 * reg_key_name_size - length of the buffer for the registry class in characters.
1074 * val_name_buf - buffer for storing value name.
1075 * Is resized if necessary.
1076 * val_name_size - length of the buffer for storing value names in characters.
1077 * val_buf - buffer for storing values while extracting.
1078 * Is resized if necessary.
1079 * val_size - size of the buffer for storing values in bytes.
1081 static void export_hkey(FILE *file, HKEY key,
1082 WCHAR **reg_key_name_buf, DWORD *reg_key_name_size,
1083 WCHAR **val_name_buf, DWORD *val_name_size,
1084 BYTE **val_buf, DWORD *val_size,
1085 WCHAR **line_buf, DWORD *line_buf_size,
1086 BOOL unicode)
1088 DWORD max_sub_key_len;
1089 DWORD max_val_name_len;
1090 DWORD max_val_size;
1091 DWORD curr_len;
1092 DWORD i;
1093 LONG ret;
1094 WCHAR key_format[] = {'\r','\n','[','%','s',']','\r','\n',0};
1096 /* get size information and resize the buffers if necessary */
1097 if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
1098 &max_sub_key_len, NULL,
1099 NULL, &max_val_name_len, &max_val_size, NULL, NULL
1100 ) != ERROR_SUCCESS)
1101 return;
1102 curr_len = strlenW(*reg_key_name_buf);
1103 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size,
1104 max_sub_key_len + curr_len + 1);
1105 REGPROC_resize_char_buffer(val_name_buf, val_name_size,
1106 max_val_name_len);
1107 REGPROC_resize_binary_buffer(val_buf, val_size, max_val_size);
1108 REGPROC_resize_char_buffer(line_buf, line_buf_size, lstrlenW(*reg_key_name_buf) + 4);
1109 /* output data for the current key */
1110 sprintfW(*line_buf, key_format, *reg_key_name_buf);
1111 REGPROC_write_line(file, *line_buf, unicode);
1113 /* print all the values */
1114 i = 0;
1115 for (;;) {
1116 DWORD value_type;
1117 DWORD val_name_size1 = *val_name_size;
1118 DWORD val_size1 = *val_size;
1119 ret = RegEnumValueW(key, i, *val_name_buf, &val_name_size1, NULL,
1120 &value_type, *val_buf, &val_size1);
1121 if (ret == ERROR_MORE_DATA) {
1122 /* Increase the size of the buffers and retry */
1123 REGPROC_resize_char_buffer(val_name_buf, val_name_size, val_name_size1);
1124 REGPROC_resize_binary_buffer(val_buf, val_size, val_size1);
1125 } else if (ret == ERROR_SUCCESS) {
1126 DWORD line_len;
1127 i++;
1129 if ((*val_name_buf)[0]) {
1130 const WCHAR val_start[] = {'"','%','s','"','=',0};
1132 line_len = 0;
1133 REGPROC_export_string(line_buf, line_buf_size, &line_len, *val_name_buf, lstrlenW(*val_name_buf));
1134 REGPROC_resize_char_buffer(val_name_buf, val_name_size, lstrlenW(*line_buf) + 1);
1135 lstrcpyW(*val_name_buf, *line_buf);
1137 line_len = 3 + lstrlenW(*val_name_buf);
1138 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1139 sprintfW(*line_buf, val_start, *val_name_buf);
1140 } else {
1141 const WCHAR std_val[] = {'@','=',0};
1142 line_len = 2;
1143 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1144 lstrcpyW(*line_buf, std_val);
1147 switch (value_type) {
1148 case REG_SZ:
1150 WCHAR* wstr = (WCHAR*)*val_buf;
1152 if (val_size1 < sizeof(WCHAR) || val_size1 % sizeof(WCHAR) ||
1153 wstr[val_size1 / sizeof(WCHAR) - 1]) {
1154 REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1155 } else {
1156 const WCHAR start[] = {'"',0};
1157 const WCHAR end[] = {'"','\r','\n',0};
1158 DWORD len;
1160 len = lstrlenW(start);
1161 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + len);
1162 lstrcpyW(*line_buf + line_len, start);
1163 line_len += len;
1165 REGPROC_export_string(line_buf, line_buf_size, &line_len, wstr, lstrlenW(wstr));
1167 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + lstrlenW(end));
1168 lstrcpyW(*line_buf + line_len, end);
1170 break;
1173 case REG_DWORD:
1175 WCHAR format[] = {'d','w','o','r','d',':','%','0','8','x','\r','\n',0};
1177 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + 15);
1178 sprintfW(*line_buf + line_len, format, *((DWORD *)*val_buf));
1179 break;
1182 default:
1184 output_message(STRING_UNSUPPORTED_TYPE, reg_type_to_wchar(value_type), *reg_key_name_buf);
1185 output_message(STRING_EXPORT_AS_BINARY, *val_name_buf);
1187 /* falls through */
1188 case REG_EXPAND_SZ:
1189 case REG_MULTI_SZ:
1190 /* falls through */
1191 case REG_BINARY:
1192 REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1194 REGPROC_write_line(file, *line_buf, unicode);
1196 else break;
1199 i = 0;
1200 (*reg_key_name_buf)[curr_len] = '\\';
1201 for (;;) {
1202 DWORD buf_size = *reg_key_name_size - curr_len - 1;
1204 ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_size,
1205 NULL, NULL, NULL, NULL);
1206 if (ret == ERROR_MORE_DATA) {
1207 /* Increase the size of the buffer and retry */
1208 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size, curr_len + 1 + buf_size);
1209 } else if (ret == ERROR_SUCCESS) {
1210 HKEY subkey;
1212 i++;
1213 if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1214 &subkey) == ERROR_SUCCESS) {
1215 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_size,
1216 val_name_buf, val_name_size, val_buf, val_size,
1217 line_buf, line_buf_size, unicode);
1218 RegCloseKey(subkey);
1220 else break;
1222 else break;
1224 (*reg_key_name_buf)[curr_len] = '\0';
1227 /******************************************************************************
1228 * Open file in binary mode for export.
1230 static FILE *REGPROC_open_export_file(WCHAR *file_name, BOOL unicode)
1232 FILE *file;
1233 WCHAR dash = '-';
1235 if (strncmpW(file_name,&dash,1)==0) {
1236 file=stdout;
1237 _setmode(_fileno(file), _O_BINARY);
1238 } else
1240 WCHAR wb_mode[] = {'w','b',0};
1241 WCHAR regedit[] = {'r','e','g','e','d','i','t',0};
1243 file = _wfopen(file_name, wb_mode);
1244 if (!file) {
1245 _wperror(regedit);
1246 output_message(STRING_CANNOT_OPEN_FILE, file_name);
1247 exit(1);
1250 if(unicode)
1252 const BYTE unicode_seq[] = {0xff,0xfe};
1253 const WCHAR header[] = {'W','i','n','d','o','w','s',' ','R','e','g','i','s','t','r','y',' ','E','d','i','t','o','r',' ','V','e','r','s','i','o','n',' ','5','.','0','0','\r','\n'};
1254 fwrite(unicode_seq, sizeof(BYTE), sizeof(unicode_seq)/sizeof(unicode_seq[0]), file);
1255 fwrite(header, sizeof(WCHAR), sizeof(header)/sizeof(header[0]), file);
1256 } else
1258 fputs("REGEDIT4\r\n", file);
1261 return file;
1264 /******************************************************************************
1265 * Writes contents of the registry key to the specified file stream.
1267 * Parameters:
1268 * file_name - name of a file to export registry branch to.
1269 * reg_key_name - registry branch to export. The whole registry is exported if
1270 * reg_key_name is NULL or contains an empty string.
1272 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name, DWORD format)
1274 WCHAR *reg_key_name_buf;
1275 WCHAR *val_name_buf;
1276 BYTE *val_buf;
1277 WCHAR *line_buf;
1278 DWORD reg_key_name_size = KEY_MAX_LEN;
1279 DWORD val_name_size = KEY_MAX_LEN;
1280 DWORD val_size = REG_VAL_BUF_SIZE;
1281 DWORD line_buf_size = KEY_MAX_LEN + REG_VAL_BUF_SIZE;
1282 FILE *file = NULL;
1283 BOOL unicode = (format == REG_FORMAT_5);
1285 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1286 reg_key_name_size * sizeof(*reg_key_name_buf));
1287 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1288 val_name_size * sizeof(*val_name_buf));
1289 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1290 line_buf = HeapAlloc(GetProcessHeap(), 0, line_buf_size * sizeof(*line_buf));
1291 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf && line_buf);
1293 if (reg_key_name && reg_key_name[0]) {
1294 HKEY reg_key_class;
1295 WCHAR *branch_name = NULL;
1296 HKEY key;
1298 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_size,
1299 lstrlenW(reg_key_name));
1300 lstrcpyW(reg_key_name_buf, reg_key_name);
1302 /* open the specified key */
1303 if (!(reg_key_class = parseKeyName(reg_key_name, &branch_name))) {
1304 output_message(STRING_INCORRECT_REG_CLASS, reg_key_name);
1305 exit(1);
1307 if (!branch_name[0]) {
1308 /* no branch - registry class is specified */
1309 file = REGPROC_open_export_file(file_name, unicode);
1310 export_hkey(file, reg_key_class,
1311 &reg_key_name_buf, &reg_key_name_size,
1312 &val_name_buf, &val_name_size,
1313 &val_buf, &val_size, &line_buf,
1314 &line_buf_size, unicode);
1315 } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1316 file = REGPROC_open_export_file(file_name, unicode);
1317 export_hkey(file, key,
1318 &reg_key_name_buf, &reg_key_name_size,
1319 &val_name_buf, &val_name_size,
1320 &val_buf, &val_size, &line_buf,
1321 &line_buf_size, unicode);
1322 RegCloseKey(key);
1323 } else {
1324 output_message(STRING_REG_KEY_NOT_FOUND, reg_key_name);
1326 } else {
1327 unsigned int i;
1329 /* export all registry classes */
1330 file = REGPROC_open_export_file(file_name, unicode);
1331 for (i = 0; i < ARRAY_SIZE(reg_class_keys); i++) {
1332 /* do not export HKEY_CLASSES_ROOT */
1333 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1334 reg_class_keys[i] != HKEY_CURRENT_USER &&
1335 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1336 reg_class_keys[i] != HKEY_DYN_DATA) {
1337 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1338 export_hkey(file, reg_class_keys[i],
1339 &reg_key_name_buf, &reg_key_name_size,
1340 &val_name_buf, &val_name_size,
1341 &val_buf, &val_size, &line_buf,
1342 &line_buf_size, unicode);
1347 if (file) {
1348 fclose(file);
1350 HeapFree(GetProcessHeap(), 0, reg_key_name);
1351 HeapFree(GetProcessHeap(), 0, val_name_buf);
1352 HeapFree(GetProcessHeap(), 0, val_buf);
1353 HeapFree(GetProcessHeap(), 0, line_buf);
1354 return TRUE;
1357 /******************************************************************************
1358 * Reads contents of the specified file into the registry.
1360 BOOL import_registry_file(FILE* reg_file)
1362 BYTE s[2];
1364 if (!reg_file || (fread(s, 2, 1, reg_file) != 1))
1365 return FALSE;
1367 if (s[0] == 0xff && s[1] == 0xfe)
1368 return processRegLinesW(reg_file);
1369 else
1370 return processRegLinesA(reg_file, (char *)s);
1373 /******************************************************************************
1374 * Removes the registry key with all subkeys. Parses full key name.
1376 * Parameters:
1377 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1378 * empty, points to register key class, does not exist.
1380 void delete_registry_key(WCHAR *reg_key_name)
1382 WCHAR *key_name = NULL;
1383 HKEY key_class;
1385 if (!reg_key_name || !reg_key_name[0])
1386 return;
1388 if (!(key_class = parseKeyName(reg_key_name, &key_name))) {
1389 output_message(STRING_INCORRECT_REG_CLASS, reg_key_name);
1390 exit(1);
1392 if (!*key_name) {
1393 output_message(STRING_DELETE_REG_CLASS_FAILED, reg_key_name);
1394 exit(1);
1397 RegDeleteTreeW(key_class, key_name);