regedit: Fix char escaping for registry export.
[wine/hacks.git] / programs / regedit / regproc.c
blobce26319e278e550e2e841fd2c50ac74cf6cbb2fc
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 <windows.h>
27 #include <winnt.h>
28 #include <winreg.h>
29 #include <assert.h>
30 #include <wine/unicode.h>
31 #include "regproc.h"
33 #define REG_VAL_BUF_SIZE 4096
35 /* maximal number of characters in hexadecimal data line,
36 not including '\' character */
37 #define REG_FILE_HEX_LINE_LEN 76
39 static const CHAR *reg_class_names[] = {
40 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
41 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
44 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
46 extern const WCHAR* reg_class_namesW[];
48 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
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 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 convers input from multibyte to wide chars
70 * Returned string must be freed by the caller
72 WCHAR* GetWideString(const char* strA)
74 if(strA)
76 WCHAR* strW = NULL;
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);
82 return strW;
84 return NULL;
87 /******************************************************************************
88 * Allocates memory and convers input from multibyte to wide chars
89 * Returned string must be freed by the caller
91 WCHAR* GetWideStringN(const char* strA, int chars, DWORD *len)
93 if(strA)
95 WCHAR* strW = NULL;
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);
101 return strW;
103 *len = 0;
104 return NULL;
107 /******************************************************************************
108 * Allocates memory and convers input from wide chars to multibyte
109 * Returned string must be freed by the caller
111 char* GetMultiByteString(const WCHAR* strW)
113 if(strW)
115 char* strA = NULL;
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);
121 return strA;
123 return NULL;
126 /******************************************************************************
127 * Allocates memory and convers input from wide chars to multibyte
128 * Returned string must be freed by the caller
130 char* GetMultiByteStringN(const WCHAR* strW, int chars, DWORD* len)
132 if(strW)
134 char* strA = NULL;
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);
140 return strA;
142 *len = 0;
143 return NULL;
146 /******************************************************************************
147 * Converts a hex representation of a DWORD into a DWORD.
149 static BOOL convertHexToDWord(WCHAR* str, DWORD *dw)
151 char buf[9];
152 char dummy;
154 WideCharToMultiByte(CP_ACP, 0, str, -1, buf, 9, NULL, NULL);
155 if (lstrlenW(str) > 8 || sscanf(buf, "%x%c", dw, &dummy) != 1) {
156 fprintf(stderr,"%s: ERROR, invalid hex value\n", getAppName());
157 return FALSE;
159 return TRUE;
162 /******************************************************************************
163 * Converts a hex comma separated values list into a binary string.
165 static BYTE* convertHexCSVToHex(WCHAR *str, DWORD *size)
167 WCHAR *s;
168 BYTE *d, *data;
170 /* The worst case is 1 digit + 1 comma per byte */
171 *size=(lstrlenW(str)+1)/2;
172 data=HeapAlloc(GetProcessHeap(), 0, *size);
173 CHECK_ENOUGH_MEMORY(data);
175 s = str;
176 d = data;
177 *size=0;
178 while (*s != '\0') {
179 UINT wc;
180 WCHAR *end;
182 wc = strtoulW(s,&end,16);
183 if (end == s || wc > 0xff || (*end && *end != ',')) {
184 char* strA = GetMultiByteString(s);
185 fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
186 getAppName(), strA);
187 HeapFree(GetProcessHeap(), 0, data);
188 HeapFree(GetProcessHeap(), 0, strA);
189 return NULL;
191 *d++ =(BYTE)wc;
192 (*size)++;
193 if (*end) end++;
194 s = end;
197 return data;
200 /******************************************************************************
201 * This function returns the HKEY associated with the data type encoded in the
202 * value. It modifies the input parameter (key value) in order to skip this
203 * "now useless" data type information.
205 * Note: Updated based on the algorithm used in 'server/registry.c'
207 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
209 struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
211 static const WCHAR quote[] = {'"'};
212 static const WCHAR str[] = {'s','t','r',':','"'};
213 static const WCHAR str2[] = {'s','t','r','(','2',')',':','"'};
214 static const WCHAR hex[] = {'h','e','x',':'};
215 static const WCHAR dword[] = {'d','w','o','r','d',':'};
216 static const WCHAR hexp[] = {'h','e','x','('};
218 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
219 { quote, 1, REG_SZ, REG_SZ },
220 { str, 5, REG_SZ, REG_SZ },
221 { str2, 8, REG_EXPAND_SZ, REG_SZ },
222 { hex, 4, REG_BINARY, REG_BINARY },
223 { dword, 6, REG_DWORD, REG_DWORD },
224 { hexp, 4, -1, REG_BINARY },
225 { NULL, 0, 0, 0 }
228 const struct data_type *ptr;
229 int type;
231 for (ptr = data_types; ptr->tag; ptr++) {
232 if (strncmpW( ptr->tag, *lpValue, ptr->len ))
233 continue;
235 /* Found! */
236 *parse_type = ptr->parse_type;
237 type=ptr->type;
238 *lpValue+=ptr->len;
239 if (type == -1) {
240 WCHAR* end;
242 /* "hex(xx):" is special */
243 type = (int)strtoulW( *lpValue , &end, 16 );
244 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
245 type=REG_NONE;
246 } else {
247 *lpValue = end + 2;
250 return type;
252 *parse_type=REG_NONE;
253 return REG_NONE;
256 /******************************************************************************
257 * Replaces escape sequences with the characters.
259 static void REGPROC_unescape_string(WCHAR* str)
261 int str_idx = 0; /* current character under analysis */
262 int val_idx = 0; /* the last character of the unescaped string */
263 int len = lstrlenW(str);
264 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
265 if (str[str_idx] == '\\') {
266 str_idx++;
267 switch (str[str_idx]) {
268 case 'n':
269 str[val_idx] = '\n';
270 break;
271 case '\\':
272 case '"':
273 str[val_idx] = str[str_idx];
274 break;
275 default:
276 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
277 str[str_idx]);
278 str[val_idx] = str[str_idx];
279 break;
281 } else {
282 str[val_idx] = str[str_idx];
285 str[val_idx] = '\0';
288 static BOOL parseKeyName(LPWSTR lpKeyName, HKEY *hKey, LPWSTR *lpKeyPath)
290 WCHAR* lpSlash = NULL;
291 unsigned int i, len;
293 if (lpKeyName == NULL)
294 return FALSE;
296 for(i = 0; *(lpKeyName+i) != 0; i++)
298 if(*(lpKeyName+i) == '\\')
300 lpSlash = lpKeyName+i;
301 break;
305 if (lpSlash)
307 len = lpSlash-lpKeyName;
309 else
311 len = lstrlenW(lpKeyName);
312 lpSlash = lpKeyName+len;
314 *hKey = NULL;
316 for (i = 0; i < REG_CLASS_NUMBER; i++) {
317 if (CompareStringW(LOCALE_USER_DEFAULT, 0, lpKeyName, len, reg_class_namesW[i], len) == CSTR_EQUAL &&
318 len == lstrlenW(reg_class_namesW[i])) {
319 *hKey = reg_class_keys[i];
320 break;
324 if (*hKey == NULL)
325 return FALSE;
328 if (*lpSlash != '\0')
329 lpSlash++;
330 *lpKeyPath = lpSlash;
331 return TRUE;
334 /* Globals used by the setValue() & co */
335 static LPSTR currentKeyName;
336 static HKEY currentKeyHandle = NULL;
338 /******************************************************************************
339 * Sets the value with name val_name to the data in val_data for the currently
340 * opened key.
342 * Parameters:
343 * val_name - name of the registry value
344 * val_data - registry value data
346 static LONG setValue(WCHAR* val_name, WCHAR* val_data, BOOL is_unicode)
348 LONG res;
349 DWORD dwDataType, dwParseType;
350 LPBYTE lpbData;
351 DWORD dwData, dwLen;
352 WCHAR del[] = {'-',0};
354 if ( (val_name == NULL) || (val_data == NULL) )
355 return ERROR_INVALID_PARAMETER;
357 if (lstrcmpW(val_data, del) == 0)
359 res=RegDeleteValueW(currentKeyHandle,val_name);
360 return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
363 /* Get the data type stored into the value field */
364 dwDataType = getDataType(&val_data, &dwParseType);
366 if (dwParseType == REG_SZ) /* no conversion for string */
368 REGPROC_unescape_string(val_data);
369 /* Compute dwLen after REGPROC_unescape_string because it may
370 * have changed the string length and we don't want to store
371 * the extra garbage in the registry.
373 dwLen = lstrlenW(val_data);
374 if (dwLen>0 && val_data[dwLen-1]=='"')
376 dwLen--;
377 val_data[dwLen]='\0';
379 lpbData = (BYTE*) val_data;
380 dwLen++; /* include terminating null */
381 dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
383 else if (dwParseType == REG_DWORD) /* Convert the dword types */
385 if (!convertHexToDWord(val_data, &dwData))
386 return ERROR_INVALID_DATA;
387 lpbData = (BYTE*)&dwData;
388 dwLen = sizeof(dwData);
390 else if (dwParseType == REG_BINARY) /* Convert the binary data */
392 lpbData = convertHexCSVToHex(val_data, &dwLen);
393 if (!lpbData)
394 return ERROR_INVALID_DATA;
396 if(dwDataType == REG_MULTI_SZ && !is_unicode)
398 LPBYTE tmp = lpbData;
399 lpbData = (LPBYTE)GetWideStringN((char*)lpbData, dwLen, &dwLen);
400 dwLen *= sizeof(WCHAR);
401 HeapFree(GetProcessHeap(), 0, tmp);
404 else /* unknown format */
406 fprintf(stderr,"%s: ERROR, unknown data format\n", getAppName());
407 return ERROR_INVALID_DATA;
410 res = RegSetValueExW(
411 currentKeyHandle,
412 val_name,
413 0, /* Reserved */
414 dwDataType,
415 lpbData,
416 dwLen);
417 if (dwParseType == REG_BINARY)
418 HeapFree(GetProcessHeap(), 0, lpbData);
419 return res;
422 /******************************************************************************
423 * A helper function for processRegEntry() that opens the current key.
424 * That key must be closed by calling closeKey().
426 static LONG openKeyW(WCHAR* stdInput)
428 HKEY keyClass;
429 WCHAR* keyPath;
430 DWORD dwDisp;
431 LONG res;
433 /* Sanity checks */
434 if (stdInput == NULL)
435 return ERROR_INVALID_PARAMETER;
437 /* Get the registry class */
438 if (!parseKeyName(stdInput, &keyClass, &keyPath))
439 return ERROR_INVALID_PARAMETER;
441 res = RegCreateKeyExW(
442 keyClass, /* Class */
443 keyPath, /* Sub Key */
444 0, /* MUST BE 0 */
445 NULL, /* object type */
446 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
447 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
448 NULL, /* security attribute */
449 &currentKeyHandle, /* result */
450 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
451 REG_OPENED_EXISTING_KEY */
453 if (res == ERROR_SUCCESS)
454 currentKeyName = GetMultiByteString(stdInput);
455 else
456 currentKeyHandle = NULL;
458 return res;
462 /******************************************************************************
463 * Close the currently opened key.
465 static void closeKey(void)
467 if (currentKeyHandle)
469 HeapFree(GetProcessHeap(), 0, currentKeyName);
470 RegCloseKey(currentKeyHandle);
471 currentKeyHandle = NULL;
475 /******************************************************************************
476 * This function is a wrapper for the setValue function. It prepares the
477 * land and cleans the area once completed.
478 * Note: this function modifies the line parameter.
480 * line - registry file unwrapped line. Should have the registry value name and
481 * complete registry value data.
483 static void processSetValue(WCHAR* line, BOOL is_unicode)
485 WCHAR* val_name; /* registry value name */
486 WCHAR* val_data; /* registry value data */
487 int line_idx = 0; /* current character under analysis */
488 LONG res;
490 /* get value name */
491 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
492 line[line_idx] = '\0';
493 val_name = line;
494 line_idx++;
495 } else if (line[line_idx] == '\"') {
496 line_idx++;
497 val_name = line + line_idx;
498 while (TRUE) {
499 if (line[line_idx] == '\\') /* skip escaped character */
501 line_idx += 2;
502 } else {
503 if (line[line_idx] == '\"') {
504 line[line_idx] = '\0';
505 line_idx++;
506 break;
507 } else {
508 line_idx++;
512 if (line[line_idx] != '=') {
513 char* lineA;
514 line[line_idx] = '\"';
515 lineA = GetMultiByteString(line);
516 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
517 HeapFree(GetProcessHeap(), 0, lineA);
518 return;
521 } else {
522 char* lineA = GetMultiByteString(line);
523 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
524 HeapFree(GetProcessHeap(), 0, lineA);
525 return;
527 line_idx++; /* skip the '=' character */
528 val_data = line + line_idx;
530 REGPROC_unescape_string(val_name);
531 res = setValue(val_name, val_data, is_unicode);
532 if ( res != ERROR_SUCCESS )
534 char* val_nameA = GetMultiByteString(val_name);
535 char* val_dataA = GetMultiByteString(val_data);
536 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
537 getAppName(),
538 currentKeyName,
539 val_nameA,
540 val_dataA);
541 HeapFree(GetProcessHeap(), 0, val_nameA);
542 HeapFree(GetProcessHeap(), 0, val_dataA);
546 /******************************************************************************
547 * This function receives the currently read entry and performs the
548 * corresponding action.
549 * isUnicode affects parsing of REG_MULTI_SZ values
551 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
554 * We encountered the end of the file, make sure we
555 * close the opened key and exit
557 if (stdInput == NULL) {
558 closeKey();
559 return;
562 if ( stdInput[0] == '[') /* We are reading a new key */
564 WCHAR* keyEnd;
565 closeKey(); /* Close the previous key */
567 /* Get rid of the square brackets */
568 stdInput++;
569 keyEnd = strrchrW(stdInput, ']');
570 if (keyEnd)
571 *keyEnd='\0';
573 /* delete the key if we encounter '-' at the start of reg key */
574 if ( stdInput[0] == '-')
576 delete_registry_key(stdInput + 1);
577 } else if ( openKeyW(stdInput) != ERROR_SUCCESS )
579 fprintf(stderr,"%s: setValue failed to open key %s\n",
580 getAppName(), stdInput);
582 } else if( currentKeyHandle &&
583 (( stdInput[0] == '@') || /* reading a default @=data pair */
584 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
586 processSetValue(stdInput, isUnicode);
587 } else
589 /* Since we are assuming that the file format is valid we must be
590 * reading a blank line which indicates the end of this key processing
592 closeKey();
596 /******************************************************************************
597 * Processes a registry file.
598 * Correctly processes comments (in # form), line continuation.
600 * Parameters:
601 * in - input stream to read from
603 void processRegLinesA(FILE *in)
605 LPSTR line = NULL; /* line read from input stream */
606 ULONG lineSize = REG_VAL_BUF_SIZE;
608 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
609 CHECK_ENOUGH_MEMORY(line);
611 while (!feof(in)) {
612 LPSTR s; /* The pointer into line for where the current fgets should read */
613 LPSTR check;
614 WCHAR* lineW;
615 s = line;
616 for (;;) {
617 size_t size_remaining;
618 int size_to_get;
619 char *s_eol; /* various local uses */
621 /* Do we need to expand the buffer ? */
622 assert (s >= line && s <= line + lineSize);
623 size_remaining = lineSize - (s-line);
624 if (size_remaining < 2) /* room for 1 character and the \0 */
626 char *new_buffer;
627 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
628 if (new_size > lineSize) /* no arithmetic overflow */
629 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
630 else
631 new_buffer = NULL;
632 CHECK_ENOUGH_MEMORY(new_buffer);
633 line = new_buffer;
634 s = line + lineSize - size_remaining;
635 lineSize = new_size;
636 size_remaining = lineSize - (s-line);
639 /* Get as much as possible into the buffer, terminated either by
640 * eof, error, eol or getting the maximum amount. Abort on error.
642 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
644 check = fgets (s, size_to_get, in);
646 if (check == NULL) {
647 if (ferror(in)) {
648 perror ("While reading input");
649 exit (IO_ERROR);
650 } else {
651 assert (feof(in));
652 *s = '\0';
653 /* It is not clear to me from the definition that the
654 * contents of the buffer are well defined on detecting
655 * an eof without managing to read anything.
660 /* If we didn't read the eol nor the eof go around for the rest */
661 s_eol = strchr (s, '\n');
662 if (!feof (in) && !s_eol) {
663 s = strchr (s, '\0');
664 /* It should be s + size_to_get - 1 but this is safer */
665 continue;
668 /* If it is a comment line then discard it and go around again */
669 if (line [0] == '#') {
670 s = line;
671 continue;
674 /* Remove any line feed. Leave s_eol on the \0 */
675 if (s_eol) {
676 *s_eol = '\0';
677 if (s_eol > line && *(s_eol-1) == '\r')
678 *--s_eol = '\0';
679 } else
680 s_eol = strchr (s, '\0');
682 /* If there is a concatenating \\ then go around again */
683 if (s_eol > line && *(s_eol-1) == '\\') {
684 int c;
685 s = s_eol-1;
689 c = fgetc(in);
690 } while(c == ' ' || c == '\t');
692 if(c == EOF)
694 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
695 getAppName());
697 else
699 *s = c;
700 s++;
702 continue;
705 lineW = GetWideString(line);
707 break; /* That is the full virtual line */
710 processRegEntry(lineW, FALSE);
711 HeapFree(GetProcessHeap(), 0, lineW);
713 processRegEntry(NULL, FALSE);
715 HeapFree(GetProcessHeap(), 0, line);
718 void processRegLinesW(FILE *in)
720 WCHAR* buf = NULL; /* line read from input stream */
721 ULONG lineSize = REG_VAL_BUF_SIZE;
722 size_t CharsInBuf = -1;
724 WCHAR* s; /* The pointer into line for where the current fgets should read */
726 buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
727 CHECK_ENOUGH_MEMORY(buf);
729 s = buf;
731 while(!feof(in)) {
732 size_t size_remaining;
733 int size_to_get;
734 WCHAR *s_eol = NULL; /* various local uses */
736 /* Do we need to expand the buffer ? */
737 assert (s >= buf && s <= buf + lineSize);
738 size_remaining = lineSize - (s-buf);
739 if (size_remaining < 2) /* room for 1 character and the \0 */
741 WCHAR *new_buffer;
742 size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
743 if (new_size > lineSize) /* no arithmetic overflow */
744 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
745 else
746 new_buffer = NULL;
747 CHECK_ENOUGH_MEMORY(new_buffer);
748 buf = new_buffer;
749 s = buf + lineSize - size_remaining;
750 lineSize = new_size;
751 size_remaining = lineSize - (s-buf);
754 /* Get as much as possible into the buffer, terminated either by
755 * eof, error or getting the maximum amount. Abort on error.
757 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
759 CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
760 s[CharsInBuf] = 0;
762 if (CharsInBuf == 0) {
763 if (ferror(in)) {
764 perror ("While reading input");
765 exit (IO_ERROR);
766 } else {
767 assert (feof(in));
768 *s = '\0';
769 /* It is not clear to me from the definition that the
770 * contents of the buffer are well defined on detecting
771 * an eof without managing to read anything.
776 /* If we didn't read the eol nor the eof go around for the rest */
777 while(1)
779 s_eol = strchrW(s, '\n');
781 if(!s_eol)
782 break;
784 /* If it is a comment line then discard it and go around again */
785 if (*s == '#') {
786 s = s_eol + 1;
787 continue;
790 /* If there is a concatenating \\ then go around again */
791 if ((*(s_eol-1) == '\\') ||
792 (*(s_eol-1) == '\r' && *(s_eol-2) == '\\')) {
793 WCHAR* NextLine = s_eol;
795 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
796 NextLine++;
798 NextLine++;
800 if(*(s_eol-1) == '\r')
801 s_eol--;
803 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - buf) + 1)*sizeof(WCHAR));
804 CharsInBuf -= NextLine - s_eol + 1;
805 s_eol = 0;
806 continue;
809 /* Remove any line feed. Leave s_eol on the \0 */
810 if (s_eol) {
811 *s_eol = '\0';
812 if (s_eol > buf && *(s_eol-1) == '\r')
813 *(s_eol-1) = '\0';
816 if(!s_eol)
817 break;
819 processRegEntry(s, TRUE);
820 s = s_eol + 1;
821 s_eol = 0;
822 continue; /* That is the full virtual line */
826 processRegEntry(NULL, TRUE);
828 HeapFree(GetProcessHeap(), 0, buf);
831 /****************************************************************************
832 * REGPROC_print_error
834 * Print the message for GetLastError
837 static void REGPROC_print_error(void)
839 LPVOID lpMsgBuf;
840 DWORD error_code;
841 int status;
843 error_code = GetLastError ();
844 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
845 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
846 if (!status) {
847 fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
848 getAppName(), error_code, GetLastError());
849 exit(1);
851 puts(lpMsgBuf);
852 LocalFree((HLOCAL)lpMsgBuf);
853 exit(1);
856 /******************************************************************************
857 * Checks whether the buffer has enough room for the string or required size.
858 * Resizes the buffer if necessary.
860 * Parameters:
861 * buffer - pointer to a buffer for string
862 * len - current length of the buffer in characters.
863 * required_len - length of the string to place to the buffer in characters.
864 * The length does not include the terminating null character.
866 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
868 required_len++;
869 if (required_len > *len) {
870 *len = required_len;
871 if (!*buffer)
872 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
873 else
874 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
875 CHECK_ENOUGH_MEMORY(*buffer);
879 /******************************************************************************
880 * Prints string str to file
882 static void REGPROC_export_string(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_size, WCHAR *str)
884 DWORD len = lstrlenW(str);
885 DWORD i;
886 DWORD extra = 0;
888 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + 10);
890 /* escaping characters */
891 for (i = 0; i < len; i++) {
892 WCHAR c = str[i];
893 switch (c) {
894 case '\\':
896 const WCHAR escape[] = {'\\','\\'};
898 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + extra + 1);
899 memcpy(*line_buf + *line_size + i + extra - 1, escape, 2 * sizeof(WCHAR));
900 extra++;
901 break;
903 case '"':
905 const WCHAR escape[] = {'\\','"'};
907 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + extra + 1);
908 memcpy(*line_buf + *line_size + i + extra - 1, escape, 2 * sizeof(WCHAR));
909 extra++;
910 break;
912 case '\n':
914 const WCHAR escape[] = {'\\','n'};
916 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + extra + 1);
917 memcpy(*line_buf + *line_size + i + extra - 1, escape, 2 * sizeof(WCHAR));
918 extra++;
919 break;
921 default:
922 memcpy(*line_buf + *line_size + i + extra - 1, &c, sizeof(WCHAR));
923 break;
926 *line_size += len + extra;
927 *(*line_buf + *line_size - 1) = 0;
930 /******************************************************************************
931 * Writes the given line to a file, in multi-byte or wide characters
933 static void REGPROC_write_line(FILE *file, const WCHAR* str, BOOL unicode)
935 if(unicode)
937 fwrite(str, sizeof(WCHAR), lstrlenW(str), file);
938 } else
940 char* strA = GetMultiByteString(str);
941 fprintf(file, strA);
942 HeapFree(GetProcessHeap(), 0, strA);
946 /******************************************************************************
947 * Writes contents of the registry key to the specified file stream.
949 * Parameters:
950 * file - writable file stream to export registry branch to.
951 * key - registry branch to export.
952 * reg_key_name_buf - name of the key with registry class.
953 * Is resized if necessary.
954 * reg_key_name_len - length of the buffer for the registry class in characters.
955 * val_name_buf - buffer for storing value name.
956 * Is resized if necessary.
957 * val_name_len - length of the buffer for storing value names in characters.
958 * val_buf - buffer for storing values while extracting.
959 * Is resized if necessary.
960 * val_size - size of the buffer for storing values in bytes.
962 static void export_hkey(FILE *file, HKEY key,
963 WCHAR **reg_key_name_buf, DWORD *reg_key_name_len,
964 WCHAR **val_name_buf, DWORD *val_name_len,
965 BYTE **val_buf, DWORD *val_size,
966 WCHAR **line_buf, DWORD *line_buf_size,
967 BOOL unicode)
969 DWORD max_sub_key_len;
970 DWORD max_val_name_len;
971 DWORD max_val_size;
972 DWORD curr_len;
973 DWORD i;
974 BOOL more_data;
975 LONG ret;
976 WCHAR key_format[] = {'\n','[','%','s',']','\n',0};
977 DWORD line_pos;
979 /* get size information and resize the buffers if necessary */
980 if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
981 &max_sub_key_len, NULL,
982 NULL, &max_val_name_len, &max_val_size, NULL, NULL
983 ) != ERROR_SUCCESS) {
984 REGPROC_print_error();
986 curr_len = strlenW(*reg_key_name_buf);
987 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
988 max_sub_key_len + curr_len + 1);
989 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
990 max_val_name_len);
991 if (max_val_size > *val_size) {
992 *val_size = max_val_size;
993 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
994 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
995 CHECK_ENOUGH_MEMORY(val_buf);
998 REGPROC_resize_char_buffer(line_buf, line_buf_size, lstrlenW(*reg_key_name_buf) + 4);
999 /* output data for the current key */
1000 wsprintfW(*line_buf, key_format, *reg_key_name_buf);
1001 REGPROC_write_line(file, *line_buf, unicode);
1003 /* print all the values */
1004 i = 0;
1005 more_data = TRUE;
1006 while(more_data) {
1007 DWORD value_type;
1008 DWORD val_name_len1 = *val_name_len;
1009 DWORD val_size1 = *val_size;
1010 DWORD line_size = 0;
1011 ret = RegEnumValueW(key, i, *val_name_buf, &val_name_len1, NULL,
1012 &value_type, *val_buf, &val_size1);
1013 if (ret != ERROR_SUCCESS) {
1014 more_data = FALSE;
1015 if (ret != ERROR_NO_MORE_ITEMS) {
1016 REGPROC_print_error();
1018 } else {
1019 i++;
1021 if ((*val_name_buf)[0]) {
1022 const WCHAR val_start[] = {'"','%','s','"','=',0};
1024 line_size = 4 + lstrlenW(*val_name_buf);
1025 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1026 wsprintfW(*line_buf, val_start, *val_name_buf);
1027 line_pos = lstrlenW(*line_buf);
1028 } else {
1029 const WCHAR std_val[] = {'@','=',0};
1030 line_size = 3;
1031 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1032 lstrcpyW(*line_buf, std_val);
1033 line_pos = lstrlenW(*line_buf);
1036 switch (value_type) {
1037 case REG_SZ:
1038 case REG_EXPAND_SZ:
1040 const WCHAR start[] = {'"',0};
1041 const WCHAR end[] = {'"','\n',0};
1043 line_size += lstrlenW(start);
1044 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1045 lstrcatW(*line_buf, start);
1047 if (val_size1) REGPROC_export_string(line_buf, line_buf_size, &line_size, (WCHAR*) *val_buf);
1049 line_size += lstrlenW(end);
1050 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1051 lstrcatW(*line_buf, end);
1052 break;
1055 case REG_DWORD:
1057 WCHAR format[] = {'d','w','o','r','d',':','%','0','8','x','\n',0};
1059 line_size += 20;
1060 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1061 wsprintfW(*line_buf + line_pos, format, *((DWORD *)*val_buf));
1062 break;
1065 default:
1066 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
1067 "treat as binary\n",
1068 getAppName(), value_type);
1069 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
1070 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
1071 /* falls through */
1072 case REG_MULTI_SZ:
1073 /* falls through */
1074 case REG_BINARY: {
1075 DWORD i1;
1076 const WCHAR *hex_prefix;
1077 WCHAR buf[20];
1078 int cur_pos;
1079 const WCHAR hex[] = {'h','e','x',':',0};
1080 const WCHAR delim[] = {'"','"','=',0};
1081 const WCHAR format[] = {'%','0','2','x',0};
1082 const WCHAR comma[] = {',',0};
1083 const WCHAR concat[] = {'\\','\n',' ',' ',0};
1084 const WCHAR newline[] = {'\n',0};
1085 BYTE* val_buf1 = *val_buf;
1086 DWORD val_buf1_size = val_size1;
1088 if (value_type == REG_BINARY) {
1089 hex_prefix = hex;
1090 } else {
1091 const WCHAR hex_format[] = {'h','e','x','(','%','d',')',':',0};
1092 hex_prefix = buf;
1093 wsprintfW(buf, hex_format, value_type);
1094 if(value_type == REG_MULTI_SZ && !unicode)
1095 val_buf1 = (BYTE*)GetMultiByteStringN((WCHAR*)*val_buf, val_size1 / sizeof(WCHAR), &val_buf1_size);
1098 /* position of where the next character will be printed */
1099 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1100 cur_pos = lstrlenW(delim) + lstrlenW(hex) +
1101 lstrlenW(*val_name_buf);
1103 line_size += lstrlenW(hex_prefix);
1104 line_size += val_buf1_size * 3 + lstrlenW(concat) * ((int)((float)val_buf1_size * 3.0 / (float)REG_FILE_HEX_LINE_LEN) + 1 ) + 1;
1105 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1106 lstrcatW(*line_buf, hex_prefix);
1107 line_pos += lstrlenW(hex_prefix);
1108 for (i1 = 0; i1 < val_buf1_size; i1++) {
1109 wsprintfW(*line_buf + line_pos, format, (unsigned int)(val_buf1)[i1]);
1110 line_pos += 2;
1111 if (i1 + 1 < val_buf1_size) {
1112 lstrcpyW(*line_buf + line_pos, comma);
1113 line_pos++;
1115 cur_pos += 3;
1117 /* wrap the line */
1118 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1119 lstrcpyW(*line_buf + line_pos, concat);
1120 line_pos += lstrlenW(concat);
1121 cur_pos = 2;
1124 if(value_type == REG_MULTI_SZ && !unicode)
1125 HeapFree(GetProcessHeap(), 0, val_buf1);
1126 lstrcpyW(*line_buf + line_pos, newline);
1127 break;
1130 REGPROC_write_line(file, *line_buf, unicode);
1134 i = 0;
1135 more_data = TRUE;
1136 (*reg_key_name_buf)[curr_len] = '\\';
1137 while(more_data) {
1138 DWORD buf_len = *reg_key_name_len - curr_len;
1140 ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1141 NULL, NULL, NULL, NULL);
1142 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1143 more_data = FALSE;
1144 if (ret != ERROR_NO_MORE_ITEMS) {
1145 REGPROC_print_error();
1147 } else {
1148 HKEY subkey;
1150 i++;
1151 if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1152 &subkey) == ERROR_SUCCESS) {
1153 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1154 val_name_buf, val_name_len, val_buf, val_size,
1155 line_buf, line_buf_size, unicode);
1156 RegCloseKey(subkey);
1157 } else {
1158 REGPROC_print_error();
1162 (*reg_key_name_buf)[curr_len] = '\0';
1165 /******************************************************************************
1166 * Open file for export.
1168 static FILE *REGPROC_open_export_file(WCHAR *file_name, BOOL unicode)
1170 FILE *file;
1171 WCHAR dash = '-';
1173 if (strncmpW(file_name,&dash,1)==0)
1174 file=stdout;
1175 else
1177 CHAR* file_nameA = GetMultiByteString(file_name);
1178 file = fopen(file_nameA, "w");
1179 if (!file) {
1180 perror("");
1181 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA);
1182 HeapFree(GetProcessHeap(), 0, file_nameA);
1183 exit(1);
1185 HeapFree(GetProcessHeap(), 0, file_nameA);
1187 if(unicode)
1189 const BYTE unicode_seq[] = {0xff,0xfe};
1190 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','\n'};
1191 fwrite(unicode_seq, sizeof(BYTE), sizeof(unicode_seq)/sizeof(unicode_seq[0]), file);
1192 fwrite(header, sizeof(WCHAR), sizeof(header)/sizeof(header[0]), file);
1193 } else
1195 fputs("REGEDIT4\n", file);
1198 return file;
1201 /******************************************************************************
1202 * Writes contents of the registry key to the specified file stream.
1204 * Parameters:
1205 * file_name - name of a file to export registry branch to.
1206 * reg_key_name - registry branch to export. The whole registry is exported if
1207 * reg_key_name is NULL or contains an empty string.
1209 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name, DWORD format)
1211 WCHAR *reg_key_name_buf;
1212 WCHAR *val_name_buf;
1213 BYTE *val_buf;
1214 WCHAR *line_buf;
1215 DWORD reg_key_name_len = KEY_MAX_LEN;
1216 DWORD val_name_len = KEY_MAX_LEN;
1217 DWORD val_size = REG_VAL_BUF_SIZE;
1218 DWORD line_buf_size = KEY_MAX_LEN + REG_VAL_BUF_SIZE;
1219 FILE *file = NULL;
1220 BOOL unicode = (format == REG_FORMAT_5);
1222 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1223 reg_key_name_len * sizeof(*reg_key_name_buf));
1224 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1225 val_name_len * sizeof(*val_name_buf));
1226 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1227 line_buf = HeapAlloc(GetProcessHeap(), 0, line_buf_size);
1228 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1230 if (reg_key_name && reg_key_name[0]) {
1231 HKEY reg_key_class;
1232 WCHAR *branch_name = NULL;
1233 HKEY key;
1235 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1236 lstrlenW(reg_key_name));
1237 lstrcpyW(reg_key_name_buf, reg_key_name);
1239 /* open the specified key */
1240 if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1241 CHAR* key_nameA = GetMultiByteString(reg_key_name);
1242 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1243 getAppName(), key_nameA);
1244 HeapFree(GetProcessHeap(), 0, key_nameA);
1245 exit(1);
1247 if (!branch_name[0]) {
1248 /* no branch - registry class is specified */
1249 file = REGPROC_open_export_file(file_name, unicode);
1250 export_hkey(file, reg_key_class,
1251 &reg_key_name_buf, &reg_key_name_len,
1252 &val_name_buf, &val_name_len,
1253 &val_buf, &val_size, &line_buf,
1254 &line_buf_size, unicode);
1255 } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1256 file = REGPROC_open_export_file(file_name, unicode);
1257 export_hkey(file, key,
1258 &reg_key_name_buf, &reg_key_name_len,
1259 &val_name_buf, &val_name_len,
1260 &val_buf, &val_size, &line_buf,
1261 &line_buf_size, unicode);
1262 RegCloseKey(key);
1263 } else {
1264 CHAR* key_nameA = GetMultiByteString(reg_key_name);
1265 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1266 getAppName(), key_nameA);
1267 HeapFree(GetProcessHeap(), 0, key_nameA);
1268 REGPROC_print_error();
1270 } else {
1271 unsigned int i;
1273 /* export all registry classes */
1274 file = REGPROC_open_export_file(file_name, unicode);
1275 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1276 /* do not export HKEY_CLASSES_ROOT */
1277 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1278 reg_class_keys[i] != HKEY_CURRENT_USER &&
1279 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1280 reg_class_keys[i] != HKEY_DYN_DATA) {
1281 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1282 export_hkey(file, reg_class_keys[i],
1283 &reg_key_name_buf, &reg_key_name_len,
1284 &val_name_buf, &val_name_len,
1285 &val_buf, &val_size, &line_buf,
1286 &line_buf_size, unicode);
1291 if (file) {
1292 fclose(file);
1294 HeapFree(GetProcessHeap(), 0, reg_key_name);
1295 HeapFree(GetProcessHeap(), 0, val_name_buf);
1296 HeapFree(GetProcessHeap(), 0, val_buf);
1297 HeapFree(GetProcessHeap(), 0, line_buf);
1298 return TRUE;
1301 /******************************************************************************
1302 * Reads contents of the specified file into the registry.
1304 BOOL import_registry_file(FILE* reg_file)
1306 if (reg_file)
1308 BYTE s[2];
1309 if (fread( s, 2, 1, reg_file) == 1)
1311 if (s[0] == 0xff && s[1] == 0xfe)
1313 processRegLinesW(reg_file);
1314 } else
1316 rewind(reg_file);
1317 processRegLinesA(reg_file);
1320 return TRUE;
1322 return FALSE;
1325 /******************************************************************************
1326 * Removes the registry key with all subkeys. Parses full key name.
1328 * Parameters:
1329 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1330 * empty, points to register key class, does not exist.
1332 void delete_registry_key(WCHAR *reg_key_name)
1334 WCHAR *key_name = NULL;
1335 HKEY key_class;
1337 if (!reg_key_name || !reg_key_name[0])
1338 return;
1340 if (!parseKeyName(reg_key_name, &key_class, &key_name)) {
1341 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1342 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1343 getAppName(), reg_key_nameA);
1344 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1345 exit(1);
1347 if (!*key_name) {
1348 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1349 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1350 getAppName(), reg_key_nameA);
1351 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1352 exit(1);
1355 RegDeleteTreeW(key_class, key_name);