push ab8f8bd6525a0f7af95fd0a2a63931cd3569f61f
[wine/hacks.git] / programs / regedit / regproc.c
blobff4918c2739eb4b11fef0b38bc7e27d271db73ca
1 /*
2 * Registry processing routines. Routines, common for registry
3 * processing frontends.
5 * Copyright 1999 Sylvain St-Germain
6 * Copyright 2002 Andriy Palamarchuk
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include <limits.h>
24 #include <stdio.h>
25 #include <windows.h>
26 #include <winnt.h>
27 #include <winreg.h>
28 #include <assert.h>
29 #include <wine/unicode.h>
30 #include "regproc.h"
32 #define REG_VAL_BUF_SIZE 4096
34 /* maximal number of characters in hexadecimal data line,
35 not including '\' character */
36 #define REG_FILE_HEX_LINE_LEN 76
38 static const CHAR *reg_class_names[] = {
39 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
40 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
43 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
45 extern const WCHAR* reg_class_namesW[];
47 static HKEY reg_class_keys[REG_CLASS_NUMBER] = {
48 HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
49 HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
52 /* return values */
53 #define NOT_ENOUGH_MEMORY 1
54 #define IO_ERROR 2
56 /* processing macros */
58 /* common check of memory allocation results */
59 #define CHECK_ENOUGH_MEMORY(p) \
60 if (!(p)) \
61 { \
62 fprintf(stderr,"%s: file %s, line %d: Not enough memory\n", \
63 getAppName(), __FILE__, __LINE__); \
64 exit(NOT_ENOUGH_MEMORY); \
67 /******************************************************************************
68 * Allocates memory and convers input from multibyte to wide chars
69 * Returned string must be freed by the caller
71 WCHAR* GetWideString(const char* strA)
73 if(strA)
75 WCHAR* strW = NULL;
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 convers input from multibyte to wide chars
88 * Returned string must be freed by the caller
90 WCHAR* GetWideStringN(const char* strA, int chars, DWORD *len)
92 if(strA)
94 WCHAR* strW = NULL;
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 convers 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 = NULL;
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 convers input from wide chars to multibyte
127 * Returned string must be freed by the caller
129 char* GetMultiByteStringN(const WCHAR* strW, int chars, DWORD* len)
131 if(strW)
133 char* strA = NULL;
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 fprintf(stderr,"%s: ERROR, invalid hex value\n", getAppName());
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 char* strA = GetMultiByteString(s);
184 fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
185 getAppName(), strA);
186 HeapFree(GetProcessHeap(), 0, data);
187 HeapFree(GetProcessHeap(), 0, strA);
188 return NULL;
190 *d++ =(BYTE)wc;
191 (*size)++;
192 if (*end) end++;
193 s = end;
196 return data;
199 /******************************************************************************
200 * This function returns the HKEY associated with the data type encoded in the
201 * value. It modifies the input parameter (key value) in order to skip this
202 * "now useless" data type information.
204 * Note: Updated based on the algorithm used in 'server/registry.c'
206 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
208 struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
210 static const WCHAR quote[] = {'"'};
211 static const WCHAR str[] = {'s','t','r',':','"'};
212 static const WCHAR str2[] = {'s','t','r','(','2',')',':','"'};
213 static const WCHAR hex[] = {'h','e','x',':'};
214 static const WCHAR dword[] = {'d','w','o','r','d',':'};
215 static const WCHAR hexp[] = {'h','e','x','('};
217 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
218 { quote, 1, REG_SZ, REG_SZ },
219 { str, 5, REG_SZ, REG_SZ },
220 { str2, 8, REG_EXPAND_SZ, REG_SZ },
221 { hex, 4, REG_BINARY, REG_BINARY },
222 { dword, 6, REG_DWORD, REG_DWORD },
223 { hexp, 4, -1, REG_BINARY },
224 { NULL, 0, 0, 0 }
227 const struct data_type *ptr;
228 int type;
230 for (ptr = data_types; ptr->tag; ptr++) {
231 if (strncmpW( ptr->tag, *lpValue, ptr->len ))
232 continue;
234 /* Found! */
235 *parse_type = ptr->parse_type;
236 type=ptr->type;
237 *lpValue+=ptr->len;
238 if (type == -1) {
239 WCHAR* end;
241 /* "hex(xx):" is special */
242 type = (int)strtoulW( *lpValue , &end, 16 );
243 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
244 type=REG_NONE;
245 } else {
246 *lpValue = end + 2;
249 return type;
251 *parse_type=REG_NONE;
252 return REG_NONE;
255 /******************************************************************************
256 * Replaces escape sequences with the characters.
258 static void REGPROC_unescape_string(WCHAR* str)
260 int str_idx = 0; /* current character under analysis */
261 int val_idx = 0; /* the last character of the unescaped string */
262 int len = lstrlenW(str);
263 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
264 if (str[str_idx] == '\\') {
265 str_idx++;
266 switch (str[str_idx]) {
267 case 'n':
268 str[val_idx] = '\n';
269 break;
270 case '\\':
271 case '"':
272 str[val_idx] = str[str_idx];
273 break;
274 default:
275 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
276 str[str_idx]);
277 str[val_idx] = str[str_idx];
278 break;
280 } else {
281 str[val_idx] = str[str_idx];
284 str[val_idx] = '\0';
287 static BOOL parseKeyName(LPWSTR lpKeyName, HKEY *hKey, LPWSTR *lpKeyPath)
289 WCHAR* lpSlash = NULL;
290 unsigned int i, len;
292 if (lpKeyName == NULL)
293 return FALSE;
295 for(i = 0; *(lpKeyName+i) != 0; i++)
297 if(*(lpKeyName+i) == '\\')
299 lpSlash = lpKeyName+i;
300 break;
304 if (lpSlash)
306 len = lpSlash-lpKeyName;
308 else
310 len = lstrlenW(lpKeyName);
311 lpSlash = lpKeyName+len;
313 *hKey = NULL;
315 for (i = 0; i < REG_CLASS_NUMBER; i++) {
316 if (CompareStringW(LOCALE_USER_DEFAULT, 0, lpKeyName, len, reg_class_namesW[i], len) == CSTR_EQUAL &&
317 len == lstrlenW(reg_class_namesW[i])) {
318 *hKey = reg_class_keys[i];
319 break;
323 if (*hKey == NULL)
324 return FALSE;
327 if (*lpSlash != '\0')
328 lpSlash++;
329 *lpKeyPath = lpSlash;
330 return TRUE;
333 /* Globals used by the setValue() & co */
334 static LPSTR currentKeyName;
335 static HKEY currentKeyHandle = NULL;
337 /******************************************************************************
338 * Sets the value with name val_name to the data in val_data for the currently
339 * opened key.
341 * Parameters:
342 * val_name - name of the registry value
343 * val_data - registry value data
345 static LONG setValue(WCHAR* val_name, WCHAR* val_data, BOOL is_unicode)
347 LONG res;
348 DWORD dwDataType, dwParseType;
349 LPBYTE lpbData;
350 DWORD dwData, dwLen;
351 WCHAR del[] = {'-',0};
353 if ( (val_name == NULL) || (val_data == NULL) )
354 return ERROR_INVALID_PARAMETER;
356 if (lstrcmpW(val_data, del) == 0)
358 res=RegDeleteValueW(currentKeyHandle,val_name);
359 return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
362 /* Get the data type stored into the value field */
363 dwDataType = getDataType(&val_data, &dwParseType);
365 if (dwParseType == REG_SZ) /* no conversion for string */
367 REGPROC_unescape_string(val_data);
368 /* Compute dwLen after REGPROC_unescape_string because it may
369 * have changed the string length and we don't want to store
370 * the extra garbage in the registry.
372 dwLen = lstrlenW(val_data);
373 if (dwLen>0 && val_data[dwLen-1]=='"')
375 dwLen--;
376 val_data[dwLen]='\0';
378 lpbData = (BYTE*) val_data;
379 dwLen++; /* include terminating null */
380 dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
382 else if (dwParseType == REG_DWORD) /* Convert the dword types */
384 if (!convertHexToDWord(val_data, &dwData))
385 return ERROR_INVALID_DATA;
386 lpbData = (BYTE*)&dwData;
387 dwLen = sizeof(dwData);
389 else if (dwParseType == REG_BINARY) /* Convert the binary data */
391 lpbData = convertHexCSVToHex(val_data, &dwLen);
392 if (!lpbData)
393 return ERROR_INVALID_DATA;
395 if(dwDataType == REG_MULTI_SZ && !is_unicode)
397 LPBYTE tmp = lpbData;
398 lpbData = (LPBYTE)GetWideStringN((char*)lpbData, dwLen, &dwLen);
399 dwLen *= sizeof(WCHAR);
400 HeapFree(GetProcessHeap(), 0, tmp);
403 else /* unknown format */
405 fprintf(stderr,"%s: ERROR, unknown data format\n", getAppName());
406 return ERROR_INVALID_DATA;
409 res = RegSetValueExW(
410 currentKeyHandle,
411 val_name,
412 0, /* Reserved */
413 dwDataType,
414 lpbData,
415 dwLen);
416 if (dwParseType == REG_BINARY)
417 HeapFree(GetProcessHeap(), 0, lpbData);
418 return res;
421 /******************************************************************************
422 * A helper function for processRegEntry() that opens the current key.
423 * That key must be closed by calling closeKey().
425 static LONG openKeyW(WCHAR* stdInput)
427 HKEY keyClass;
428 WCHAR* keyPath;
429 DWORD dwDisp;
430 LONG res;
432 /* Sanity checks */
433 if (stdInput == NULL)
434 return ERROR_INVALID_PARAMETER;
436 /* Get the registry class */
437 if (!parseKeyName(stdInput, &keyClass, &keyPath))
438 return ERROR_INVALID_PARAMETER;
440 res = RegCreateKeyExW(
441 keyClass, /* Class */
442 keyPath, /* Sub Key */
443 0, /* MUST BE 0 */
444 NULL, /* object type */
445 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
446 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
447 NULL, /* security attribute */
448 &currentKeyHandle, /* result */
449 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
450 REG_OPENED_EXISTING_KEY */
452 if (res == ERROR_SUCCESS)
453 currentKeyName = GetMultiByteString(stdInput);
454 else
455 currentKeyHandle = NULL;
457 return res;
461 /******************************************************************************
462 * Close the currently opened key.
464 static void closeKey(void)
466 if (currentKeyHandle)
468 HeapFree(GetProcessHeap(), 0, currentKeyName);
469 RegCloseKey(currentKeyHandle);
470 currentKeyHandle = NULL;
474 /******************************************************************************
475 * This function is a wrapper for the setValue function. It prepares the
476 * land and cleans the area once completed.
477 * Note: this function modifies the line parameter.
479 * line - registry file unwrapped line. Should have the registry value name and
480 * complete registry value data.
482 static void processSetValue(WCHAR* line, BOOL is_unicode)
484 WCHAR* val_name; /* registry value name */
485 WCHAR* val_data; /* registry value data */
486 int line_idx = 0; /* current character under analysis */
487 LONG res;
489 /* get value name */
490 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
491 line[line_idx] = '\0';
492 val_name = line;
493 line_idx++;
494 } else if (line[line_idx] == '\"') {
495 line_idx++;
496 val_name = line + line_idx;
497 while (TRUE) {
498 if (line[line_idx] == '\\') /* skip escaped character */
500 line_idx += 2;
501 } else {
502 if (line[line_idx] == '\"') {
503 line[line_idx] = '\0';
504 line_idx++;
505 break;
506 } else {
507 line_idx++;
511 if (line[line_idx] != '=') {
512 char* lineA;
513 line[line_idx] = '\"';
514 lineA = GetMultiByteString(line);
515 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
516 HeapFree(GetProcessHeap(), 0, lineA);
517 return;
520 } else {
521 char* lineA = GetMultiByteString(line);
522 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
523 HeapFree(GetProcessHeap(), 0, lineA);
524 return;
526 line_idx++; /* skip the '=' character */
527 val_data = line + line_idx;
529 REGPROC_unescape_string(val_name);
530 res = setValue(val_name, val_data, is_unicode);
531 if ( res != ERROR_SUCCESS )
533 char* val_nameA = GetMultiByteString(val_name);
534 char* val_dataA = GetMultiByteString(val_data);
535 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
536 getAppName(),
537 currentKeyName,
538 val_nameA,
539 val_dataA);
540 HeapFree(GetProcessHeap(), 0, val_nameA);
541 HeapFree(GetProcessHeap(), 0, val_dataA);
545 /******************************************************************************
546 * This function receives the currently read entry and performs the
547 * corresponding action.
548 * isUnicode affects parsing of REG_MULTI_SZ values
550 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
553 * We encountered the end of the file, make sure we
554 * close the opened key and exit
556 if (stdInput == NULL) {
557 closeKey();
558 return;
561 if ( stdInput[0] == '[') /* We are reading a new key */
563 WCHAR* keyEnd;
564 closeKey(); /* Close the previous key */
566 /* Get rid of the square brackets */
567 stdInput++;
568 keyEnd = strrchrW(stdInput, ']');
569 if (keyEnd)
570 *keyEnd='\0';
572 /* delete the key if we encounter '-' at the start of reg key */
573 if ( stdInput[0] == '-')
575 delete_registry_key(stdInput + 1);
576 } else if ( openKeyW(stdInput) != ERROR_SUCCESS )
578 fprintf(stderr,"%s: setValue failed to open key %s\n",
579 getAppName(), stdInput);
581 } else if( currentKeyHandle &&
582 (( stdInput[0] == '@') || /* reading a default @=data pair */
583 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
585 processSetValue(stdInput, isUnicode);
586 } else
588 /* Since we are assuming that the file format is valid we must be
589 * reading a blank line which indicates the end of this key processing
591 closeKey();
595 /******************************************************************************
596 * Processes a registry file.
597 * Correctly processes comments (in # form), line continuation.
599 * Parameters:
600 * in - input stream to read from
602 void processRegLinesA(FILE *in)
604 LPSTR line = NULL; /* line read from input stream */
605 ULONG lineSize = REG_VAL_BUF_SIZE;
607 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
608 CHECK_ENOUGH_MEMORY(line);
610 while (!feof(in)) {
611 LPSTR s; /* The pointer into line for where the current fgets should read */
612 LPSTR check;
613 WCHAR* lineW;
614 s = line;
615 for (;;) {
616 size_t size_remaining;
617 int size_to_get;
618 char *s_eol; /* various local uses */
620 /* Do we need to expand the buffer ? */
621 assert (s >= line && s <= line + lineSize);
622 size_remaining = lineSize - (s-line);
623 if (size_remaining < 2) /* room for 1 character and the \0 */
625 char *new_buffer;
626 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
627 if (new_size > lineSize) /* no arithmetic overflow */
628 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
629 else
630 new_buffer = NULL;
631 CHECK_ENOUGH_MEMORY(new_buffer);
632 line = new_buffer;
633 s = line + lineSize - size_remaining;
634 lineSize = new_size;
635 size_remaining = lineSize - (s-line);
638 /* Get as much as possible into the buffer, terminated either by
639 * eof, error, eol or getting the maximum amount. Abort on error.
641 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
643 check = fgets (s, size_to_get, in);
645 if (check == NULL) {
646 if (ferror(in)) {
647 perror ("While reading input");
648 exit (IO_ERROR);
649 } else {
650 assert (feof(in));
651 *s = '\0';
652 /* It is not clear to me from the definition that the
653 * contents of the buffer are well defined on detecting
654 * an eof without managing to read anything.
659 /* If we didn't read the eol nor the eof go around for the rest */
660 s_eol = strchr (s, '\n');
661 if (!feof (in) && !s_eol) {
662 s = strchr (s, '\0');
663 /* It should be s + size_to_get - 1 but this is safer */
664 continue;
667 /* If it is a comment line then discard it and go around again */
668 if (line [0] == '#') {
669 s = line;
670 continue;
673 /* Remove any line feed. Leave s_eol on the \0 */
674 if (s_eol) {
675 *s_eol = '\0';
676 if (s_eol > line && *(s_eol-1) == '\r')
677 *--s_eol = '\0';
678 } else
679 s_eol = strchr (s, '\0');
681 /* If there is a concatenating \\ then go around again */
682 if (s_eol > line && *(s_eol-1) == '\\') {
683 int c;
684 s = s_eol-1;
688 c = fgetc(in);
689 } while(c == ' ' || c == '\t');
691 if(c == EOF)
693 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
694 getAppName());
696 else
698 *s = c;
699 s++;
701 continue;
704 lineW = GetWideString(line);
706 break; /* That is the full virtual line */
709 processRegEntry(lineW, FALSE);
710 HeapFree(GetProcessHeap(), 0, lineW);
712 processRegEntry(NULL, FALSE);
714 HeapFree(GetProcessHeap(), 0, line);
717 void processRegLinesW(FILE *in)
719 WCHAR* buf = NULL; /* line read from input stream */
720 ULONG lineSize = REG_VAL_BUF_SIZE;
721 size_t CharsInBuf = -1;
723 WCHAR* s; /* The pointer into line for where the current fgets should read */
725 buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
726 CHECK_ENOUGH_MEMORY(buf);
728 s = buf;
730 while(!feof(in)) {
731 size_t size_remaining;
732 int size_to_get;
733 WCHAR *s_eol = NULL; /* various local uses */
735 /* Do we need to expand the buffer ? */
736 assert (s >= buf && s <= buf + lineSize);
737 size_remaining = lineSize - (s-buf);
738 if (size_remaining < 2) /* room for 1 character and the \0 */
740 WCHAR *new_buffer;
741 size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
742 if (new_size > lineSize) /* no arithmetic overflow */
743 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
744 else
745 new_buffer = NULL;
746 CHECK_ENOUGH_MEMORY(new_buffer);
747 buf = new_buffer;
748 s = buf + lineSize - size_remaining;
749 lineSize = new_size;
750 size_remaining = lineSize - (s-buf);
753 /* Get as much as possible into the buffer, terminated either by
754 * eof, error or getting the maximum amount. Abort on error.
756 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
758 CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
759 s[CharsInBuf] = 0;
761 if (CharsInBuf == 0) {
762 if (ferror(in)) {
763 perror ("While reading input");
764 exit (IO_ERROR);
765 } else {
766 assert (feof(in));
767 *s = '\0';
768 /* It is not clear to me from the definition that the
769 * contents of the buffer are well defined on detecting
770 * an eof without managing to read anything.
775 /* If we didn't read the eol nor the eof go around for the rest */
776 while(1)
778 s_eol = strchrW(s, '\n');
780 if(!s_eol)
781 break;
783 /* If it is a comment line then discard it and go around again */
784 if (*s == '#') {
785 s = s_eol + 1;
786 continue;
789 /* If there is a concatenating \\ then go around again */
790 if ((*(s_eol-1) == '\\') ||
791 (*(s_eol-1) == '\r' && *(s_eol-2) == '\\')) {
792 WCHAR* NextLine = s_eol;
794 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
795 NextLine++;
797 NextLine++;
799 if(*(s_eol-1) == '\r')
800 s_eol--;
802 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - buf) + 1)*sizeof(WCHAR));
803 CharsInBuf -= NextLine - s_eol + 1;
804 s_eol = 0;
805 continue;
808 /* Remove any line feed. Leave s_eol on the \0 */
809 if (s_eol) {
810 *s_eol = '\0';
811 if (s_eol > buf && *(s_eol-1) == '\r')
812 *(s_eol-1) = '\0';
815 if(!s_eol)
816 break;
818 processRegEntry(s, TRUE);
819 s = s_eol + 1;
820 s_eol = 0;
821 continue; /* That is the full virtual line */
825 processRegEntry(NULL, TRUE);
827 HeapFree(GetProcessHeap(), 0, buf);
830 /****************************************************************************
831 * REGPROC_print_error
833 * Print the message for GetLastError
836 static void REGPROC_print_error(void)
838 LPVOID lpMsgBuf;
839 DWORD error_code;
840 int status;
842 error_code = GetLastError ();
843 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
844 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
845 if (!status) {
846 fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
847 getAppName(), error_code, GetLastError());
848 exit(1);
850 puts(lpMsgBuf);
851 LocalFree((HLOCAL)lpMsgBuf);
852 exit(1);
855 /******************************************************************************
856 * Checks whether the buffer has enough room for the string or required size.
857 * Resizes the buffer if necessary.
859 * Parameters:
860 * buffer - pointer to a buffer for string
861 * len - current length of the buffer in characters.
862 * required_len - length of the string to place to the buffer in characters.
863 * The length does not include the terminating null character.
865 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
867 required_len++;
868 if (required_len > *len) {
869 *len = required_len;
870 if (!*buffer)
871 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
872 else
873 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
874 CHECK_ENOUGH_MEMORY(*buffer);
878 /******************************************************************************
879 * Prints string str to file
881 static void REGPROC_export_string(FILE *file, WCHAR *str)
883 CHAR* strA = GetMultiByteString(str);
884 size_t len = strlen(strA);
885 size_t i;
887 /* escaping characters */
888 for (i = 0; i < len; i++) {
889 CHAR c = str[i];
890 switch (c) {
891 case '\\':
892 fputs("\\\\", file);
893 break;
894 case '\"':
895 fputs("\\\"", file);
896 break;
897 case '\n':
898 fputs("\\\n", file);
899 break;
900 default:
901 fputc(c, file);
902 break;
905 HeapFree(GetProcessHeap(), 0, strA);
908 /******************************************************************************
909 * Writes contents of the registry key to the specified file stream.
911 * Parameters:
912 * file - writable file stream to export registry branch to.
913 * key - registry branch to export.
914 * reg_key_name_buf - name of the key with registry class.
915 * Is resized if necessary.
916 * reg_key_name_len - length of the buffer for the registry class in characters.
917 * val_name_buf - buffer for storing value name.
918 * Is resized if necessary.
919 * val_name_len - length of the buffer for storing value names in characters.
920 * val_buf - buffer for storing values while extracting.
921 * Is resized if necessary.
922 * val_size - size of the buffer for storing values in bytes.
924 static void export_hkey(FILE *file, HKEY key,
925 WCHAR **reg_key_name_buf, DWORD *reg_key_name_len,
926 WCHAR **val_name_buf, DWORD *val_name_len,
927 BYTE **val_buf, DWORD *val_size)
929 DWORD max_sub_key_len;
930 DWORD max_val_name_len;
931 DWORD max_val_size;
932 DWORD curr_len;
933 DWORD i;
934 BOOL more_data;
935 LONG ret;
936 CHAR* bufA;
938 /* get size information and resize the buffers if necessary */
939 if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
940 &max_sub_key_len, NULL,
941 NULL, &max_val_name_len, &max_val_size, NULL, NULL
942 ) != ERROR_SUCCESS) {
943 REGPROC_print_error();
945 curr_len = strlenW(*reg_key_name_buf);
946 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
947 max_sub_key_len + curr_len + 1);
948 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
949 max_val_name_len);
950 if (max_val_size > *val_size) {
951 *val_size = max_val_size;
952 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
953 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
954 CHECK_ENOUGH_MEMORY(val_buf);
957 /* output data for the current key */
958 fputs("\n[", file);
959 bufA = GetMultiByteString(*reg_key_name_buf);
960 fputs(bufA, file);
961 HeapFree(GetProcessHeap(), 0, bufA);
962 fputs("]\n", file);
963 /* print all the values */
964 i = 0;
965 more_data = TRUE;
966 while(more_data) {
967 DWORD value_type;
968 DWORD val_name_len1 = *val_name_len;
969 DWORD val_size1 = *val_size;
970 ret = RegEnumValueW(key, i, *val_name_buf, &val_name_len1, NULL,
971 &value_type, *val_buf, &val_size1);
972 if (ret != ERROR_SUCCESS) {
973 more_data = FALSE;
974 if (ret != ERROR_NO_MORE_ITEMS) {
975 REGPROC_print_error();
977 } else {
978 i++;
980 if ((*val_name_buf)[0]) {
981 fputs("\"", file);
982 REGPROC_export_string(file, *val_name_buf);
983 fputs("\"=", file);
984 } else {
985 fputs("@=", file);
988 switch (value_type) {
989 case REG_SZ:
990 case REG_EXPAND_SZ:
991 fputs("\"", file);
992 if (val_size1) REGPROC_export_string(file, (WCHAR*) *val_buf);
993 fputs("\"\n", file);
994 break;
996 case REG_DWORD:
997 fprintf(file, "dword:%08x\n", *((DWORD *)*val_buf));
998 break;
1000 default:
1001 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
1002 "treat as binary\n",
1003 getAppName(), value_type);
1004 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
1005 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
1006 /* falls through */
1007 case REG_MULTI_SZ:
1008 /* falls through */
1009 case REG_BINARY: {
1010 DWORD i1;
1011 const WCHAR *hex_prefix;
1012 WCHAR buf[20];
1013 int cur_pos;
1014 const WCHAR hex[] = {'h','e','x',':',0};
1015 const WCHAR delim[] = {'"','"','=',0};
1016 CHAR* hex_prefixA;
1017 BYTE* val_buf1 = *val_buf;
1018 DWORD val_buf1_size = val_size1;
1020 if (value_type == REG_BINARY) {
1021 hex_prefix = hex;
1022 } else {
1023 const WCHAR hex_format[] = {'h','e','x','(','%','d',')',':',0};
1024 hex_prefix = buf;
1025 wsprintfW(buf, hex_format, value_type);
1026 if(value_type == REG_MULTI_SZ)
1027 val_buf1 = (BYTE*)GetMultiByteStringN((WCHAR*)*val_buf, val_size1 / sizeof(WCHAR), &val_buf1_size);
1030 /* position of where the next character will be printed */
1031 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1032 cur_pos = lstrlenW(delim) + lstrlenW(hex) +
1033 lstrlenW(*val_name_buf);
1035 hex_prefixA = GetMultiByteString(hex_prefix);
1036 fputs(hex_prefixA, file);
1037 HeapFree(GetProcessHeap(), 0, hex_prefixA);
1038 for (i1 = 0; i1 < val_buf1_size; i1++) {
1039 fprintf(file, "%02x", (unsigned int)(val_buf1)[i1]);
1040 if (i1 + 1 < val_buf1_size) {
1041 fputs(",", file);
1043 cur_pos += 3;
1045 /* wrap the line */
1046 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1047 fputs("\\\n ", file);
1048 cur_pos = 2;
1051 if(value_type == REG_MULTI_SZ)
1052 HeapFree(GetProcessHeap(), 0, val_buf1);
1053 fputs("\n", file);
1054 break;
1060 i = 0;
1061 more_data = TRUE;
1062 (*reg_key_name_buf)[curr_len] = '\\';
1063 while(more_data) {
1064 DWORD buf_len = *reg_key_name_len - curr_len;
1066 ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1067 NULL, NULL, NULL, NULL);
1068 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1069 more_data = FALSE;
1070 if (ret != ERROR_NO_MORE_ITEMS) {
1071 REGPROC_print_error();
1073 } else {
1074 HKEY subkey;
1076 i++;
1077 if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1078 &subkey) == ERROR_SUCCESS) {
1079 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1080 val_name_buf, val_name_len, val_buf, val_size);
1081 RegCloseKey(subkey);
1082 } else {
1083 REGPROC_print_error();
1087 (*reg_key_name_buf)[curr_len] = '\0';
1090 /******************************************************************************
1091 * Open file for export.
1093 static FILE *REGPROC_open_export_file(WCHAR *file_name)
1095 FILE *file;
1096 WCHAR dash = '-';
1098 if (strncmpW(file_name,&dash,1)==0)
1099 file=stdout;
1100 else
1102 CHAR* file_nameA = GetMultiByteString(file_name);
1103 file = fopen(file_nameA, "w");
1104 if (!file) {
1105 perror("");
1106 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA);
1107 HeapFree(GetProcessHeap(), 0, file_nameA);
1108 exit(1);
1110 HeapFree(GetProcessHeap(), 0, file_nameA);
1112 fputs("REGEDIT4\n", file);
1113 return file;
1116 /******************************************************************************
1117 * Writes contents of the registry key to the specified file stream.
1119 * Parameters:
1120 * file_name - name of a file to export registry branch to.
1121 * reg_key_name - registry branch to export. The whole registry is exported if
1122 * reg_key_name is NULL or contains an empty string.
1124 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name)
1126 WCHAR *reg_key_name_buf;
1127 WCHAR *val_name_buf;
1128 BYTE *val_buf;
1129 DWORD reg_key_name_len = KEY_MAX_LEN;
1130 DWORD val_name_len = KEY_MAX_LEN;
1131 DWORD val_size = REG_VAL_BUF_SIZE;
1132 FILE *file = NULL;
1134 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1135 reg_key_name_len * sizeof(*reg_key_name_buf));
1136 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1137 val_name_len * sizeof(*val_name_buf));
1138 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1139 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1141 if (reg_key_name && reg_key_name[0]) {
1142 HKEY reg_key_class;
1143 WCHAR *branch_name = NULL;
1144 HKEY key;
1146 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1147 lstrlenW(reg_key_name));
1148 lstrcpyW(reg_key_name_buf, reg_key_name);
1150 /* open the specified key */
1151 if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1152 CHAR* key_nameA = GetMultiByteString(reg_key_name);
1153 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1154 getAppName(), key_nameA);
1155 HeapFree(GetProcessHeap(), 0, key_nameA);
1156 exit(1);
1158 if (!branch_name[0]) {
1159 /* no branch - registry class is specified */
1160 file = REGPROC_open_export_file(file_name);
1161 export_hkey(file, reg_key_class,
1162 &reg_key_name_buf, &reg_key_name_len,
1163 &val_name_buf, &val_name_len,
1164 &val_buf, &val_size);
1165 } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1166 file = REGPROC_open_export_file(file_name);
1167 export_hkey(file, key,
1168 &reg_key_name_buf, &reg_key_name_len,
1169 &val_name_buf, &val_name_len,
1170 &val_buf, &val_size);
1171 RegCloseKey(key);
1172 } else {
1173 CHAR* key_nameA = GetMultiByteString(reg_key_name);
1174 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1175 getAppName(), key_nameA);
1176 HeapFree(GetProcessHeap(), 0, key_nameA);
1177 REGPROC_print_error();
1179 } else {
1180 unsigned int i;
1182 /* export all registry classes */
1183 file = REGPROC_open_export_file(file_name);
1184 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1185 /* do not export HKEY_CLASSES_ROOT */
1186 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1187 reg_class_keys[i] != HKEY_CURRENT_USER &&
1188 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1189 reg_class_keys[i] != HKEY_DYN_DATA) {
1190 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1191 export_hkey(file, reg_class_keys[i],
1192 &reg_key_name_buf, &reg_key_name_len,
1193 &val_name_buf, &val_name_len,
1194 &val_buf, &val_size);
1199 if (file) {
1200 fclose(file);
1202 HeapFree(GetProcessHeap(), 0, reg_key_name);
1203 HeapFree(GetProcessHeap(), 0, val_name_buf);
1204 HeapFree(GetProcessHeap(), 0, val_buf);
1205 return TRUE;
1208 /******************************************************************************
1209 * Reads contents of the specified file into the registry.
1211 BOOL import_registry_file(FILE* reg_file)
1213 if (reg_file)
1215 BYTE s[2];
1216 if (fread( s, 2, 1, reg_file) == 1)
1218 if (s[0] == 0xff && s[1] == 0xfe)
1220 processRegLinesW(reg_file);
1221 } else
1223 rewind(reg_file);
1224 processRegLinesA(reg_file);
1227 return TRUE;
1229 return FALSE;
1232 /******************************************************************************
1233 * Removes the registry key with all subkeys. Parses full key name.
1235 * Parameters:
1236 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1237 * empty, points to register key class, does not exist.
1239 void delete_registry_key(WCHAR *reg_key_name)
1241 WCHAR *key_name = NULL;
1242 HKEY key_class;
1244 if (!reg_key_name || !reg_key_name[0])
1245 return;
1247 if (!parseKeyName(reg_key_name, &key_class, &key_name)) {
1248 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1249 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1250 getAppName(), reg_key_nameA);
1251 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1252 exit(1);
1254 if (!*key_name) {
1255 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1256 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1257 getAppName(), reg_key_nameA);
1258 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1259 exit(1);
1262 RegDeleteTreeW(key_class, key_name);