regedit: Convert clipboard handling to unicode.
[wine/wine-kai.git] / programs / regedit / regproc.c
blob8f05a2d6e4504dc13058802e3212657711833e4d
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 WCHAR* strW = NULL;
74 int len = MultiByteToWideChar(CP_ACP, 0, strA, -1, NULL, 0);
76 strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
77 CHECK_ENOUGH_MEMORY(strW);
78 MultiByteToWideChar(CP_ACP, 0, strA, -1, strW, len);
79 return strW;
82 /******************************************************************************
83 * Allocates memory and convers input from wide chars to multibyte
84 * Returned string must be freed by the caller
86 char* GetMultiByteString(const WCHAR* strW)
88 char* strA = NULL;
89 int len = WideCharToMultiByte(CP_ACP, 0, strW, -1, NULL, 0, NULL, NULL);
91 strA = HeapAlloc(GetProcessHeap(), 0, len);
92 CHECK_ENOUGH_MEMORY(strA);
93 WideCharToMultiByte(CP_ACP, 0, strW, -1, strA, len, NULL, NULL);
94 return strA;
97 /******************************************************************************
98 * Converts a hex representation of a DWORD into a DWORD.
100 static BOOL convertHexToDWord(WCHAR* str, DWORD *dw)
102 char buf[9];
103 char dummy;
105 WideCharToMultiByte(CP_ACP, 0, str, -1, buf, 9, NULL, NULL);
106 if (lstrlenW(str) > 8 || sscanf(buf, "%x%c", dw, &dummy) != 1) {
107 fprintf(stderr,"%s: ERROR, invalid hex value\n", getAppName());
108 return FALSE;
110 return TRUE;
113 /******************************************************************************
114 * Converts a hex comma separated values list into a binary string.
116 static BYTE* convertHexCSVToHex(WCHAR *strW, DWORD *size)
118 char *s;
119 BYTE *d, *data;
120 char* strA = GetMultiByteString(strW);
122 /* The worst case is 1 digit + 1 comma per byte */
123 *size=(strlen(strA)+1)/2;
124 data=HeapAlloc(GetProcessHeap(), 0, *size);
125 CHECK_ENOUGH_MEMORY(data);
127 s = strA;
128 d = data;
129 *size=0;
130 while (*s != '\0') {
131 UINT wc;
132 char *end;
134 wc = strtoul(s,&end,16);
135 if (end == s || wc > 0xff || (*end && *end != ',')) {
136 fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
137 getAppName(), s);
138 HeapFree(GetProcessHeap(), 0, data);
139 HeapFree(GetProcessHeap(), 0, strA);
140 return NULL;
142 *d++ =(BYTE)wc;
143 (*size)++;
144 if (*end) end++;
145 s = end;
148 HeapFree(GetProcessHeap(), 0, strA);
150 return data;
153 /******************************************************************************
154 * This function returns the HKEY associated with the data type encoded in the
155 * value. It modifies the input parameter (key value) in order to skip this
156 * "now useless" data type information.
158 * Note: Updated based on the algorithm used in 'server/registry.c'
160 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
162 struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
164 static const WCHAR quote[] = {'"'};
165 static const WCHAR str[] = {'s','t','r',':','"'};
166 static const WCHAR str2[] = {'s','t','r','(','2',')',':','"'};
167 static const WCHAR hex[] = {'h','e','x',':'};
168 static const WCHAR dword[] = {'d','w','o','r','d',':'};
169 static const WCHAR hexp[] = {'h','e','x','('};
171 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
172 { quote, 1, REG_SZ, REG_SZ },
173 { str, 5, REG_SZ, REG_SZ },
174 { str2, 8, REG_EXPAND_SZ, REG_SZ },
175 { hex, 4, REG_BINARY, REG_BINARY },
176 { dword, 6, REG_DWORD, REG_DWORD },
177 { hexp, 4, -1, REG_BINARY },
178 { NULL, 0, 0, 0 }
181 const struct data_type *ptr;
182 int type;
184 for (ptr = data_types; ptr->tag; ptr++) {
185 if (strncmpW( ptr->tag, *lpValue, ptr->len ))
186 continue;
188 /* Found! */
189 *parse_type = ptr->parse_type;
190 type=ptr->type;
191 *lpValue+=ptr->len;
192 if (type == -1) {
193 WCHAR* end;
195 /* "hex(xx):" is special */
196 type = (int)strtoulW( *lpValue , &end, 16 );
197 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
198 type=REG_NONE;
199 } else {
200 *lpValue = end + 2;
203 return type;
205 *parse_type=REG_NONE;
206 return REG_NONE;
209 /******************************************************************************
210 * Replaces escape sequences with the characters.
212 static void REGPROC_unescape_string(WCHAR* str)
214 int str_idx = 0; /* current character under analysis */
215 int val_idx = 0; /* the last character of the unescaped string */
216 int len = lstrlenW(str);
217 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
218 if (str[str_idx] == '\\') {
219 str_idx++;
220 switch (str[str_idx]) {
221 case 'n':
222 str[val_idx] = '\n';
223 break;
224 case '\\':
225 case '"':
226 str[val_idx] = str[str_idx];
227 break;
228 default:
229 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
230 str[str_idx]);
231 str[val_idx] = str[str_idx];
232 break;
234 } else {
235 str[val_idx] = str[str_idx];
238 str[val_idx] = '\0';
241 /******************************************************************************
242 * Parses HKEY_SOME_ROOT\some\key\path to get the root key handle and
243 * extract the key path (what comes after the first '\').
245 static BOOL parseKeyName(LPSTR lpKeyName, HKEY *hKey, LPSTR *lpKeyPath)
247 LPSTR lpSlash;
248 unsigned int i, len;
250 if (lpKeyName == NULL)
251 return FALSE;
253 lpSlash = strchr(lpKeyName, '\\');
254 if (lpSlash)
256 len = lpSlash-lpKeyName;
258 else
260 len = strlen(lpKeyName);
261 lpSlash = lpKeyName+len;
263 *hKey = NULL;
264 for (i = 0; i < REG_CLASS_NUMBER; i++) {
265 if (strncmp(lpKeyName, reg_class_names[i], len) == 0 &&
266 len == strlen(reg_class_names[i])) {
267 *hKey = reg_class_keys[i];
268 break;
271 if (*hKey == NULL)
272 return FALSE;
274 if (*lpSlash != '\0')
275 lpSlash++;
276 *lpKeyPath = lpSlash;
277 return TRUE;
280 static BOOL parseKeyNameW(LPWSTR lpKeyName, HKEY *hKey, LPWSTR *lpKeyPath)
282 WCHAR* lpSlash = NULL;
283 unsigned int i, len;
285 if (lpKeyName == NULL)
286 return FALSE;
288 for(i = 0; *(lpKeyName+i) != 0; i++)
290 if(*(lpKeyName+i) == '\\')
292 lpSlash = lpKeyName+i;
293 break;
297 if (lpSlash)
299 len = lpSlash-lpKeyName;
301 else
303 len = lstrlenW(lpKeyName);
304 lpSlash = lpKeyName+len;
306 *hKey = NULL;
308 for (i = 0; i < REG_CLASS_NUMBER; i++) {
309 if (CompareStringW(LOCALE_USER_DEFAULT, 0, lpKeyName, len, reg_class_namesW[i], len) == CSTR_EQUAL &&
310 len == lstrlenW(reg_class_namesW[i])) {
311 *hKey = reg_class_keys[i];
312 break;
316 if (*hKey == NULL)
317 return FALSE;
320 if (*lpSlash != '\0')
321 lpSlash++;
322 *lpKeyPath = lpSlash;
323 return TRUE;
326 /* Globals used by the setValue() & co */
327 static LPSTR currentKeyName;
328 static HKEY currentKeyHandle = NULL;
330 /******************************************************************************
331 * Sets the value with name val_name to the data in val_data for the currently
332 * opened key.
334 * Parameters:
335 * val_name - name of the registry value
336 * val_data - registry value data
338 static LONG setValue(WCHAR* val_name, WCHAR* val_data)
340 LONG res;
341 DWORD dwDataType, dwParseType;
342 LPBYTE lpbData;
343 DWORD dwData, dwLen;
344 WCHAR del[] = {'-',0};
346 if ( (val_name == NULL) || (val_data == NULL) )
347 return ERROR_INVALID_PARAMETER;
349 if (lstrcmpW(val_data, del) == 0)
351 res=RegDeleteValueW(currentKeyHandle,val_name);
352 return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
355 /* Get the data type stored into the value field */
356 dwDataType = getDataType(&val_data, &dwParseType);
358 if (dwParseType == REG_SZ) /* no conversion for string */
360 REGPROC_unescape_string(val_data);
361 /* Compute dwLen after REGPROC_unescape_string because it may
362 * have changed the string length and we don't want to store
363 * the extra garbage in the registry.
365 dwLen = lstrlenW(val_data);
366 if (dwLen>0 && val_data[dwLen-1]=='"')
368 dwLen--;
369 val_data[dwLen]='\0';
371 lpbData = (BYTE*) val_data;
372 dwLen++; /* include terminating null */
373 dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
375 else if (dwParseType == REG_DWORD) /* Convert the dword types */
377 if (!convertHexToDWord(val_data, &dwData))
378 return ERROR_INVALID_DATA;
379 lpbData = (BYTE*)&dwData;
380 dwLen = sizeof(dwData);
382 else if (dwParseType == REG_BINARY) /* Convert the binary data */
384 lpbData = convertHexCSVToHex(val_data, &dwLen);
385 if (!lpbData)
386 return ERROR_INVALID_DATA;
388 else /* unknown format */
390 fprintf(stderr,"%s: ERROR, unknown data format\n", getAppName());
391 return ERROR_INVALID_DATA;
394 res = RegSetValueExW(
395 currentKeyHandle,
396 val_name,
397 0, /* Reserved */
398 dwDataType,
399 lpbData,
400 dwLen);
401 if (dwParseType == REG_BINARY)
402 HeapFree(GetProcessHeap(), 0, lpbData);
403 return res;
406 /******************************************************************************
407 * A helper function for processRegEntry() that opens the current key.
408 * That key must be closed by calling closeKey().
410 static LONG openKeyW(WCHAR* stdInput)
412 HKEY keyClass;
413 WCHAR* keyPath;
414 DWORD dwDisp;
415 LONG res;
417 /* Sanity checks */
418 if (stdInput == NULL)
419 return ERROR_INVALID_PARAMETER;
421 /* Get the registry class */
422 if (!parseKeyNameW(stdInput, &keyClass, &keyPath))
423 return ERROR_INVALID_PARAMETER;
425 res = RegCreateKeyExW(
426 keyClass, /* Class */
427 keyPath, /* Sub Key */
428 0, /* MUST BE 0 */
429 NULL, /* object type */
430 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
431 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
432 NULL, /* security attribute */
433 &currentKeyHandle, /* result */
434 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
435 REG_OPENED_EXISTING_KEY */
437 if (res == ERROR_SUCCESS)
438 currentKeyName = GetMultiByteString(stdInput);
439 else
440 currentKeyHandle = NULL;
442 return res;
446 /******************************************************************************
447 * Close the currently opened key.
449 static void closeKey(void)
451 if (currentKeyHandle)
453 HeapFree(GetProcessHeap(), 0, currentKeyName);
454 RegCloseKey(currentKeyHandle);
455 currentKeyHandle = NULL;
459 /******************************************************************************
460 * This function is a wrapper for the setValue function. It prepares the
461 * land and cleans the area once completed.
462 * Note: this function modifies the line parameter.
464 * line - registry file unwrapped line. Should have the registry value name and
465 * complete registry value data.
467 static void processSetValue(WCHAR* line)
469 WCHAR* val_name; /* registry value name */
470 WCHAR* val_data; /* registry value data */
471 int line_idx = 0; /* current character under analysis */
472 LONG res;
474 /* get value name */
475 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
476 line[line_idx] = '\0';
477 val_name = line;
478 line_idx++;
479 } else if (line[line_idx] == '\"') {
480 line_idx++;
481 val_name = line + line_idx;
482 while (TRUE) {
483 if (line[line_idx] == '\\') /* skip escaped character */
485 line_idx += 2;
486 } else {
487 if (line[line_idx] == '\"') {
488 line[line_idx] = '\0';
489 line_idx++;
490 break;
491 } else {
492 line_idx++;
496 if (line[line_idx] != '=') {
497 char* lineA;
498 line[line_idx] = '\"';
499 lineA = GetMultiByteString(line);
500 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
501 HeapFree(GetProcessHeap(), 0, lineA);
502 return;
505 } else {
506 char* lineA = GetMultiByteString(line);
507 fprintf(stderr,"Warning! unrecognized line:\n%s\n", lineA);
508 HeapFree(GetProcessHeap(), 0, lineA);
509 return;
511 line_idx++; /* skip the '=' character */
512 val_data = line + line_idx;
514 REGPROC_unescape_string(val_name);
515 res = setValue(val_name, val_data);
516 if ( res != ERROR_SUCCESS )
518 char* val_nameA = GetMultiByteString(val_name);
519 char* val_dataA = GetMultiByteString(val_data);
520 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
521 getAppName(),
522 currentKeyName,
523 val_nameA,
524 val_dataA);
525 HeapFree(GetProcessHeap(), 0, val_nameA);
526 HeapFree(GetProcessHeap(), 0, val_dataA);
530 /******************************************************************************
531 * This function receives the currently read entry and performs the
532 * corresponding action.
534 static void processRegEntry(WCHAR* stdInput)
537 * We encountered the end of the file, make sure we
538 * close the opened key and exit
540 if (stdInput == NULL) {
541 closeKey();
542 return;
545 if ( stdInput[0] == '[') /* We are reading a new key */
547 WCHAR* keyEnd;
548 closeKey(); /* Close the previous key */
550 /* Get rid of the square brackets */
551 stdInput++;
552 keyEnd = strrchrW(stdInput, ']');
553 if (keyEnd)
554 *keyEnd='\0';
556 /* delete the key if we encounter '-' at the start of reg key */
557 if ( stdInput[0] == '-')
559 delete_registry_key(stdInput + 1);
560 } else if ( openKeyW(stdInput) != ERROR_SUCCESS )
562 fprintf(stderr,"%s: setValue failed to open key %s\n",
563 getAppName(), stdInput);
565 } else if( currentKeyHandle &&
566 (( stdInput[0] == '@') || /* reading a default @=data pair */
567 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
569 processSetValue(stdInput);
570 } else
572 /* Since we are assuming that the file format is valid we must be
573 * reading a blank line which indicates the end of this key processing
575 closeKey();
579 /******************************************************************************
580 * Processes a registry file.
581 * Correctly processes comments (in # form), line continuation.
583 * Parameters:
584 * in - input stream to read from
586 void processRegLinesA(FILE *in)
588 LPSTR line = NULL; /* line read from input stream */
589 ULONG lineSize = REG_VAL_BUF_SIZE;
591 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
592 CHECK_ENOUGH_MEMORY(line);
594 while (!feof(in)) {
595 LPSTR s; /* The pointer into line for where the current fgets should read */
596 LPSTR check;
597 WCHAR* lineW;
598 s = line;
599 for (;;) {
600 size_t size_remaining;
601 int size_to_get;
602 char *s_eol; /* various local uses */
604 /* Do we need to expand the buffer ? */
605 assert (s >= line && s <= line + lineSize);
606 size_remaining = lineSize - (s-line);
607 if (size_remaining < 2) /* room for 1 character and the \0 */
609 char *new_buffer;
610 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
611 if (new_size > lineSize) /* no arithmetic overflow */
612 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
613 else
614 new_buffer = NULL;
615 CHECK_ENOUGH_MEMORY(new_buffer);
616 line = new_buffer;
617 s = line + lineSize - size_remaining;
618 lineSize = new_size;
619 size_remaining = lineSize - (s-line);
622 /* Get as much as possible into the buffer, terminated either by
623 * eof, error, eol or getting the maximum amount. Abort on error.
625 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
627 check = fgets (s, size_to_get, in);
629 if (check == NULL) {
630 if (ferror(in)) {
631 perror ("While reading input");
632 exit (IO_ERROR);
633 } else {
634 assert (feof(in));
635 *s = '\0';
636 /* It is not clear to me from the definition that the
637 * contents of the buffer are well defined on detecting
638 * an eof without managing to read anything.
643 /* If we didn't read the eol nor the eof go around for the rest */
644 s_eol = strchr (s, '\n');
645 if (!feof (in) && !s_eol) {
646 s = strchr (s, '\0');
647 /* It should be s + size_to_get - 1 but this is safer */
648 continue;
651 /* If it is a comment line then discard it and go around again */
652 if (line [0] == '#') {
653 s = line;
654 continue;
657 /* Remove any line feed. Leave s_eol on the \0 */
658 if (s_eol) {
659 *s_eol = '\0';
660 if (s_eol > line && *(s_eol-1) == '\r')
661 *--s_eol = '\0';
662 } else
663 s_eol = strchr (s, '\0');
665 /* If there is a concatenating \\ then go around again */
666 if (s_eol > line && *(s_eol-1) == '\\') {
667 int c;
668 s = s_eol-1;
669 /* The following error protection could be made more self-
670 * correcting but I thought it not worth trying.
672 if ((c = fgetc (in)) == EOF || c != ' ' ||
673 (c = fgetc (in)) == EOF || c != ' ')
674 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
675 getAppName());
676 continue;
679 lineW = GetWideString(line);
681 break; /* That is the full virtual line */
684 processRegEntry(lineW);
685 HeapFree(GetProcessHeap(), 0, lineW);
687 processRegEntry(NULL);
689 HeapFree(GetProcessHeap(), 0, line);
692 void processRegLinesW(FILE *in)
694 WCHAR* buf = NULL; /* line read from input stream */
695 ULONG lineSize = REG_VAL_BUF_SIZE;
696 size_t CharsInBuf = -1;
698 WCHAR* s; /* The pointer into line for where the current fgets should read */
700 buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
701 CHECK_ENOUGH_MEMORY(buf);
703 s = buf;
705 while(!feof(in)) {
706 size_t size_remaining;
707 int size_to_get;
708 WCHAR *s_eol = NULL; /* various local uses */
710 /* Do we need to expand the buffer ? */
711 assert (s >= buf && s <= buf + lineSize);
712 size_remaining = lineSize - (s-buf);
713 if (size_remaining < 2) /* room for 1 character and the \0 */
715 WCHAR *new_buffer;
716 size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
717 if (new_size > lineSize) /* no arithmetic overflow */
718 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
719 else
720 new_buffer = NULL;
721 CHECK_ENOUGH_MEMORY(new_buffer);
722 buf = new_buffer;
723 s = buf + lineSize - size_remaining;
724 lineSize = new_size;
725 size_remaining = lineSize - (s-buf);
728 /* Get as much as possible into the buffer, terminated either by
729 * eof, error or getting the maximum amount. Abort on error.
731 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
733 CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
734 s[CharsInBuf] = 0;
736 if (CharsInBuf == 0) {
737 if (ferror(in)) {
738 perror ("While reading input");
739 exit (IO_ERROR);
740 } else {
741 assert (feof(in));
742 *s = '\0';
743 /* It is not clear to me from the definition that the
744 * contents of the buffer are well defined on detecting
745 * an eof without managing to read anything.
750 /* If we didn't read the eol nor the eof go around for the rest */
751 while(1)
753 s_eol = strchrW(s, '\n');
755 if(!s_eol)
756 break;
758 /* If it is a comment line then discard it and go around again */
759 if (*s == '#') {
760 s = s_eol + 1;
761 continue;
764 /* If there is a concatenating \\ then go around again */
765 if ((*(s_eol-1) == '\\') ||
766 (*(s_eol-1) == '\r' && *(s_eol-2) == '\\')) {
767 WCHAR* NextLine = s_eol;
769 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
770 NextLine++;
772 NextLine++;
774 if(*(s_eol-1) == '\r')
775 s_eol--;
777 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - buf) + 1)*sizeof(WCHAR));
778 CharsInBuf -= NextLine - s_eol + 1;
779 s_eol = 0;
780 continue;
783 /* Remove any line feed. Leave s_eol on the \0 */
784 if (s_eol) {
785 *s_eol = '\0';
786 if (s_eol > buf && *(s_eol-1) == '\r')
787 *(s_eol-1) = '\0';
790 if(!s_eol)
791 break;
793 processRegEntry(s);
794 s = s_eol + 1;
795 s_eol = 0;
796 continue; /* That is the full virtual line */
800 processRegEntry(NULL);
802 HeapFree(GetProcessHeap(), 0, buf);
805 /****************************************************************************
806 * REGPROC_print_error
808 * Print the message for GetLastError
811 static void REGPROC_print_error(void)
813 LPVOID lpMsgBuf;
814 DWORD error_code;
815 int status;
817 error_code = GetLastError ();
818 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
819 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
820 if (!status) {
821 fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
822 getAppName(), error_code, GetLastError());
823 exit(1);
825 puts(lpMsgBuf);
826 LocalFree((HLOCAL)lpMsgBuf);
827 exit(1);
830 /******************************************************************************
831 * Checks whether the buffer has enough room for the string or required size.
832 * Resizes the buffer if necessary.
834 * Parameters:
835 * buffer - pointer to a buffer for string
836 * len - current length of the buffer in characters.
837 * required_len - length of the string to place to the buffer in characters.
838 * The length does not include the terminating null character.
840 static void REGPROC_resize_char_buffer(CHAR **buffer, DWORD *len, DWORD required_len)
842 required_len++;
843 if (required_len > *len) {
844 *len = required_len;
845 if (!*buffer)
846 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
847 else
848 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
849 CHECK_ENOUGH_MEMORY(*buffer);
853 /******************************************************************************
854 * Prints string str to file
856 static void REGPROC_export_string(FILE *file, CHAR *str)
858 size_t len = strlen(str);
859 size_t i;
861 /* escaping characters */
862 for (i = 0; i < len; i++) {
863 CHAR c = str[i];
864 switch (c) {
865 case '\\':
866 fputs("\\\\", file);
867 break;
868 case '\"':
869 fputs("\\\"", file);
870 break;
871 case '\n':
872 fputs("\\\n", file);
873 break;
874 default:
875 fputc(c, file);
876 break;
881 /******************************************************************************
882 * Writes contents of the registry key to the specified file stream.
884 * Parameters:
885 * file - writable file stream to export registry branch to.
886 * key - registry branch to export.
887 * reg_key_name_buf - name of the key with registry class.
888 * Is resized if necessary.
889 * reg_key_name_len - length of the buffer for the registry class in characters.
890 * val_name_buf - buffer for storing value name.
891 * Is resized if necessary.
892 * val_name_len - length of the buffer for storing value names in characters.
893 * val_buf - buffer for storing values while extracting.
894 * Is resized if necessary.
895 * val_size - size of the buffer for storing values in bytes.
897 static void export_hkey(FILE *file, HKEY key,
898 CHAR **reg_key_name_buf, DWORD *reg_key_name_len,
899 CHAR **val_name_buf, DWORD *val_name_len,
900 BYTE **val_buf, DWORD *val_size)
902 DWORD max_sub_key_len;
903 DWORD max_val_name_len;
904 DWORD max_val_size;
905 DWORD curr_len;
906 DWORD i;
907 BOOL more_data;
908 LONG ret;
910 /* get size information and resize the buffers if necessary */
911 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL,
912 &max_sub_key_len, NULL,
913 NULL, &max_val_name_len, &max_val_size, NULL, NULL
914 ) != ERROR_SUCCESS) {
915 REGPROC_print_error();
917 curr_len = strlen(*reg_key_name_buf);
918 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
919 max_sub_key_len + curr_len + 1);
920 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
921 max_val_name_len);
922 if (max_val_size > *val_size) {
923 *val_size = max_val_size;
924 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
925 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
926 CHECK_ENOUGH_MEMORY(val_buf);
929 /* output data for the current key */
930 fputs("\n[", file);
931 fputs(*reg_key_name_buf, file);
932 fputs("]\n", file);
933 /* print all the values */
934 i = 0;
935 more_data = TRUE;
936 while(more_data) {
937 DWORD value_type;
938 DWORD val_name_len1 = *val_name_len;
939 DWORD val_size1 = *val_size;
940 ret = RegEnumValue(key, i, *val_name_buf, &val_name_len1, NULL,
941 &value_type, *val_buf, &val_size1);
942 if (ret != ERROR_SUCCESS) {
943 more_data = FALSE;
944 if (ret != ERROR_NO_MORE_ITEMS) {
945 REGPROC_print_error();
947 } else {
948 i++;
950 if ((*val_name_buf)[0]) {
951 fputs("\"", file);
952 REGPROC_export_string(file, *val_name_buf);
953 fputs("\"=", file);
954 } else {
955 fputs("@=", file);
958 switch (value_type) {
959 case REG_SZ:
960 case REG_EXPAND_SZ:
961 fputs("\"", file);
962 if (val_size1) REGPROC_export_string(file, (char*) *val_buf);
963 fputs("\"\n", file);
964 break;
966 case REG_DWORD:
967 fprintf(file, "dword:%08x\n", *((DWORD *)*val_buf));
968 break;
970 default:
971 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
972 "treat as binary\n",
973 getAppName(), value_type);
974 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
975 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
976 /* falls through */
977 case REG_MULTI_SZ:
978 /* falls through */
979 case REG_BINARY: {
980 DWORD i1;
981 const CHAR *hex_prefix;
982 CHAR buf[20];
983 int cur_pos;
985 if (value_type == REG_BINARY) {
986 hex_prefix = "hex:";
987 } else {
988 hex_prefix = buf;
989 sprintf(buf, "hex(%d):", value_type);
992 /* position of where the next character will be printed */
993 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
994 cur_pos = strlen("\"\"=") + strlen("hex:") +
995 strlen(*val_name_buf);
997 fputs(hex_prefix, file);
998 for (i1 = 0; i1 < val_size1; i1++) {
999 fprintf(file, "%02x", (unsigned int)(*val_buf)[i1]);
1000 if (i1 + 1 < val_size1) {
1001 fputs(",", file);
1003 cur_pos += 3;
1005 /* wrap the line */
1006 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1007 fputs("\\\n ", file);
1008 cur_pos = 2;
1011 fputs("\n", file);
1012 break;
1018 i = 0;
1019 more_data = TRUE;
1020 (*reg_key_name_buf)[curr_len] = '\\';
1021 while(more_data) {
1022 DWORD buf_len = *reg_key_name_len - curr_len;
1024 ret = RegEnumKeyEx(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1025 NULL, NULL, NULL, NULL);
1026 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1027 more_data = FALSE;
1028 if (ret != ERROR_NO_MORE_ITEMS) {
1029 REGPROC_print_error();
1031 } else {
1032 HKEY subkey;
1034 i++;
1035 if (RegOpenKey(key, *reg_key_name_buf + curr_len + 1,
1036 &subkey) == ERROR_SUCCESS) {
1037 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1038 val_name_buf, val_name_len, val_buf, val_size);
1039 RegCloseKey(subkey);
1040 } else {
1041 REGPROC_print_error();
1045 (*reg_key_name_buf)[curr_len] = '\0';
1048 /******************************************************************************
1049 * Open file for export.
1051 static FILE *REGPROC_open_export_file(CHAR *file_name)
1053 FILE *file;
1055 if (strcmp(file_name,"-")==0)
1056 file=stdout;
1057 else
1059 file = fopen(file_name, "w");
1060 if (!file) {
1061 perror("");
1062 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_name);
1063 exit(1);
1066 fputs("REGEDIT4\n", file);
1067 return file;
1070 /******************************************************************************
1071 * Writes contents of the registry key to the specified file stream.
1073 * Parameters:
1074 * file_name - name of a file to export registry branch to.
1075 * reg_key_name - registry branch to export. The whole registry is exported if
1076 * reg_key_name is NULL or contains an empty string.
1078 BOOL export_registry_key(CHAR *file_name, CHAR *reg_key_name)
1080 CHAR *reg_key_name_buf;
1081 CHAR *val_name_buf;
1082 BYTE *val_buf;
1083 DWORD reg_key_name_len = KEY_MAX_LEN;
1084 DWORD val_name_len = KEY_MAX_LEN;
1085 DWORD val_size = REG_VAL_BUF_SIZE;
1086 FILE *file = NULL;
1088 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1089 reg_key_name_len * sizeof(*reg_key_name_buf));
1090 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1091 val_name_len * sizeof(*val_name_buf));
1092 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1093 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1095 if (reg_key_name && reg_key_name[0]) {
1096 HKEY reg_key_class;
1097 CHAR *branch_name = NULL;
1098 HKEY key;
1100 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1101 strlen(reg_key_name));
1102 strcpy(reg_key_name_buf, reg_key_name);
1104 /* open the specified key */
1105 if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1106 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1107 getAppName(), reg_key_name);
1108 exit(1);
1110 if (!branch_name[0]) {
1111 /* no branch - registry class is specified */
1112 file = REGPROC_open_export_file(file_name);
1113 export_hkey(file, reg_key_class,
1114 &reg_key_name_buf, &reg_key_name_len,
1115 &val_name_buf, &val_name_len,
1116 &val_buf, &val_size);
1117 } else if (RegOpenKey(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1118 file = REGPROC_open_export_file(file_name);
1119 export_hkey(file, key,
1120 &reg_key_name_buf, &reg_key_name_len,
1121 &val_name_buf, &val_name_len,
1122 &val_buf, &val_size);
1123 RegCloseKey(key);
1124 } else {
1125 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1126 getAppName(), reg_key_name);
1127 REGPROC_print_error();
1129 } else {
1130 unsigned int i;
1132 /* export all registry classes */
1133 file = REGPROC_open_export_file(file_name);
1134 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1135 /* do not export HKEY_CLASSES_ROOT */
1136 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1137 reg_class_keys[i] != HKEY_CURRENT_USER &&
1138 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1139 reg_class_keys[i] != HKEY_DYN_DATA) {
1140 strcpy(reg_key_name_buf, reg_class_names[i]);
1141 export_hkey(file, reg_class_keys[i],
1142 &reg_key_name_buf, &reg_key_name_len,
1143 &val_name_buf, &val_name_len,
1144 &val_buf, &val_size);
1149 if (file) {
1150 fclose(file);
1152 HeapFree(GetProcessHeap(), 0, reg_key_name);
1153 HeapFree(GetProcessHeap(), 0, val_buf);
1154 return TRUE;
1157 /******************************************************************************
1158 * Reads contents of the specified file into the registry.
1160 BOOL import_registry_file(FILE* reg_file)
1162 if (reg_file)
1164 BYTE s[2];
1165 if (fread( s, 2, 1, reg_file) == 1)
1167 if (s[0] == 0xff && s[1] == 0xfe)
1169 processRegLinesW(reg_file);
1170 } else
1172 rewind(reg_file);
1173 processRegLinesA(reg_file);
1176 return TRUE;
1178 return FALSE;
1181 /******************************************************************************
1182 * Removes the registry key with all subkeys. Parses full key name.
1184 * Parameters:
1185 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1186 * empty, points to register key class, does not exist.
1188 void delete_registry_key(WCHAR *reg_key_name)
1190 WCHAR *key_name = NULL;
1191 HKEY key_class;
1193 if (!reg_key_name || !reg_key_name[0])
1194 return;
1196 if (!parseKeyNameW(reg_key_name, &key_class, &key_name)) {
1197 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1198 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1199 getAppName(), reg_key_nameA);
1200 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1201 exit(1);
1203 if (!*key_name) {
1204 char* reg_key_nameA = GetMultiByteString(reg_key_name);
1205 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1206 getAppName(), reg_key_nameA);
1207 HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1208 exit(1);
1211 RegDeleteTreeW(key_class, key_name);