ddraw/tests: Use FAILED instead of !SUCCEEDED.
[wine/multimedia.git] / programs / regedit / regproc.c
blobc3825bd36a9faa58e1eb305b070d027fba040faa
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 while ( isspaceW(line[line_idx]) ) line_idx++;
492 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
493 line[line_idx] = '\0';
494 val_name = line;
495 line_idx++;
496 } else if (line[line_idx] == '\"') {
497 line_idx++;
498 val_name = line + line_idx;
499 while (TRUE) {
500 if (line[line_idx] == '\\') /* skip escaped character */
502 line_idx += 2;
503 } else {
504 if (line[line_idx] == '\"') {
505 line[line_idx] = '\0';
506 line_idx++;
507 break;
508 } else {
509 line_idx++;
513 while ( isspaceW(line[line_idx]) ) line_idx++;
514 if (line[line_idx] != '=') {
515 char* lineA;
516 line[line_idx] = '\"';
517 lineA = GetMultiByteString(line);
518 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
519 HeapFree(GetProcessHeap(), 0, lineA);
520 return;
523 } else {
524 char* lineA = GetMultiByteString(line);
525 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
526 HeapFree(GetProcessHeap(), 0, lineA);
527 return;
529 line_idx++; /* skip the '=' character */
531 while ( isspaceW(line[line_idx]) ) line_idx++;
532 val_data = line + line_idx;
533 /* trim trailing blanks */
534 line_idx = strlenW(val_data);
535 while (line_idx > 0 && isspaceW(val_data[line_idx-1])) line_idx--;
536 val_data[line_idx] = '\0';
538 REGPROC_unescape_string(val_name);
539 res = setValue(val_name, val_data, is_unicode);
540 if ( res != ERROR_SUCCESS )
542 char* val_nameA = GetMultiByteString(val_name);
543 char* val_dataA = GetMultiByteString(val_data);
544 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
545 getAppName(),
546 currentKeyName,
547 val_nameA,
548 val_dataA);
549 HeapFree(GetProcessHeap(), 0, val_nameA);
550 HeapFree(GetProcessHeap(), 0, val_dataA);
554 /******************************************************************************
555 * This function receives the currently read entry and performs the
556 * corresponding action.
557 * isUnicode affects parsing of REG_MULTI_SZ values
559 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
562 * We encountered the end of the file, make sure we
563 * close the opened key and exit
565 if (stdInput == NULL) {
566 closeKey();
567 return;
570 if ( stdInput[0] == '[') /* We are reading a new key */
572 WCHAR* keyEnd;
573 closeKey(); /* Close the previous key */
575 /* Get rid of the square brackets */
576 stdInput++;
577 keyEnd = strrchrW(stdInput, ']');
578 if (keyEnd)
579 *keyEnd='\0';
581 /* delete the key if we encounter '-' at the start of reg key */
582 if ( stdInput[0] == '-')
584 delete_registry_key(stdInput + 1);
585 } else if ( openKeyW(stdInput) != ERROR_SUCCESS )
587 char* stdInputA = GetMultiByteString(stdInput);
588 fprintf(stderr,"%s: setValue failed to open key %s\n",
589 getAppName(), stdInputA);
590 HeapFree(GetProcessHeap(), 0, stdInputA);
592 } else if( currentKeyHandle &&
593 (( stdInput[0] == '@') || /* reading a default @=data pair */
594 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
596 processSetValue(stdInput, isUnicode);
597 } else
599 /* Since we are assuming that the file format is valid we must be
600 * reading a blank line which indicates the end of this key processing
602 closeKey();
606 /******************************************************************************
607 * Processes a registry file.
608 * Correctly processes comments (in # form), line continuation.
610 * Parameters:
611 * in - input stream to read from
613 void processRegLinesA(FILE *in)
615 LPSTR line = NULL; /* line read from input stream */
616 ULONG lineSize = REG_VAL_BUF_SIZE;
618 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
619 CHECK_ENOUGH_MEMORY(line);
621 while (!feof(in)) {
622 LPSTR s; /* The pointer into line for where the current fgets should read */
623 LPSTR check;
624 WCHAR* lineW;
625 s = line;
626 for (;;) {
627 size_t size_remaining;
628 int size_to_get;
629 char *s_eol; /* various local uses */
631 /* Do we need to expand the buffer ? */
632 assert (s >= line && s <= line + lineSize);
633 size_remaining = lineSize - (s-line);
634 if (size_remaining < 2) /* room for 1 character and the \0 */
636 char *new_buffer;
637 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
638 if (new_size > lineSize) /* no arithmetic overflow */
639 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
640 else
641 new_buffer = NULL;
642 CHECK_ENOUGH_MEMORY(new_buffer);
643 line = new_buffer;
644 s = line + lineSize - size_remaining;
645 lineSize = new_size;
646 size_remaining = lineSize - (s-line);
649 /* Get as much as possible into the buffer, terminated either by
650 * eof, error, eol or getting the maximum amount. Abort on error.
652 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
654 check = fgets (s, size_to_get, in);
656 if (check == NULL) {
657 if (ferror(in)) {
658 perror ("While reading input");
659 exit (IO_ERROR);
660 } else {
661 assert (feof(in));
662 *s = '\0';
663 /* It is not clear to me from the definition that the
664 * contents of the buffer are well defined on detecting
665 * an eof without managing to read anything.
670 /* If we didn't read the eol nor the eof go around for the rest */
671 s_eol = strchr (s, '\n');
672 if (!feof (in) && !s_eol) {
673 s = strchr (s, '\0');
674 /* It should be s + size_to_get - 1 but this is safer */
675 continue;
678 /* If it is a comment line then discard it and go around again */
679 if (line [0] == '#') {
680 s = line;
681 continue;
684 /* Remove any line feed. Leave s_eol on the \0 */
685 if (s_eol) {
686 *s_eol = '\0';
687 if (s_eol > line && *(s_eol-1) == '\r')
688 *--s_eol = '\0';
689 } else
690 s_eol = strchr (s, '\0');
692 /* If there is a concatenating \\ then go around again */
693 if (s_eol > line && *(s_eol-1) == '\\') {
694 int c;
695 s = s_eol-1;
699 c = fgetc(in);
700 } while(c == ' ' || c == '\t');
702 if(c == EOF)
704 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
705 getAppName());
707 else
709 *s = c;
710 s++;
712 continue;
715 lineW = GetWideString(line);
717 break; /* That is the full virtual line */
720 processRegEntry(lineW, FALSE);
721 HeapFree(GetProcessHeap(), 0, lineW);
723 processRegEntry(NULL, FALSE);
725 HeapFree(GetProcessHeap(), 0, line);
728 void processRegLinesW(FILE *in)
730 WCHAR* buf = NULL; /* line read from input stream */
731 ULONG lineSize = REG_VAL_BUF_SIZE;
732 size_t CharsInBuf = -1;
734 WCHAR* s; /* The pointer into line for where the current fgets should read */
736 buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
737 CHECK_ENOUGH_MEMORY(buf);
739 s = buf;
741 while(!feof(in)) {
742 size_t size_remaining;
743 int size_to_get;
744 WCHAR *s_eol = NULL; /* various local uses */
746 /* Do we need to expand the buffer ? */
747 assert (s >= buf && s <= buf + lineSize);
748 size_remaining = lineSize - (s-buf);
749 if (size_remaining < 2) /* room for 1 character and the \0 */
751 WCHAR *new_buffer;
752 size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
753 if (new_size > lineSize) /* no arithmetic overflow */
754 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
755 else
756 new_buffer = NULL;
757 CHECK_ENOUGH_MEMORY(new_buffer);
758 buf = new_buffer;
759 s = buf + lineSize - size_remaining;
760 lineSize = new_size;
761 size_remaining = lineSize - (s-buf);
764 /* Get as much as possible into the buffer, terminated either by
765 * eof, error or getting the maximum amount. Abort on error.
767 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
769 CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
770 s[CharsInBuf] = 0;
772 if (CharsInBuf == 0) {
773 if (ferror(in)) {
774 perror ("While reading input");
775 exit (IO_ERROR);
776 } else {
777 assert (feof(in));
778 *s = '\0';
779 /* It is not clear to me from the definition that the
780 * contents of the buffer are well defined on detecting
781 * an eof without managing to read anything.
786 /* If we didn't read the eol nor the eof go around for the rest */
787 while(1)
789 s_eol = strchrW(s, '\n');
791 if(!s_eol)
792 break;
794 /* If it is a comment line then discard it and go around again */
795 if (*s == '#') {
796 s = s_eol + 1;
797 continue;
800 /* If there is a concatenating \\ then go around again */
801 if ((*(s_eol-1) == '\\') ||
802 (*(s_eol-1) == '\r' && *(s_eol-2) == '\\')) {
803 WCHAR* NextLine = s_eol;
805 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
806 NextLine++;
808 NextLine++;
810 if(*(s_eol-1) == '\r')
811 s_eol--;
813 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - buf) + 1)*sizeof(WCHAR));
814 CharsInBuf -= NextLine - s_eol + 1;
815 s_eol = 0;
816 continue;
819 /* Remove any line feed. Leave s_eol on the \0 */
820 if (s_eol) {
821 *s_eol = '\0';
822 if (s_eol > buf && *(s_eol-1) == '\r')
823 *(s_eol-1) = '\0';
826 if(!s_eol)
827 break;
829 processRegEntry(s, TRUE);
830 s = s_eol + 1;
831 s_eol = 0;
832 continue; /* That is the full virtual line */
836 processRegEntry(NULL, TRUE);
838 HeapFree(GetProcessHeap(), 0, buf);
841 /****************************************************************************
842 * REGPROC_print_error
844 * Print the message for GetLastError
847 static void REGPROC_print_error(void)
849 LPVOID lpMsgBuf;
850 DWORD error_code;
851 int status;
853 error_code = GetLastError ();
854 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
855 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
856 if (!status) {
857 fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
858 getAppName(), error_code, GetLastError());
859 exit(1);
861 puts(lpMsgBuf);
862 LocalFree((HLOCAL)lpMsgBuf);
863 exit(1);
866 /******************************************************************************
867 * Checks whether the buffer has enough room for the string or required size.
868 * Resizes the buffer if necessary.
870 * Parameters:
871 * buffer - pointer to a buffer for string
872 * len - current length of the buffer in characters.
873 * required_len - length of the string to place to the buffer in characters.
874 * The length does not include the terminating null character.
876 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
878 required_len++;
879 if (required_len > *len) {
880 *len = required_len;
881 if (!*buffer)
882 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
883 else
884 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
885 CHECK_ENOUGH_MEMORY(*buffer);
889 /******************************************************************************
890 * Prints string str to file
892 static void REGPROC_export_string(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_size, WCHAR *str)
894 DWORD len = lstrlenW(str);
895 DWORD i;
896 DWORD extra = 0;
898 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + 10);
900 /* escaping characters */
901 for (i = 0; i < len; i++) {
902 WCHAR c = str[i];
903 switch (c) {
904 case '\\':
906 const WCHAR escape[] = {'\\','\\'};
908 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + extra + 1);
909 memcpy(*line_buf + *line_size + i + extra - 1, escape, 2 * sizeof(WCHAR));
910 extra++;
911 break;
913 case '"':
915 const WCHAR escape[] = {'\\','"'};
917 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + extra + 1);
918 memcpy(*line_buf + *line_size + i + extra - 1, escape, 2 * sizeof(WCHAR));
919 extra++;
920 break;
922 case '\n':
924 const WCHAR escape[] = {'\\','n'};
926 REGPROC_resize_char_buffer(line_buf, line_buf_size, len + *line_size + extra + 1);
927 memcpy(*line_buf + *line_size + i + extra - 1, escape, 2 * sizeof(WCHAR));
928 extra++;
929 break;
931 default:
932 memcpy(*line_buf + *line_size + i + extra - 1, &c, sizeof(WCHAR));
933 break;
936 *line_size += len + extra;
937 *(*line_buf + *line_size - 1) = 0;
940 /******************************************************************************
941 * Writes the given line to a file, in multi-byte or wide characters
943 static void REGPROC_write_line(FILE *file, const WCHAR* str, BOOL unicode)
945 if(unicode)
947 fwrite(str, sizeof(WCHAR), lstrlenW(str), file);
948 } else
950 char* strA = GetMultiByteString(str);
951 fputs(strA, file);
952 HeapFree(GetProcessHeap(), 0, strA);
956 /******************************************************************************
957 * Writes contents of the registry key to the specified file stream.
959 * Parameters:
960 * file - writable file stream to export registry branch to.
961 * key - registry branch to export.
962 * reg_key_name_buf - name of the key with registry class.
963 * Is resized if necessary.
964 * reg_key_name_len - length of the buffer for the registry class in characters.
965 * val_name_buf - buffer for storing value name.
966 * Is resized if necessary.
967 * val_name_len - length of the buffer for storing value names in characters.
968 * val_buf - buffer for storing values while extracting.
969 * Is resized if necessary.
970 * val_size - size of the buffer for storing values in bytes.
972 static void export_hkey(FILE *file, HKEY key,
973 WCHAR **reg_key_name_buf, DWORD *reg_key_name_len,
974 WCHAR **val_name_buf, DWORD *val_name_len,
975 BYTE **val_buf, DWORD *val_size,
976 WCHAR **line_buf, DWORD *line_buf_size,
977 BOOL unicode)
979 DWORD max_sub_key_len;
980 DWORD max_val_name_len;
981 DWORD max_val_size;
982 DWORD curr_len;
983 DWORD i;
984 BOOL more_data;
985 LONG ret;
986 WCHAR key_format[] = {'\n','[','%','s',']','\n',0};
987 DWORD line_pos;
989 /* get size information and resize the buffers if necessary */
990 if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
991 &max_sub_key_len, NULL,
992 NULL, &max_val_name_len, &max_val_size, NULL, NULL
993 ) != ERROR_SUCCESS) {
994 REGPROC_print_error();
996 curr_len = strlenW(*reg_key_name_buf);
997 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
998 max_sub_key_len + curr_len + 1);
999 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
1000 max_val_name_len);
1001 if (max_val_size > *val_size) {
1002 *val_size = max_val_size;
1003 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
1004 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
1005 CHECK_ENOUGH_MEMORY(val_buf);
1008 REGPROC_resize_char_buffer(line_buf, line_buf_size, lstrlenW(*reg_key_name_buf) + 4);
1009 /* output data for the current key */
1010 wsprintfW(*line_buf, key_format, *reg_key_name_buf);
1011 REGPROC_write_line(file, *line_buf, unicode);
1013 /* print all the values */
1014 i = 0;
1015 more_data = TRUE;
1016 while(more_data) {
1017 DWORD value_type;
1018 DWORD val_name_len1 = *val_name_len;
1019 DWORD val_size1 = *val_size;
1020 DWORD line_size = 0;
1021 ret = RegEnumValueW(key, i, *val_name_buf, &val_name_len1, NULL,
1022 &value_type, *val_buf, &val_size1);
1023 if (ret != ERROR_SUCCESS) {
1024 more_data = FALSE;
1025 if (ret != ERROR_NO_MORE_ITEMS) {
1026 REGPROC_print_error();
1028 } else {
1029 i++;
1031 if ((*val_name_buf)[0]) {
1032 const WCHAR val_start[] = {'"','%','s','"','=',0};
1034 line_size = 4 + lstrlenW(*val_name_buf);
1035 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1036 wsprintfW(*line_buf, val_start, *val_name_buf);
1037 line_pos = lstrlenW(*line_buf);
1038 } else {
1039 const WCHAR std_val[] = {'@','=',0};
1040 line_size = 3;
1041 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1042 lstrcpyW(*line_buf, std_val);
1043 line_pos = lstrlenW(*line_buf);
1046 switch (value_type) {
1047 case REG_SZ:
1048 case REG_EXPAND_SZ:
1050 const WCHAR start[] = {'"',0};
1051 const WCHAR end[] = {'"','\n',0};
1053 line_size += lstrlenW(start);
1054 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1055 lstrcatW(*line_buf, start);
1057 if (val_size1) REGPROC_export_string(line_buf, line_buf_size, &line_size, (WCHAR*) *val_buf);
1059 line_size += lstrlenW(end);
1060 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1061 lstrcatW(*line_buf, end);
1062 break;
1065 case REG_DWORD:
1067 WCHAR format[] = {'d','w','o','r','d',':','%','0','8','x','\n',0};
1069 line_size += 20;
1070 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1071 wsprintfW(*line_buf + line_pos, format, *((DWORD *)*val_buf));
1072 break;
1075 default:
1077 char* key_nameA = GetMultiByteString(*reg_key_name_buf);
1078 char* value_nameA = GetMultiByteString(*val_name_buf);
1079 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
1080 "treat as binary\n",
1081 getAppName(), value_type);
1082 fprintf(stderr,"key name: \"%s\"\n", key_nameA);
1083 fprintf(stderr,"value name:\"%s\"\n\n", value_nameA);
1084 HeapFree(GetProcessHeap(), 0, key_nameA);
1085 HeapFree(GetProcessHeap(), 0, value_nameA);
1087 /* falls through */
1088 case REG_MULTI_SZ:
1089 /* falls through */
1090 case REG_BINARY: {
1091 DWORD i1;
1092 const WCHAR *hex_prefix;
1093 WCHAR buf[20];
1094 int cur_pos;
1095 const WCHAR hex[] = {'h','e','x',':',0};
1096 const WCHAR delim[] = {'"','"','=',0};
1097 const WCHAR format[] = {'%','0','2','x',0};
1098 const WCHAR comma[] = {',',0};
1099 const WCHAR concat[] = {'\\','\n',' ',' ',0};
1100 const WCHAR newline[] = {'\n',0};
1101 BYTE* val_buf1 = *val_buf;
1102 DWORD val_buf1_size = val_size1;
1104 if (value_type == REG_BINARY) {
1105 hex_prefix = hex;
1106 } else {
1107 const WCHAR hex_format[] = {'h','e','x','(','%','d',')',':',0};
1108 hex_prefix = buf;
1109 wsprintfW(buf, hex_format, value_type);
1110 if(value_type == REG_MULTI_SZ && !unicode)
1111 val_buf1 = (BYTE*)GetMultiByteStringN((WCHAR*)*val_buf, val_size1 / sizeof(WCHAR), &val_buf1_size);
1114 /* position of where the next character will be printed */
1115 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1116 cur_pos = lstrlenW(delim) + lstrlenW(hex) +
1117 lstrlenW(*val_name_buf);
1119 line_size += lstrlenW(hex_prefix);
1120 line_size += val_buf1_size * 3 + lstrlenW(concat) * ((int)((float)val_buf1_size * 3.0 / (float)REG_FILE_HEX_LINE_LEN) + 1 ) + 1;
1121 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_size);
1122 lstrcatW(*line_buf, hex_prefix);
1123 line_pos += lstrlenW(hex_prefix);
1124 for (i1 = 0; i1 < val_buf1_size; i1++) {
1125 wsprintfW(*line_buf + line_pos, format, (unsigned int)(val_buf1)[i1]);
1126 line_pos += 2;
1127 if (i1 + 1 < val_buf1_size) {
1128 lstrcpyW(*line_buf + line_pos, comma);
1129 line_pos++;
1131 cur_pos += 3;
1133 /* wrap the line */
1134 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1135 lstrcpyW(*line_buf + line_pos, concat);
1136 line_pos += lstrlenW(concat);
1137 cur_pos = 2;
1140 if(value_type == REG_MULTI_SZ && !unicode)
1141 HeapFree(GetProcessHeap(), 0, val_buf1);
1142 lstrcpyW(*line_buf + line_pos, newline);
1143 break;
1146 REGPROC_write_line(file, *line_buf, unicode);
1150 i = 0;
1151 more_data = TRUE;
1152 (*reg_key_name_buf)[curr_len] = '\\';
1153 while(more_data) {
1154 DWORD buf_len = *reg_key_name_len - curr_len;
1156 ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1157 NULL, NULL, NULL, NULL);
1158 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1159 more_data = FALSE;
1160 if (ret != ERROR_NO_MORE_ITEMS) {
1161 REGPROC_print_error();
1163 } else {
1164 HKEY subkey;
1166 i++;
1167 if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1168 &subkey) == ERROR_SUCCESS) {
1169 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1170 val_name_buf, val_name_len, val_buf, val_size,
1171 line_buf, line_buf_size, unicode);
1172 RegCloseKey(subkey);
1173 } else {
1174 REGPROC_print_error();
1178 (*reg_key_name_buf)[curr_len] = '\0';
1181 /******************************************************************************
1182 * Open file for export.
1184 static FILE *REGPROC_open_export_file(WCHAR *file_name, BOOL unicode)
1186 FILE *file;
1187 WCHAR dash = '-';
1189 if (strncmpW(file_name,&dash,1)==0)
1190 file=stdout;
1191 else
1193 CHAR* file_nameA = GetMultiByteString(file_name);
1194 file = fopen(file_nameA, "w");
1195 if (!file) {
1196 perror("");
1197 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA);
1198 HeapFree(GetProcessHeap(), 0, file_nameA);
1199 exit(1);
1201 HeapFree(GetProcessHeap(), 0, file_nameA);
1203 if(unicode)
1205 const BYTE unicode_seq[] = {0xff,0xfe};
1206 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'};
1207 fwrite(unicode_seq, sizeof(BYTE), sizeof(unicode_seq)/sizeof(unicode_seq[0]), file);
1208 fwrite(header, sizeof(WCHAR), sizeof(header)/sizeof(header[0]), file);
1209 } else
1211 fputs("REGEDIT4\n", file);
1214 return file;
1217 /******************************************************************************
1218 * Writes contents of the registry key to the specified file stream.
1220 * Parameters:
1221 * file_name - name of a file to export registry branch to.
1222 * reg_key_name - registry branch to export. The whole registry is exported if
1223 * reg_key_name is NULL or contains an empty string.
1225 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name, DWORD format)
1227 WCHAR *reg_key_name_buf;
1228 WCHAR *val_name_buf;
1229 BYTE *val_buf;
1230 WCHAR *line_buf;
1231 DWORD reg_key_name_len = KEY_MAX_LEN;
1232 DWORD val_name_len = KEY_MAX_LEN;
1233 DWORD val_size = REG_VAL_BUF_SIZE;
1234 DWORD line_buf_size = KEY_MAX_LEN + REG_VAL_BUF_SIZE;
1235 FILE *file = NULL;
1236 BOOL unicode = (format == REG_FORMAT_5);
1238 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1239 reg_key_name_len * sizeof(*reg_key_name_buf));
1240 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1241 val_name_len * sizeof(*val_name_buf));
1242 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1243 line_buf = HeapAlloc(GetProcessHeap(), 0, line_buf_size);
1244 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1246 if (reg_key_name && reg_key_name[0]) {
1247 HKEY reg_key_class;
1248 WCHAR *branch_name = NULL;
1249 HKEY key;
1251 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1252 lstrlenW(reg_key_name));
1253 lstrcpyW(reg_key_name_buf, reg_key_name);
1255 /* open the specified key */
1256 if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1257 CHAR* key_nameA = GetMultiByteString(reg_key_name);
1258 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1259 getAppName(), key_nameA);
1260 HeapFree(GetProcessHeap(), 0, key_nameA);
1261 exit(1);
1263 if (!branch_name[0]) {
1264 /* no branch - registry class is specified */
1265 file = REGPROC_open_export_file(file_name, unicode);
1266 export_hkey(file, reg_key_class,
1267 &reg_key_name_buf, &reg_key_name_len,
1268 &val_name_buf, &val_name_len,
1269 &val_buf, &val_size, &line_buf,
1270 &line_buf_size, unicode);
1271 } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1272 file = REGPROC_open_export_file(file_name, unicode);
1273 export_hkey(file, key,
1274 &reg_key_name_buf, &reg_key_name_len,
1275 &val_name_buf, &val_name_len,
1276 &val_buf, &val_size, &line_buf,
1277 &line_buf_size, unicode);
1278 RegCloseKey(key);
1279 } else {
1280 CHAR* key_nameA = GetMultiByteString(reg_key_name);
1281 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1282 getAppName(), key_nameA);
1283 HeapFree(GetProcessHeap(), 0, key_nameA);
1284 REGPROC_print_error();
1286 } else {
1287 unsigned int i;
1289 /* export all registry classes */
1290 file = REGPROC_open_export_file(file_name, unicode);
1291 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1292 /* do not export HKEY_CLASSES_ROOT */
1293 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1294 reg_class_keys[i] != HKEY_CURRENT_USER &&
1295 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1296 reg_class_keys[i] != HKEY_DYN_DATA) {
1297 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1298 export_hkey(file, reg_class_keys[i],
1299 &reg_key_name_buf, &reg_key_name_len,
1300 &val_name_buf, &val_name_len,
1301 &val_buf, &val_size, &line_buf,
1302 &line_buf_size, unicode);
1307 if (file) {
1308 fclose(file);
1310 HeapFree(GetProcessHeap(), 0, reg_key_name);
1311 HeapFree(GetProcessHeap(), 0, val_name_buf);
1312 HeapFree(GetProcessHeap(), 0, val_buf);
1313 HeapFree(GetProcessHeap(), 0, line_buf);
1314 return TRUE;
1317 /******************************************************************************
1318 * Reads contents of the specified file into the registry.
1320 BOOL import_registry_file(FILE* reg_file)
1322 if (reg_file)
1324 BYTE s[2];
1325 if (fread( s, 2, 1, reg_file) == 1)
1327 if (s[0] == 0xff && s[1] == 0xfe)
1329 processRegLinesW(reg_file);
1330 } else
1332 rewind(reg_file);
1333 processRegLinesA(reg_file);
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 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1358 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1359 getAppName(), reg_key_nameA);
1360 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1361 exit(1);
1363 if (!*key_name) {
1364 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1365 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1366 getAppName(), reg_key_nameA);
1367 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1368 exit(1);
1371 RegDeleteTreeW(key_class, key_name);