regedit: Close the registry key handle in the read function instead of the parser.
[wine.git] / programs / regedit / regproc.c
blob5e4c2d28c439d683e06e762e937e180fce447391
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
55 #define IO_ERROR 2
57 /* processing macros */
59 /* common check of memory allocation results */
60 #define CHECK_ENOUGH_MEMORY(p) \
61 if (!(p)) \
62 { \
63 output_message(STRING_OUT_OF_MEMORY, __FILE__, __LINE__); \
64 exit(NOT_ENOUGH_MEMORY); \
67 /******************************************************************************
68 * Allocates memory and converts input from multibyte to wide chars
69 * Returned string must be freed by the caller
71 static WCHAR* GetWideString(const char* strA)
73 if(strA)
75 WCHAR* strW;
76 int len = MultiByteToWideChar(CP_ACP, 0, strA, -1, NULL, 0);
78 strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
79 CHECK_ENOUGH_MEMORY(strW);
80 MultiByteToWideChar(CP_ACP, 0, strA, -1, strW, len);
81 return strW;
83 return NULL;
86 /******************************************************************************
87 * Allocates memory and converts input from multibyte to wide chars
88 * Returned string must be freed by the caller
90 static WCHAR* GetWideStringN(const char* strA, int chars, DWORD *len)
92 if(strA)
94 WCHAR* strW;
95 *len = MultiByteToWideChar(CP_ACP, 0, strA, chars, NULL, 0);
97 strW = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(WCHAR));
98 CHECK_ENOUGH_MEMORY(strW);
99 MultiByteToWideChar(CP_ACP, 0, strA, chars, strW, *len);
100 return strW;
102 *len = 0;
103 return NULL;
106 /******************************************************************************
107 * Allocates memory and converts input from wide chars to multibyte
108 * Returned string must be freed by the caller
110 char* GetMultiByteString(const WCHAR* strW)
112 if(strW)
114 char* strA;
115 int len = WideCharToMultiByte(CP_ACP, 0, strW, -1, NULL, 0, NULL, NULL);
117 strA = HeapAlloc(GetProcessHeap(), 0, len);
118 CHECK_ENOUGH_MEMORY(strA);
119 WideCharToMultiByte(CP_ACP, 0, strW, -1, strA, len, NULL, NULL);
120 return strA;
122 return NULL;
125 /******************************************************************************
126 * Allocates memory and converts input from wide chars to multibyte
127 * Returned string must be freed by the caller
129 static char* GetMultiByteStringN(const WCHAR* strW, int chars, DWORD* len)
131 if(strW)
133 char* strA;
134 *len = WideCharToMultiByte(CP_ACP, 0, strW, chars, NULL, 0, NULL, NULL);
136 strA = HeapAlloc(GetProcessHeap(), 0, *len);
137 CHECK_ENOUGH_MEMORY(strA);
138 WideCharToMultiByte(CP_ACP, 0, strW, chars, strA, *len, NULL, NULL);
139 return strA;
141 *len = 0;
142 return NULL;
145 /******************************************************************************
146 * Converts a hex representation of a DWORD into a DWORD.
148 static BOOL convertHexToDWord(WCHAR* str, DWORD *dw)
150 char buf[9];
151 char dummy;
153 WideCharToMultiByte(CP_ACP, 0, str, -1, buf, 9, NULL, NULL);
154 if (lstrlenW(str) > 8 || sscanf(buf, "%x%c", dw, &dummy) != 1) {
155 output_message(STRING_INVALID_HEX);
156 return FALSE;
158 return TRUE;
161 /******************************************************************************
162 * Converts a hex comma separated values list into a binary string.
164 static BYTE* convertHexCSVToHex(WCHAR *str, DWORD *size)
166 WCHAR *s;
167 BYTE *d, *data;
169 /* The worst case is 1 digit + 1 comma per byte */
170 *size=(lstrlenW(str)+1)/2;
171 data=HeapAlloc(GetProcessHeap(), 0, *size);
172 CHECK_ENOUGH_MEMORY(data);
174 s = str;
175 d = data;
176 *size=0;
177 while (*s != '\0') {
178 UINT wc;
179 WCHAR *end;
181 wc = strtoulW(s,&end,16);
182 if (end == s || wc > 0xff || (*end && *end != ',')) {
183 output_message(STRING_CSV_HEX_ERROR, s);
184 HeapFree(GetProcessHeap(), 0, data);
185 return NULL;
187 *d++ =(BYTE)wc;
188 (*size)++;
189 if (*end) end++;
190 s = end;
193 return data;
196 /******************************************************************************
197 * This function returns the HKEY associated with the data type encoded in the
198 * value. It modifies the input parameter (key value) in order to skip this
199 * "now useless" data type information.
201 * Note: Updated based on the algorithm used in 'server/registry.c'
203 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
205 struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
207 static const WCHAR quote[] = {'"'};
208 static const WCHAR str[] = {'s','t','r',':','"'};
209 static const WCHAR str2[] = {'s','t','r','(','2',')',':','"'};
210 static const WCHAR hex[] = {'h','e','x',':'};
211 static const WCHAR dword[] = {'d','w','o','r','d',':'};
212 static const WCHAR hexp[] = {'h','e','x','('};
214 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
215 { quote, 1, REG_SZ, REG_SZ },
216 { str, 5, REG_SZ, REG_SZ },
217 { str2, 8, REG_EXPAND_SZ, REG_SZ },
218 { hex, 4, REG_BINARY, REG_BINARY },
219 { dword, 6, REG_DWORD, REG_DWORD },
220 { hexp, 4, -1, REG_BINARY },
221 { NULL, 0, 0, 0 }
224 const struct data_type *ptr;
225 int type;
227 for (ptr = data_types; ptr->tag; ptr++) {
228 if (strncmpW( ptr->tag, *lpValue, ptr->len ))
229 continue;
231 /* Found! */
232 *parse_type = ptr->parse_type;
233 type=ptr->type;
234 *lpValue+=ptr->len;
235 if (type == -1) {
236 WCHAR* end;
238 /* "hex(xx):" is special */
239 type = (int)strtoulW( *lpValue , &end, 16 );
240 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
241 type=REG_NONE;
242 } else {
243 *lpValue = end + 2;
246 return type;
248 *parse_type=REG_NONE;
249 return REG_NONE;
252 /******************************************************************************
253 * Replaces escape sequences with the characters.
255 static int REGPROC_unescape_string(WCHAR* str)
257 int str_idx = 0; /* current character under analysis */
258 int val_idx = 0; /* the last character of the unescaped string */
259 int len = lstrlenW(str);
260 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
261 if (str[str_idx] == '\\') {
262 str_idx++;
263 switch (str[str_idx]) {
264 case 'n':
265 str[val_idx] = '\n';
266 break;
267 case 'r':
268 str[val_idx] = '\r';
269 break;
270 case '0':
271 str[val_idx] = '\0';
272 break;
273 case '\\':
274 case '"':
275 str[val_idx] = str[str_idx];
276 break;
277 default:
278 output_message(STRING_ESCAPE_SEQUENCE, str[str_idx]);
279 str[val_idx] = str[str_idx];
280 break;
282 } else {
283 str[val_idx] = str[str_idx];
286 str[val_idx] = '\0';
287 return val_idx;
290 static BOOL parseKeyName(LPWSTR lpKeyName, HKEY *hKey, LPWSTR *lpKeyPath)
292 WCHAR* lpSlash = NULL;
293 unsigned int i, len;
295 if (lpKeyName == NULL)
296 return FALSE;
298 for(i = 0; *(lpKeyName+i) != 0; i++)
300 if(*(lpKeyName+i) == '\\')
302 lpSlash = lpKeyName+i;
303 break;
307 if (lpSlash)
309 len = lpSlash-lpKeyName;
311 else
313 len = lstrlenW(lpKeyName);
314 lpSlash = lpKeyName+len;
316 *hKey = NULL;
318 for (i = 0; i < ARRAY_SIZE(reg_class_keys); i++) {
319 if (CompareStringW(LOCALE_USER_DEFAULT, 0, lpKeyName, len, reg_class_namesW[i], -1) == CSTR_EQUAL &&
320 len == lstrlenW(reg_class_namesW[i])) {
321 *hKey = reg_class_keys[i];
322 break;
326 if (*hKey == NULL)
327 return FALSE;
330 if (*lpSlash != '\0')
331 lpSlash++;
332 *lpKeyPath = lpSlash;
333 return TRUE;
336 /* Globals used by the setValue() & co */
337 static WCHAR *currentKeyName;
338 static HKEY currentKeyHandle = NULL;
340 /* Registry data types */
341 static const WCHAR type_none[] = {'R','E','G','_','N','O','N','E',0};
342 static const WCHAR type_sz[] = {'R','E','G','_','S','Z',0};
343 static const WCHAR type_expand_sz[] = {'R','E','G','_','E','X','P','A','N','D','_','S','Z',0};
344 static const WCHAR type_binary[] = {'R','E','G','_','B','I','N','A','R','Y',0};
345 static const WCHAR type_dword[] = {'R','E','G','_','D','W','O','R','D',0};
346 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};
347 static const WCHAR type_dword_be[] = {'R','E','G','_','D','W','O','R','D','_','B','I','G','_','E','N','D','I','A','N',0};
348 static const WCHAR type_multi_sz[] = {'R','E','G','_','M','U','L','T','I','_','S','Z',0};
350 static const struct
352 DWORD type;
353 const WCHAR *name;
355 type_rels[] =
357 {REG_NONE, type_none},
358 {REG_SZ, type_sz},
359 {REG_EXPAND_SZ, type_expand_sz},
360 {REG_BINARY, type_binary},
361 {REG_DWORD, type_dword},
362 {REG_DWORD_LITTLE_ENDIAN, type_dword_le},
363 {REG_DWORD_BIG_ENDIAN, type_dword_be},
364 {REG_MULTI_SZ, type_multi_sz},
367 static const WCHAR *reg_type_to_wchar(DWORD type)
369 int i, array_size = ARRAY_SIZE(type_rels);
371 for (i = 0; i < array_size; i++)
373 if (type == type_rels[i].type)
374 return type_rels[i].name;
376 return NULL;
379 /******************************************************************************
380 * Sets the value with name val_name to the data in val_data for the currently
381 * opened key.
383 * Parameters:
384 * val_name - name of the registry value
385 * val_data - registry value data
387 static LONG setValue(WCHAR* val_name, WCHAR* val_data, BOOL is_unicode)
389 LONG res;
390 DWORD dwDataType, dwParseType;
391 LPBYTE lpbData;
392 DWORD dwData, dwLen;
393 WCHAR del[] = {'-',0};
395 if ( (val_name == NULL) || (val_data == NULL) )
396 return ERROR_INVALID_PARAMETER;
398 if (lstrcmpW(val_data, del) == 0)
400 res=RegDeleteValueW(currentKeyHandle,val_name);
401 return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
404 /* Get the data type stored into the value field */
405 dwDataType = getDataType(&val_data, &dwParseType);
407 if (dwParseType == REG_SZ) /* no conversion for string */
409 dwLen = REGPROC_unescape_string(val_data);
410 if(!dwLen || val_data[dwLen-1] != '"')
411 return ERROR_INVALID_DATA;
412 val_data[dwLen-1] = '\0'; /* remove last quotes */
413 lpbData = (BYTE*) val_data;
414 dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
416 else if (dwParseType == REG_DWORD) /* Convert the dword types */
418 if (!convertHexToDWord(val_data, &dwData))
419 return ERROR_INVALID_DATA;
420 lpbData = (BYTE*)&dwData;
421 dwLen = sizeof(dwData);
423 else if (dwParseType == REG_BINARY) /* Convert the binary data */
425 lpbData = convertHexCSVToHex(val_data, &dwLen);
426 if (!lpbData)
427 return ERROR_INVALID_DATA;
429 if((dwDataType == REG_MULTI_SZ || dwDataType == REG_EXPAND_SZ) && !is_unicode)
431 LPBYTE tmp = lpbData;
432 lpbData = (LPBYTE)GetWideStringN((char*)lpbData, dwLen, &dwLen);
433 dwLen *= sizeof(WCHAR);
434 HeapFree(GetProcessHeap(), 0, tmp);
437 else /* unknown format */
439 output_message(STRING_UNKNOWN_DATA_FORMAT, reg_type_to_wchar(dwDataType));
440 return ERROR_INVALID_DATA;
443 res = RegSetValueExW(
444 currentKeyHandle,
445 val_name,
446 0, /* Reserved */
447 dwDataType,
448 lpbData,
449 dwLen);
450 if (dwParseType == REG_BINARY)
451 HeapFree(GetProcessHeap(), 0, lpbData);
452 return res;
455 /******************************************************************************
456 * A helper function for processRegEntry() that opens the current key.
457 * That key must be closed by calling closeKey().
459 static LONG openKeyW(WCHAR* stdInput)
461 HKEY keyClass;
462 WCHAR* keyPath;
463 DWORD dwDisp;
464 LONG res;
466 /* Sanity checks */
467 if (stdInput == NULL)
468 return ERROR_INVALID_PARAMETER;
470 /* Get the registry class */
471 if (!parseKeyName(stdInput, &keyClass, &keyPath))
472 return ERROR_INVALID_PARAMETER;
474 res = RegCreateKeyExW(
475 keyClass, /* Class */
476 keyPath, /* Sub Key */
477 0, /* MUST BE 0 */
478 NULL, /* object type */
479 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
480 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
481 NULL, /* security attribute */
482 &currentKeyHandle, /* result */
483 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
484 REG_OPENED_EXISTING_KEY */
486 if (res == ERROR_SUCCESS)
488 currentKeyName = HeapAlloc(GetProcessHeap(), 0, (strlenW(stdInput) + 1) * sizeof(WCHAR));
489 CHECK_ENOUGH_MEMORY(currentKeyName);
490 strcpyW(currentKeyName, stdInput);
492 else
493 currentKeyHandle = NULL;
495 return res;
499 /******************************************************************************
500 * Close the currently opened key.
502 static void closeKey(void)
504 if (currentKeyHandle)
506 HeapFree(GetProcessHeap(), 0, currentKeyName);
507 RegCloseKey(currentKeyHandle);
508 currentKeyHandle = NULL;
512 /******************************************************************************
513 * This function is a wrapper for the setValue function. It prepares the
514 * land and cleans the area once completed.
515 * Note: this function modifies the line parameter.
517 * line - registry file unwrapped line. Should have the registry value name and
518 * complete registry value data.
520 static void processSetValue(WCHAR* line, BOOL is_unicode)
522 WCHAR* val_name; /* registry value name */
523 WCHAR* val_data; /* registry value data */
524 int line_idx = 0; /* current character under analysis */
525 LONG res;
527 /* get value name */
528 while ( isspaceW(line[line_idx]) ) line_idx++;
529 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
530 line[line_idx] = '\0';
531 val_name = line;
532 line_idx++;
533 } else if (line[line_idx] == '\"') {
534 line_idx++;
535 val_name = line + line_idx;
536 while (line[line_idx]) {
537 if (line[line_idx] == '\\') /* skip escaped character */
539 line_idx += 2;
540 } else {
541 if (line[line_idx] == '\"') {
542 line[line_idx] = '\0';
543 line_idx++;
544 break;
545 } else {
546 line_idx++;
550 while ( isspaceW(line[line_idx]) ) line_idx++;
551 if (!line[line_idx]) {
552 output_message(STRING_UNEXPECTED_EOL, line);
553 return;
555 if (line[line_idx] != '=') {
556 line[line_idx] = '\"';
557 output_message(STRING_UNRECOGNIZED_LINE, line);
558 return;
561 } else {
562 output_message(STRING_UNRECOGNIZED_LINE, line);
563 return;
565 line_idx++; /* skip the '=' character */
567 while ( isspaceW(line[line_idx]) ) line_idx++;
568 val_data = line + line_idx;
569 /* trim trailing blanks */
570 line_idx = strlenW(val_data);
571 while (line_idx > 0 && isspaceW(val_data[line_idx-1])) line_idx--;
572 val_data[line_idx] = '\0';
574 REGPROC_unescape_string(val_name);
575 res = setValue(val_name, val_data, is_unicode);
576 if ( res != ERROR_SUCCESS )
577 output_message(STRING_SETVALUE_FAILED, val_name, currentKeyName);
580 /******************************************************************************
581 * This function receives the currently read entry and performs the
582 * corresponding action.
583 * isUnicode affects parsing of REG_MULTI_SZ values
585 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
587 if ( stdInput[0] == '[') /* We are reading a new key */
589 WCHAR* keyEnd;
590 closeKey(); /* Close the previous key */
592 /* Get rid of the square brackets */
593 stdInput++;
594 keyEnd = strrchrW(stdInput, ']');
595 if (keyEnd)
596 *keyEnd='\0';
598 /* delete the key if we encounter '-' at the start of reg key */
599 if (stdInput[0] == '-')
600 delete_registry_key(stdInput + 1);
601 else if (openKeyW(stdInput) != ERROR_SUCCESS)
602 output_message(STRING_OPEN_KEY_FAILED, stdInput);
603 } else if( currentKeyHandle &&
604 (( stdInput[0] == '@') || /* reading a default @=data pair */
605 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
607 processSetValue(stdInput, isUnicode);
611 /******************************************************************************
612 * Processes a registry file.
613 * Correctly processes comments (in # and ; form), line continuation.
615 * Parameters:
616 * in - input stream to read from
617 * first_chars - beginning of stream, read due to Unicode check
619 static void processRegLinesA(FILE *in, char* first_chars)
621 char *buf = NULL; /* the line read from the input stream */
622 unsigned long line_size = REG_VAL_BUF_SIZE;
623 size_t chars_in_buf = -1;
624 char *s; /* A pointer to buf for fread */
625 char *line; /* The start of the current line */
626 WCHAR *lineW;
628 buf = HeapAlloc(GetProcessHeap(), 0, line_size);
629 CHECK_ENOUGH_MEMORY(buf);
630 s = buf;
631 line = buf;
633 memcpy(line, first_chars, 2);
635 if (first_chars)
636 s += 2;
638 while (!feof(in)) {
639 size_t size_remaining;
640 int size_to_get;
641 char *s_eol = NULL; /* various local uses */
643 /* Do we need to expand the buffer? */
644 assert(s >= buf && s <= buf + line_size);
645 size_remaining = line_size - (s - buf);
646 if (size_remaining < 3) /* we need at least 3 bytes of room for \r\n\0 */
648 char *new_buffer;
649 size_t new_size = line_size + REG_VAL_BUF_SIZE;
650 if (new_size > line_size) /* no arithmetic overflow */
651 new_buffer = HeapReAlloc(GetProcessHeap(), 0, buf, new_size);
652 else
653 new_buffer = NULL;
654 CHECK_ENOUGH_MEMORY(new_buffer);
655 buf = new_buffer;
656 line = buf;
657 s = buf + line_size - size_remaining;
658 line_size = new_size;
659 size_remaining = line_size - (s - buf);
662 /* Get as much as possible into the buffer, terminating on EOF,
663 * error or once we have read the maximum amount. Abort on error.
665 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
667 chars_in_buf = fread(s, 1, size_to_get - 1, in);
668 s[chars_in_buf] = 0;
670 if (chars_in_buf == 0) {
671 if (ferror(in)) {
672 perror("While reading input");
673 exit(IO_ERROR);
674 } else {
675 assert(feof(in));
676 *s = '\0';
680 /* If we didn't read the end-of-line sequence or EOF, go around again */
681 while (1)
683 s_eol = strpbrk(line, "\r\n");
684 if (!s_eol) {
685 /* Move the stub of the line to the start of the buffer so
686 * we get the maximum space to read into, and so we don't
687 * have to recalculate 'line' if the buffer expands */
688 MoveMemory(buf, line, strlen(line) + 1);
689 line = buf;
690 s = strchr(line, '\0');
691 break;
694 /* If we find a comment line, discard it and go around again */
695 if (line [0] == '#' || line [0] == ';') {
696 if (*s_eol == '\r' && *(s_eol + 1) == '\n')
697 line = s_eol + 2;
698 else
699 line = s_eol + 1;
700 continue;
703 /* If there is a concatenating '\\', go around again */
704 if (*(s_eol - 1) == '\\') {
705 char *next_line = s_eol + 1;
707 if (*s_eol == '\r' && *(s_eol + 1) == '\n')
708 next_line++;
710 while (*(next_line + 1) == ' ' || *(next_line + 1) == '\t')
711 next_line++;
713 MoveMemory(s_eol - 1, next_line, chars_in_buf - (next_line - s) + 1);
714 chars_in_buf -= next_line - s_eol + 1;
715 continue;
718 /* Remove any line feed. Leave s_eol on the last \0 */
719 if (*s_eol == '\r' && *(s_eol + 1) == '\n')
720 *s_eol++ = '\0';
721 *s_eol = '\0';
723 lineW = GetWideString(line);
724 processRegEntry(lineW, FALSE);
725 HeapFree(GetProcessHeap(), 0, lineW);
726 line = s_eol + 1;
729 closeKey();
731 HeapFree(GetProcessHeap(), 0, buf);
734 static void processRegLinesW(FILE *in)
736 WCHAR* buf = NULL; /* line read from input stream */
737 ULONG lineSize = REG_VAL_BUF_SIZE;
738 size_t CharsInBuf = -1;
740 WCHAR* s; /* The pointer into buf for where the current fgets should read */
741 WCHAR* line; /* The start of the current line */
743 buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
744 CHECK_ENOUGH_MEMORY(buf);
746 s = buf;
747 line = buf;
749 while(!feof(in)) {
750 size_t size_remaining;
751 int size_to_get;
752 WCHAR *s_eol = NULL; /* various local uses */
754 /* Do we need to expand the buffer ? */
755 assert (s >= buf && s <= buf + lineSize);
756 size_remaining = lineSize - (s-buf);
757 if (size_remaining < 2) /* room for 1 character and the \0 */
759 WCHAR *new_buffer;
760 size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
761 if (new_size > lineSize) /* no arithmetic overflow */
762 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
763 else
764 new_buffer = NULL;
765 CHECK_ENOUGH_MEMORY(new_buffer);
766 buf = new_buffer;
767 line = buf;
768 s = buf + lineSize - size_remaining;
769 lineSize = new_size;
770 size_remaining = lineSize - (s-buf);
773 /* Get as much as possible into the buffer, terminated either by
774 * eof, error or getting the maximum amount. Abort on error.
776 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
778 CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
779 s[CharsInBuf] = 0;
781 if (CharsInBuf == 0) {
782 if (ferror(in)) {
783 perror ("While reading input");
784 exit (IO_ERROR);
785 } else {
786 assert (feof(in));
787 *s = '\0';
788 /* It is not clear to me from the definition that the
789 * contents of the buffer are well defined on detecting
790 * an eof without managing to read anything.
795 /* If we didn't read the eol nor the eof go around for the rest */
796 while(1)
798 const WCHAR line_endings[] = {'\r','\n',0};
799 s_eol = strpbrkW(line, line_endings);
801 if(!s_eol) {
802 /* Move the stub of the line to the start of the buffer so
803 * we get the maximum space to read into, and so we don't
804 * have to recalculate 'line' if the buffer expands */
805 MoveMemory(buf, line, (strlenW(line)+1) * sizeof(WCHAR));
806 line = buf;
807 s = strchrW(line, '\0');
808 break;
811 /* If it is a comment line then discard it and go around again */
812 if (*line == '#' || *line == ';') {
813 if (*s_eol == '\r' && *(s_eol+1) == '\n')
814 line = s_eol + 2;
815 else
816 line = s_eol + 1;
817 continue;
820 /* If there is a concatenating \\ then go around again */
821 if (*(s_eol-1) == '\\') {
822 WCHAR* NextLine = s_eol + 1;
824 if(*s_eol == '\r' && *(s_eol+1) == '\n')
825 NextLine++;
827 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
828 NextLine++;
830 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - s) + 1)*sizeof(WCHAR));
831 CharsInBuf -= NextLine - s_eol + 1;
832 continue;
835 /* Remove any line feed. Leave s_eol on the last \0 */
836 if (*s_eol == '\r' && *(s_eol + 1) == '\n')
837 *s_eol++ = '\0';
838 *s_eol = '\0';
840 processRegEntry(line, TRUE);
841 line = s_eol + 1;
845 closeKey();
847 HeapFree(GetProcessHeap(), 0, buf);
850 /******************************************************************************
851 * Checks whether the buffer has enough room for the string or required size.
852 * Resizes the buffer if necessary.
854 * Parameters:
855 * buffer - pointer to a buffer for string
856 * len - current length of the buffer in characters.
857 * required_len - length of the string to place to the buffer in characters.
858 * The length does not include the terminating null character.
860 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
862 required_len++;
863 if (required_len > *len) {
864 *len = required_len;
865 if (!*buffer)
866 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
867 else
868 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
869 CHECK_ENOUGH_MEMORY(*buffer);
873 /******************************************************************************
874 * Same as REGPROC_resize_char_buffer() but on a regular buffer.
876 * Parameters:
877 * buffer - pointer to a buffer
878 * len - current size of the buffer in bytes
879 * required_size - size of the data to place in the buffer in bytes
881 static void REGPROC_resize_binary_buffer(BYTE **buffer, DWORD *size, DWORD required_size)
883 if (required_size > *size) {
884 *size = required_size;
885 if (!*buffer)
886 *buffer = HeapAlloc(GetProcessHeap(), 0, *size);
887 else
888 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *size);
889 CHECK_ENOUGH_MEMORY(*buffer);
893 /******************************************************************************
894 * Prints string str to file
896 static void REGPROC_export_string(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, WCHAR *str, DWORD str_len)
898 DWORD i, pos;
899 DWORD extra = 0;
901 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + 10);
903 /* escaping characters */
904 pos = *line_len;
905 for (i = 0; i < str_len; i++) {
906 WCHAR c = str[i];
907 switch (c) {
908 case '\n':
909 extra++;
910 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
911 (*line_buf)[pos++] = '\\';
912 (*line_buf)[pos++] = 'n';
913 break;
915 case '\r':
916 extra++;
917 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
918 (*line_buf)[pos++] = '\\';
919 (*line_buf)[pos++] = 'r';
920 break;
922 case '\\':
923 case '"':
924 extra++;
925 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
926 (*line_buf)[pos++] = '\\';
927 /* Fall through */
929 default:
930 (*line_buf)[pos++] = c;
931 break;
934 (*line_buf)[pos] = '\0';
935 *line_len = pos;
938 static void REGPROC_export_binary(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, DWORD type, BYTE *value, DWORD value_size, BOOL unicode)
940 DWORD hex_pos, data_pos;
941 const WCHAR *hex_prefix;
942 const WCHAR hex[] = {'h','e','x',':',0};
943 WCHAR hex_buf[17];
944 const WCHAR concat[] = {'\\','\r','\n',' ',' ',0};
945 DWORD concat_prefix, concat_len;
946 const WCHAR newline[] = {'\r','\n',0};
947 CHAR* value_multibyte = NULL;
949 if (type == REG_BINARY) {
950 hex_prefix = hex;
951 } else {
952 const WCHAR hex_format[] = {'h','e','x','(','%','x',')',':',0};
953 hex_prefix = hex_buf;
954 sprintfW(hex_buf, hex_format, type);
955 if ((type == REG_SZ || type == REG_EXPAND_SZ || type == REG_MULTI_SZ) && !unicode)
957 value_multibyte = GetMultiByteStringN((WCHAR*)value, value_size / sizeof(WCHAR), &value_size);
958 value = (BYTE*)value_multibyte;
962 concat_len = lstrlenW(concat);
963 concat_prefix = 2;
965 hex_pos = *line_len;
966 *line_len += lstrlenW(hex_prefix);
967 data_pos = *line_len;
968 *line_len += value_size * 3;
969 /* - The 2 spaces that concat places at the start of the
970 * line effectively reduce the space available for data.
971 * - If the value name and hex prefix are very long
972 * ( > REG_FILE_HEX_LINE_LEN) or *line_len divides
973 * without a remainder then we may overestimate
974 * the needed number of lines by one. But that's ok.
975 * - The trailing '\r' takes the place of a comma so
976 * we only need to add 1 for the trailing '\n'
978 *line_len += *line_len / (REG_FILE_HEX_LINE_LEN - concat_prefix) * concat_len + 1;
979 REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len);
980 lstrcpyW(*line_buf + hex_pos, hex_prefix);
981 if (value_size)
983 const WCHAR format[] = {'%','0','2','x',0};
984 DWORD i, column;
986 column = data_pos; /* no line wrap yet */
987 i = 0;
988 while (1)
990 sprintfW(*line_buf + data_pos, format, (unsigned int)value[i]);
991 data_pos += 2;
992 if (++i == value_size)
993 break;
995 (*line_buf)[data_pos++] = ',';
996 column += 3;
998 /* wrap the line */
999 if (column >= REG_FILE_HEX_LINE_LEN) {
1000 lstrcpyW(*line_buf + data_pos, concat);
1001 data_pos += concat_len;
1002 column = concat_prefix;
1006 lstrcpyW(*line_buf + data_pos, newline);
1007 HeapFree(GetProcessHeap(), 0, value_multibyte);
1010 /******************************************************************************
1011 * Writes the given line to a file, in multi-byte or wide characters
1013 static void REGPROC_write_line(FILE *file, const WCHAR* str, BOOL unicode)
1015 if(unicode)
1017 fwrite(str, sizeof(WCHAR), lstrlenW(str), file);
1018 } else
1020 char* strA = GetMultiByteString(str);
1021 fputs(strA, file);
1022 HeapFree(GetProcessHeap(), 0, strA);
1026 /******************************************************************************
1027 * Writes contents of the registry key to the specified file stream.
1029 * Parameters:
1030 * file - writable file stream to export registry branch to.
1031 * key - registry branch to export.
1032 * reg_key_name_buf - name of the key with registry class.
1033 * Is resized if necessary.
1034 * reg_key_name_size - length of the buffer for the registry class in characters.
1035 * val_name_buf - buffer for storing value name.
1036 * Is resized if necessary.
1037 * val_name_size - length of the buffer for storing value names in characters.
1038 * val_buf - buffer for storing values while extracting.
1039 * Is resized if necessary.
1040 * val_size - size of the buffer for storing values in bytes.
1042 static void export_hkey(FILE *file, HKEY key,
1043 WCHAR **reg_key_name_buf, DWORD *reg_key_name_size,
1044 WCHAR **val_name_buf, DWORD *val_name_size,
1045 BYTE **val_buf, DWORD *val_size,
1046 WCHAR **line_buf, DWORD *line_buf_size,
1047 BOOL unicode)
1049 DWORD max_sub_key_len;
1050 DWORD max_val_name_len;
1051 DWORD max_val_size;
1052 DWORD curr_len;
1053 DWORD i;
1054 LONG ret;
1055 WCHAR key_format[] = {'\r','\n','[','%','s',']','\r','\n',0};
1057 /* get size information and resize the buffers if necessary */
1058 if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
1059 &max_sub_key_len, NULL,
1060 NULL, &max_val_name_len, &max_val_size, NULL, NULL
1061 ) != ERROR_SUCCESS)
1062 return;
1063 curr_len = strlenW(*reg_key_name_buf);
1064 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size,
1065 max_sub_key_len + curr_len + 1);
1066 REGPROC_resize_char_buffer(val_name_buf, val_name_size,
1067 max_val_name_len);
1068 REGPROC_resize_binary_buffer(val_buf, val_size, max_val_size);
1069 REGPROC_resize_char_buffer(line_buf, line_buf_size, lstrlenW(*reg_key_name_buf) + 4);
1070 /* output data for the current key */
1071 sprintfW(*line_buf, key_format, *reg_key_name_buf);
1072 REGPROC_write_line(file, *line_buf, unicode);
1074 /* print all the values */
1075 i = 0;
1076 for (;;) {
1077 DWORD value_type;
1078 DWORD val_name_size1 = *val_name_size;
1079 DWORD val_size1 = *val_size;
1080 ret = RegEnumValueW(key, i, *val_name_buf, &val_name_size1, NULL,
1081 &value_type, *val_buf, &val_size1);
1082 if (ret == ERROR_MORE_DATA) {
1083 /* Increase the size of the buffers and retry */
1084 REGPROC_resize_char_buffer(val_name_buf, val_name_size, val_name_size1);
1085 REGPROC_resize_binary_buffer(val_buf, val_size, val_size1);
1086 } else if (ret == ERROR_SUCCESS) {
1087 DWORD line_len;
1088 i++;
1090 if ((*val_name_buf)[0]) {
1091 const WCHAR val_start[] = {'"','%','s','"','=',0};
1093 line_len = 0;
1094 REGPROC_export_string(line_buf, line_buf_size, &line_len, *val_name_buf, lstrlenW(*val_name_buf));
1095 REGPROC_resize_char_buffer(val_name_buf, val_name_size, lstrlenW(*line_buf) + 1);
1096 lstrcpyW(*val_name_buf, *line_buf);
1098 line_len = 3 + lstrlenW(*val_name_buf);
1099 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1100 sprintfW(*line_buf, val_start, *val_name_buf);
1101 } else {
1102 const WCHAR std_val[] = {'@','=',0};
1103 line_len = 2;
1104 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1105 lstrcpyW(*line_buf, std_val);
1108 switch (value_type) {
1109 case REG_SZ:
1111 WCHAR* wstr = (WCHAR*)*val_buf;
1113 if (val_size1 < sizeof(WCHAR) || val_size1 % sizeof(WCHAR) ||
1114 wstr[val_size1 / sizeof(WCHAR) - 1]) {
1115 REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1116 } else {
1117 const WCHAR start[] = {'"',0};
1118 const WCHAR end[] = {'"','\r','\n',0};
1119 DWORD len;
1121 len = lstrlenW(start);
1122 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + len);
1123 lstrcpyW(*line_buf + line_len, start);
1124 line_len += len;
1126 REGPROC_export_string(line_buf, line_buf_size, &line_len, wstr, lstrlenW(wstr));
1128 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + lstrlenW(end));
1129 lstrcpyW(*line_buf + line_len, end);
1131 break;
1134 case REG_DWORD:
1136 WCHAR format[] = {'d','w','o','r','d',':','%','0','8','x','\r','\n',0};
1138 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + 15);
1139 sprintfW(*line_buf + line_len, format, *((DWORD *)*val_buf));
1140 break;
1143 default:
1145 output_message(STRING_UNSUPPORTED_TYPE, reg_type_to_wchar(value_type), *reg_key_name_buf);
1146 output_message(STRING_EXPORT_AS_BINARY, *val_name_buf);
1148 /* falls through */
1149 case REG_EXPAND_SZ:
1150 case REG_MULTI_SZ:
1151 /* falls through */
1152 case REG_BINARY:
1153 REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1155 REGPROC_write_line(file, *line_buf, unicode);
1157 else break;
1160 i = 0;
1161 (*reg_key_name_buf)[curr_len] = '\\';
1162 for (;;) {
1163 DWORD buf_size = *reg_key_name_size - curr_len - 1;
1165 ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_size,
1166 NULL, NULL, NULL, NULL);
1167 if (ret == ERROR_MORE_DATA) {
1168 /* Increase the size of the buffer and retry */
1169 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size, curr_len + 1 + buf_size);
1170 } else if (ret == ERROR_SUCCESS) {
1171 HKEY subkey;
1173 i++;
1174 if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1175 &subkey) == ERROR_SUCCESS) {
1176 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_size,
1177 val_name_buf, val_name_size, val_buf, val_size,
1178 line_buf, line_buf_size, unicode);
1179 RegCloseKey(subkey);
1181 else break;
1183 else break;
1185 (*reg_key_name_buf)[curr_len] = '\0';
1188 /******************************************************************************
1189 * Open file in binary mode for export.
1191 static FILE *REGPROC_open_export_file(WCHAR *file_name, BOOL unicode)
1193 FILE *file;
1194 WCHAR dash = '-';
1196 if (strncmpW(file_name,&dash,1)==0) {
1197 file=stdout;
1198 _setmode(_fileno(file), _O_BINARY);
1199 } else
1201 WCHAR wb_mode[] = {'w','b',0};
1202 WCHAR regedit[] = {'r','e','g','e','d','i','t',0};
1204 file = _wfopen(file_name, wb_mode);
1205 if (!file) {
1206 _wperror(regedit);
1207 output_message(STRING_CANNOT_OPEN_FILE, file_name);
1208 exit(1);
1211 if(unicode)
1213 const BYTE unicode_seq[] = {0xff,0xfe};
1214 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'};
1215 fwrite(unicode_seq, sizeof(BYTE), sizeof(unicode_seq)/sizeof(unicode_seq[0]), file);
1216 fwrite(header, sizeof(WCHAR), sizeof(header)/sizeof(header[0]), file);
1217 } else
1219 fputs("REGEDIT4\r\n", file);
1222 return file;
1225 /******************************************************************************
1226 * Writes contents of the registry key to the specified file stream.
1228 * Parameters:
1229 * file_name - name of a file to export registry branch to.
1230 * reg_key_name - registry branch to export. The whole registry is exported if
1231 * reg_key_name is NULL or contains an empty string.
1233 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name, DWORD format)
1235 WCHAR *reg_key_name_buf;
1236 WCHAR *val_name_buf;
1237 BYTE *val_buf;
1238 WCHAR *line_buf;
1239 DWORD reg_key_name_size = KEY_MAX_LEN;
1240 DWORD val_name_size = KEY_MAX_LEN;
1241 DWORD val_size = REG_VAL_BUF_SIZE;
1242 DWORD line_buf_size = KEY_MAX_LEN + REG_VAL_BUF_SIZE;
1243 FILE *file = NULL;
1244 BOOL unicode = (format == REG_FORMAT_5);
1246 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1247 reg_key_name_size * sizeof(*reg_key_name_buf));
1248 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1249 val_name_size * sizeof(*val_name_buf));
1250 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1251 line_buf = HeapAlloc(GetProcessHeap(), 0, line_buf_size * sizeof(*line_buf));
1252 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf && line_buf);
1254 if (reg_key_name && reg_key_name[0]) {
1255 HKEY reg_key_class;
1256 WCHAR *branch_name = NULL;
1257 HKEY key;
1259 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_size,
1260 lstrlenW(reg_key_name));
1261 lstrcpyW(reg_key_name_buf, reg_key_name);
1263 /* open the specified key */
1264 if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1265 output_message(STRING_INCORRECT_REG_CLASS, reg_key_name);
1266 exit(1);
1268 if (!branch_name[0]) {
1269 /* no branch - registry class is specified */
1270 file = REGPROC_open_export_file(file_name, unicode);
1271 export_hkey(file, reg_key_class,
1272 &reg_key_name_buf, &reg_key_name_size,
1273 &val_name_buf, &val_name_size,
1274 &val_buf, &val_size, &line_buf,
1275 &line_buf_size, unicode);
1276 } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1277 file = REGPROC_open_export_file(file_name, unicode);
1278 export_hkey(file, key,
1279 &reg_key_name_buf, &reg_key_name_size,
1280 &val_name_buf, &val_name_size,
1281 &val_buf, &val_size, &line_buf,
1282 &line_buf_size, unicode);
1283 RegCloseKey(key);
1284 } else {
1285 output_message(STRING_REG_KEY_NOT_FOUND, reg_key_name);
1287 } else {
1288 unsigned int i;
1290 /* export all registry classes */
1291 file = REGPROC_open_export_file(file_name, unicode);
1292 for (i = 0; i < ARRAY_SIZE(reg_class_keys); i++) {
1293 /* do not export HKEY_CLASSES_ROOT */
1294 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1295 reg_class_keys[i] != HKEY_CURRENT_USER &&
1296 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1297 reg_class_keys[i] != HKEY_DYN_DATA) {
1298 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1299 export_hkey(file, reg_class_keys[i],
1300 &reg_key_name_buf, &reg_key_name_size,
1301 &val_name_buf, &val_name_size,
1302 &val_buf, &val_size, &line_buf,
1303 &line_buf_size, unicode);
1308 if (file) {
1309 fclose(file);
1311 HeapFree(GetProcessHeap(), 0, reg_key_name);
1312 HeapFree(GetProcessHeap(), 0, val_name_buf);
1313 HeapFree(GetProcessHeap(), 0, val_buf);
1314 HeapFree(GetProcessHeap(), 0, line_buf);
1315 return TRUE;
1318 /******************************************************************************
1319 * Reads contents of the specified file into the registry.
1321 BOOL import_registry_file(FILE* reg_file)
1323 if (reg_file)
1325 BYTE s[2];
1326 if (fread( s, 2, 1, reg_file) == 1)
1328 if (s[0] == 0xff && s[1] == 0xfe)
1330 processRegLinesW(reg_file);
1331 } else
1333 processRegLinesA(reg_file, (char*)s);
1336 return TRUE;
1338 return FALSE;
1341 /******************************************************************************
1342 * Removes the registry key with all subkeys. Parses full key name.
1344 * Parameters:
1345 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1346 * empty, points to register key class, does not exist.
1348 void delete_registry_key(WCHAR *reg_key_name)
1350 WCHAR *key_name = NULL;
1351 HKEY key_class;
1353 if (!reg_key_name || !reg_key_name[0])
1354 return;
1356 if (!parseKeyName(reg_key_name, &key_class, &key_name)) {
1357 output_message(STRING_INCORRECT_REG_CLASS, reg_key_name);
1358 exit(1);
1360 if (!*key_name) {
1361 output_message(STRING_DELETE_REG_CLASS_FAILED, reg_key_name);
1362 exit(1);
1365 RegDeleteTreeW(key_class, key_name);