regedit: Modify getRegClass() to avoid dubious comparisons and casts between HKEYs...
[wine/testsucceed.git] / programs / regedit / regproc.c
blobd1d757d08fb1c36c31141680fcaf3c03432aa4f6
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 "regproc.h"
31 #define REG_VAL_BUF_SIZE 4096
33 /* maximal number of characters in hexadecimal data line,
34 not including '\' character */
35 #define REG_FILE_HEX_LINE_LEN 76
37 /* Globals used by the api setValue */
38 static LPSTR currentKeyName = NULL;
39 static HKEY currentKeyClass = 0;
40 static HKEY currentKeyHandle = 0;
41 static BOOL bTheKeyIsOpen = FALSE;
43 static const CHAR *reg_class_names[] = {
44 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
45 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
48 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
50 static HKEY reg_class_keys[REG_CLASS_NUMBER] = {
51 HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
52 HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
55 /* return values */
56 #define NOT_ENOUGH_MEMORY 1
57 #define IO_ERROR 2
59 /* processing macros */
61 /* common check of memory allocation results */
62 #define CHECK_ENOUGH_MEMORY(p) \
63 if (!(p)) \
64 { \
65 fprintf(stderr,"%s: file %s, line %d: Not enough memory", \
66 getAppName(), __FILE__, __LINE__); \
67 exit(NOT_ENOUGH_MEMORY); \
70 /******************************************************************************
71 * Converts a hex representation of a DWORD into a DWORD.
73 static BOOL convertHexToDWord(char* str, DWORD *dw)
75 char dummy;
76 if (strlen(str) > 8 || sscanf(str, "%x%c", dw, &dummy) != 1) {
77 fprintf(stderr,"%s: ERROR, invalid hex value\n", getAppName());
78 return FALSE;
80 return TRUE;
83 /******************************************************************************
84 * Converts a hex comma separated values list into a binary string.
86 static BYTE* convertHexCSVToHex(char *str, DWORD *size)
88 char *s;
89 BYTE *d, *data;
91 /* The worst case is 1 digit + 1 comma per byte */
92 *size=(strlen(str)+1)/2;
93 data=HeapAlloc(GetProcessHeap(), 0, *size);
94 CHECK_ENOUGH_MEMORY(data);
96 s = str;
97 d = data;
98 *size=0;
99 while (*s != '\0') {
100 UINT wc;
101 char dummy;
103 if (s[1] != ',' && s[1] != '\0' && s[2] != ',' && s[2] != '\0') {
104 fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid sequence at '%s'\n",
105 getAppName(), s);
106 HeapFree(GetProcessHeap(), 0, data);
107 return NULL;
109 if (sscanf(s, "%x%c", &wc, &dummy) < 1 || dummy != ',') {
110 fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
111 getAppName(), s);
112 HeapFree(GetProcessHeap(), 0, data);
113 return NULL;
115 *d++ =(BYTE)wc;
116 (*size)++;
118 s+=(wc < 0x10 ? 2 : 3);
121 return data;
124 /******************************************************************************
125 * This function returns the HKEY associated with the data type encoded in the
126 * value. It modifies the input parameter (key value) in order to skip this
127 * "now useless" data type information.
129 * Note: Updated based on the algorithm used in 'server/registry.c'
131 static DWORD getDataType(LPSTR *lpValue, DWORD* parse_type)
133 struct data_type { const char *tag; int len; int type; int parse_type; };
135 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
136 { "\"", 1, REG_SZ, REG_SZ },
137 { "str:\"", 5, REG_SZ, REG_SZ },
138 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
139 { "hex:", 4, REG_BINARY, REG_BINARY },
140 { "dword:", 6, REG_DWORD, REG_DWORD },
141 { "hex(", 4, -1, REG_BINARY },
142 { NULL, 0, 0, 0 }
145 const struct data_type *ptr;
146 int type;
148 for (ptr = data_types; ptr->tag; ptr++) {
149 if (memcmp( ptr->tag, *lpValue, ptr->len ))
150 continue;
152 /* Found! */
153 *parse_type = ptr->parse_type;
154 type=ptr->type;
155 *lpValue+=ptr->len;
156 if (type == -1) {
157 char* end;
158 /* "hex(xx):" is special */
159 type = (int)strtoul( *lpValue , &end, 16 );
160 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
161 type=REG_NONE;
162 } else {
163 *lpValue=end+2;
166 return type;
168 *parse_type=REG_NONE;
169 return REG_NONE;
172 /******************************************************************************
173 * Replaces escape sequences with the characters.
175 static void REGPROC_unescape_string(LPSTR str)
177 int str_idx = 0; /* current character under analysis */
178 int val_idx = 0; /* the last character of the unescaped string */
179 int len = strlen(str);
180 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
181 if (str[str_idx] == '\\') {
182 str_idx++;
183 switch (str[str_idx]) {
184 case 'n':
185 str[val_idx] = '\n';
186 break;
187 case '\\':
188 case '"':
189 str[val_idx] = str[str_idx];
190 break;
191 default:
192 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
193 str[str_idx]);
194 str[val_idx] = str[str_idx];
195 break;
197 } else {
198 str[val_idx] = str[str_idx];
201 str[val_idx] = '\0';
204 /******************************************************************************
205 * Sets the value with name val_name to the data in val_data for the currently
206 * opened key.
208 * Parameters:
209 * val_name - name of the registry value
210 * val_data - registry value data
212 static LONG setValue(LPSTR val_name, LPSTR val_data)
214 LONG res;
215 DWORD dwDataType, dwParseType;
216 LPBYTE lpbData;
217 DWORD dwData, dwLen;
219 if ( (val_name == NULL) || (val_data == NULL) )
220 return ERROR_INVALID_PARAMETER;
222 if (strcmp(val_data, "-") == 0)
224 res=RegDeleteValue(currentKeyHandle,val_name);
225 return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
228 /* Get the data type stored into the value field */
229 dwDataType = getDataType(&val_data, &dwParseType);
231 if (dwParseType == REG_SZ) /* no conversion for string */
233 REGPROC_unescape_string(val_data);
234 /* Compute dwLen after REGPROC_unescape_string because it may
235 * have changed the string length and we don't want to store
236 * the extra garbage in the registry.
238 dwLen = strlen(val_data);
239 if (dwLen>0 && val_data[dwLen-1]=='"')
241 dwLen--;
242 val_data[dwLen]='\0';
244 lpbData = (BYTE*) val_data;
246 else if (dwParseType == REG_DWORD) /* Convert the dword types */
248 if (!convertHexToDWord(val_data, &dwData))
249 return ERROR_INVALID_DATA;
250 lpbData = (BYTE*)&dwData;
251 dwLen = sizeof(dwData);
253 else if (dwParseType == REG_BINARY) /* Convert the binary data */
255 lpbData = convertHexCSVToHex(val_data, &dwLen);
256 if (!lpbData)
257 return ERROR_INVALID_DATA;
259 else /* unknown format */
261 fprintf(stderr,"%s: ERROR, unknown data format\n", getAppName());
262 return ERROR_INVALID_DATA;
265 res = RegSetValueEx(
266 currentKeyHandle,
267 val_name,
268 0, /* Reserved */
269 dwDataType,
270 lpbData,
271 dwLen);
272 if (dwParseType == REG_BINARY)
273 HeapFree(GetProcessHeap(), 0, lpbData);
274 return res;
278 /******************************************************************************
279 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
280 * the key class (what ends before the first '\')
282 static BOOL getRegClass(LPSTR lpClass, HKEY* hkey)
284 LPSTR classNameEnd;
285 LPSTR classNameBeg;
286 unsigned int i;
288 char lpClassCopy[KEY_MAX_LEN];
290 if (lpClass == NULL)
291 return FALSE;
293 lstrcpynA(lpClassCopy, lpClass, KEY_MAX_LEN);
295 classNameEnd = strchr(lpClassCopy, '\\'); /* The class name ends by '\' */
296 if (!classNameEnd) /* or the whole string */
298 classNameEnd = lpClassCopy + strlen(lpClassCopy);
299 if (classNameEnd[-1] == ']')
301 classNameEnd--;
304 *classNameEnd = '\0'; /* Isolate the class name */
305 if (lpClassCopy[0] == '[') {
306 classNameBeg = lpClassCopy + 1;
307 } else {
308 classNameBeg = lpClassCopy;
311 for (i = 0; i < REG_CLASS_NUMBER; i++) {
312 if (!strcmp(classNameBeg, reg_class_names[i])) {
313 *hkey = reg_class_keys[i];
314 return TRUE;
317 return FALSE;
320 /******************************************************************************
321 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
322 * the key name (what starts after the first '\')
324 static LPSTR getRegKeyName(LPSTR lpLine)
326 LPSTR keyNameBeg;
327 char lpLineCopy[KEY_MAX_LEN];
329 if (lpLine == NULL)
330 return NULL;
332 strcpy(lpLineCopy, lpLine);
334 keyNameBeg = strchr(lpLineCopy, '\\'); /* The key name start by '\' */
335 if (keyNameBeg) {
336 keyNameBeg++; /* is not part of the name */
338 if (lpLine[0] == '[') /* need to find matching ']' */
340 LPSTR keyNameEnd;
342 keyNameEnd = strrchr(lpLineCopy, ']');
343 if (keyNameEnd) {
344 *keyNameEnd = '\0'; /* remove ']' from the key name */
347 } else {
348 keyNameBeg = lpLineCopy + strlen(lpLineCopy); /* branch - empty string */
350 currentKeyName = HeapAlloc(GetProcessHeap(), 0, strlen(keyNameBeg) + 1);
351 CHECK_ENOUGH_MEMORY(currentKeyName);
352 strcpy(currentKeyName, keyNameBeg);
353 return currentKeyName;
356 /******************************************************************************
357 * Open the key
359 static LONG openKey( LPSTR stdInput)
361 DWORD dwDisp;
362 LONG res;
364 /* Sanity checks */
365 if (stdInput == NULL)
366 return ERROR_INVALID_PARAMETER;
368 /* Get the registry class */
369 if (!getRegClass(stdInput, &currentKeyClass)) /* Sets global variable */
370 return ERROR_INVALID_PARAMETER;
372 /* Get the key name */
373 currentKeyName = getRegKeyName(stdInput); /* Sets global variable */
374 if (currentKeyName == NULL)
375 return ERROR_INVALID_PARAMETER;
377 res = RegCreateKeyEx(
378 currentKeyClass, /* Class */
379 currentKeyName, /* Sub Key */
380 0, /* MUST BE 0 */
381 NULL, /* object type */
382 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
383 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
384 NULL, /* security attribute */
385 &currentKeyHandle, /* result */
386 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
387 REG_OPENED_EXISTING_KEY */
389 if (res == ERROR_SUCCESS)
390 bTheKeyIsOpen = TRUE;
392 return res;
396 /******************************************************************************
397 * Close the currently opened key.
399 static void closeKey(void)
401 RegCloseKey(currentKeyHandle);
403 HeapFree(GetProcessHeap(), 0, currentKeyName); /* Allocated by getKeyName */
405 bTheKeyIsOpen = FALSE;
407 currentKeyName = NULL;
408 currentKeyClass = 0;
409 currentKeyHandle = 0;
412 /******************************************************************************
413 * This function is a wrapper for the setValue function. It prepares the
414 * land and clean the area once completed.
415 * Note: this function modifies the line parameter.
417 * line - registry file unwrapped line. Should have the registry value name and
418 * complete registry value data.
420 static void processSetValue(LPSTR line)
422 LPSTR val_name; /* registry value name */
423 LPSTR val_data; /* registry value data */
425 int line_idx = 0; /* current character under analysis */
426 LONG res;
428 /* get value name */
429 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
430 line[line_idx] = '\0';
431 val_name = line;
432 line_idx++;
433 } else if (line[line_idx] == '\"') {
434 line_idx++;
435 val_name = line + line_idx;
436 while (TRUE) {
437 if (line[line_idx] == '\\') /* skip escaped character */
439 line_idx += 2;
440 } else {
441 if (line[line_idx] == '\"') {
442 line[line_idx] = '\0';
443 line_idx++;
444 break;
445 } else {
446 line_idx++;
450 if (line[line_idx] != '=') {
451 line[line_idx] = '\"';
452 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
453 return;
456 } else {
457 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
458 return;
460 line_idx++; /* skip the '=' character */
461 val_data = line + line_idx;
463 REGPROC_unescape_string(val_name);
464 res = setValue(val_name, val_data);
465 if ( res != ERROR_SUCCESS )
466 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
467 getAppName(),
468 currentKeyName,
469 val_name,
470 val_data);
473 /******************************************************************************
474 * This function receives the currently read entry and performs the
475 * corresponding action.
477 static void processRegEntry(LPSTR stdInput)
480 * We encountered the end of the file, make sure we
481 * close the opened key and exit
483 if (stdInput == NULL) {
484 if (bTheKeyIsOpen != FALSE)
485 closeKey();
487 return;
490 if ( stdInput[0] == '[') /* We are reading a new key */
492 if ( bTheKeyIsOpen != FALSE )
493 closeKey(); /* Close the previous key before */
495 /* delete the key if we encounter '-' at the start of reg key */
496 if ( stdInput[1] == '-')
498 int last_chr = strlen(stdInput) - 1;
500 /* skip leading "[-" and get rid of trailing "]" */
501 if (stdInput[last_chr] == ']')
502 stdInput[last_chr] = '\0';
503 delete_registry_key(stdInput+2);
504 return;
507 if ( openKey(stdInput) != ERROR_SUCCESS )
508 fprintf(stderr,"%s: setValue failed to open key %s\n",
509 getAppName(), stdInput);
510 } else if( ( bTheKeyIsOpen ) &&
511 (( stdInput[0] == '@') || /* reading a default @=data pair */
512 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
514 processSetValue(stdInput);
515 } else /* since we are assuming that the */
516 { /* file format is valid we must */
517 if ( bTheKeyIsOpen ) /* be reading a blank line which */
518 closeKey(); /* indicate end of this key processing */
522 /******************************************************************************
523 * Processes a registry file.
524 * Correctly processes comments (in # form), line continuation.
526 * Parameters:
527 * in - input stream to read from
529 void processRegLines(FILE *in)
531 LPSTR line = NULL; /* line read from input stream */
532 ULONG lineSize = REG_VAL_BUF_SIZE;
534 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
535 CHECK_ENOUGH_MEMORY(line);
537 while (!feof(in)) {
538 LPSTR s; /* The pointer into line for where the current fgets should read */
539 s = line;
540 for (;;) {
541 size_t size_remaining;
542 int size_to_get;
543 char *s_eol; /* various local uses */
545 /* Do we need to expand the buffer ? */
546 assert (s >= line && s <= line + lineSize);
547 size_remaining = lineSize - (s-line);
548 if (size_remaining < 2) /* room for 1 character and the \0 */
550 char *new_buffer;
551 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
552 if (new_size > lineSize) /* no arithmetic overflow */
553 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
554 else
555 new_buffer = NULL;
556 CHECK_ENOUGH_MEMORY(new_buffer);
557 line = new_buffer;
558 s = line + lineSize - size_remaining;
559 lineSize = new_size;
560 size_remaining = lineSize - (s-line);
563 /* Get as much as possible into the buffer, terminated either by
564 * eof, error, eol or getting the maximum amount. Abort on error.
566 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
567 if (NULL == fgets (s, size_to_get, in)) {
568 if (ferror(in)) {
569 perror ("While reading input");
570 exit (IO_ERROR);
571 } else {
572 assert (feof(in));
573 *s = '\0';
574 /* It is not clear to me from the definition that the
575 * contents of the buffer are well defined on detecting
576 * an eof without managing to read anything.
581 /* If we didn't read the eol nor the eof go around for the rest */
582 s_eol = strchr (s, '\n');
583 if (!feof (in) && !s_eol) {
584 s = strchr (s, '\0');
585 /* It should be s + size_to_get - 1 but this is safer */
586 continue;
589 /* If it is a comment line then discard it and go around again */
590 if (line [0] == '#') {
591 s = line;
592 continue;
595 /* Remove any line feed. Leave s_eol on the \0 */
596 if (s_eol) {
597 *s_eol = '\0';
598 if (s_eol > line && *(s_eol-1) == '\r')
599 *--s_eol = '\0';
600 } else
601 s_eol = strchr (s, '\0');
603 /* If there is a concatenating \\ then go around again */
604 if (s_eol > line && *(s_eol-1) == '\\') {
605 int c;
606 s = s_eol-1;
607 /* The following error protection could be made more self-
608 * correcting but I thought it not worth trying.
610 if ((c = fgetc (in)) == EOF || c != ' ' ||
611 (c = fgetc (in)) == EOF || c != ' ')
612 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
613 getAppName());
614 continue;
617 break; /* That is the full virtual line */
620 processRegEntry(line);
622 processRegEntry(NULL);
624 HeapFree(GetProcessHeap(), 0, line);
627 /****************************************************************************
628 * REGPROC_print_error
630 * Print the message for GetLastError
633 static void REGPROC_print_error(void)
635 LPVOID lpMsgBuf;
636 DWORD error_code;
637 int status;
639 error_code = GetLastError ();
640 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
641 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
642 if (!status) {
643 fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
644 getAppName(), error_code, GetLastError());
645 exit(1);
647 puts(lpMsgBuf);
648 LocalFree((HLOCAL)lpMsgBuf);
649 exit(1);
652 /******************************************************************************
653 * Checks whether the buffer has enough room for the string or required size.
654 * Resizes the buffer if necessary.
656 * Parameters:
657 * buffer - pointer to a buffer for string
658 * len - current length of the buffer in characters.
659 * required_len - length of the string to place to the buffer in characters.
660 * The length does not include the terminating null character.
662 static void REGPROC_resize_char_buffer(CHAR **buffer, DWORD *len, DWORD required_len)
664 required_len++;
665 if (required_len > *len) {
666 *len = required_len;
667 if (!*buffer)
668 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
669 else
670 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
671 CHECK_ENOUGH_MEMORY(*buffer);
675 /******************************************************************************
676 * Prints string str to file
678 static void REGPROC_export_string(FILE *file, CHAR *str)
680 size_t len = strlen(str);
681 size_t i;
683 /* escaping characters */
684 for (i = 0; i < len; i++) {
685 CHAR c = str[i];
686 switch (c) {
687 case '\\':
688 fputs("\\\\", file);
689 break;
690 case '\"':
691 fputs("\\\"", file);
692 break;
693 case '\n':
694 fputs("\\\n", file);
695 break;
696 default:
697 fputc(c, file);
698 break;
703 /******************************************************************************
704 * Writes contents of the registry key to the specified file stream.
706 * Parameters:
707 * file - writable file stream to export registry branch to.
708 * key - registry branch to export.
709 * reg_key_name_buf - name of the key with registry class.
710 * Is resized if necessary.
711 * reg_key_name_len - length of the buffer for the registry class in characters.
712 * val_name_buf - buffer for storing value name.
713 * Is resized if necessary.
714 * val_name_len - length of the buffer for storing value names in characters.
715 * val_buf - buffer for storing values while extracting.
716 * Is resized if necessary.
717 * val_size - size of the buffer for storing values in bytes.
719 static void export_hkey(FILE *file, HKEY key,
720 CHAR **reg_key_name_buf, DWORD *reg_key_name_len,
721 CHAR **val_name_buf, DWORD *val_name_len,
722 BYTE **val_buf, DWORD *val_size)
724 DWORD max_sub_key_len;
725 DWORD max_val_name_len;
726 DWORD max_val_size;
727 DWORD curr_len;
728 DWORD i;
729 BOOL more_data;
730 LONG ret;
732 /* get size information and resize the buffers if necessary */
733 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL,
734 &max_sub_key_len, NULL,
735 NULL, &max_val_name_len, &max_val_size, NULL, NULL
736 ) != ERROR_SUCCESS) {
737 REGPROC_print_error();
739 curr_len = strlen(*reg_key_name_buf);
740 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
741 max_sub_key_len + curr_len + 1);
742 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
743 max_val_name_len);
744 if (max_val_size > *val_size) {
745 *val_size = max_val_size;
746 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
747 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
748 CHECK_ENOUGH_MEMORY(val_buf);
751 /* output data for the current key */
752 fputs("\n[", file);
753 fputs(*reg_key_name_buf, file);
754 fputs("]\n", file);
755 /* print all the values */
756 i = 0;
757 more_data = TRUE;
758 while(more_data) {
759 DWORD value_type;
760 DWORD val_name_len1 = *val_name_len;
761 DWORD val_size1 = *val_size;
762 ret = RegEnumValue(key, i, *val_name_buf, &val_name_len1, NULL,
763 &value_type, *val_buf, &val_size1);
764 if (ret != ERROR_SUCCESS) {
765 more_data = FALSE;
766 if (ret != ERROR_NO_MORE_ITEMS) {
767 REGPROC_print_error();
769 } else {
770 i++;
772 if ((*val_name_buf)[0]) {
773 fputs("\"", file);
774 REGPROC_export_string(file, *val_name_buf);
775 fputs("\"=", file);
776 } else {
777 fputs("@=", file);
780 switch (value_type) {
781 case REG_SZ:
782 case REG_EXPAND_SZ:
783 fputs("\"", file);
784 REGPROC_export_string(file, (char*) *val_buf);
785 fputs("\"\n", file);
786 break;
788 case REG_DWORD:
789 fprintf(file, "dword:%08x\n", *((DWORD *)*val_buf));
790 break;
792 default:
793 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
794 "treat as binary\n",
795 getAppName(), value_type);
796 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
797 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
798 /* falls through */
799 case REG_MULTI_SZ:
800 /* falls through */
801 case REG_BINARY: {
802 DWORD i1;
803 const CHAR *hex_prefix;
804 CHAR buf[20];
805 int cur_pos;
807 if (value_type == REG_BINARY) {
808 hex_prefix = "hex:";
809 } else {
810 hex_prefix = buf;
811 sprintf(buf, "hex(%d):", value_type);
814 /* position of where the next character will be printed */
815 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
816 cur_pos = strlen("\"\"=") + strlen("hex:") +
817 strlen(*val_name_buf);
819 fputs(hex_prefix, file);
820 for (i1 = 0; i1 < val_size1; i1++) {
821 fprintf(file, "%02x", (unsigned int)(*val_buf)[i1]);
822 if (i1 + 1 < val_size1) {
823 fputs(",", file);
825 cur_pos += 3;
827 /* wrap the line */
828 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
829 fputs("\\\n ", file);
830 cur_pos = 2;
833 fputs("\n", file);
834 break;
840 i = 0;
841 more_data = TRUE;
842 (*reg_key_name_buf)[curr_len] = '\\';
843 while(more_data) {
844 DWORD buf_len = *reg_key_name_len - curr_len;
846 ret = RegEnumKeyEx(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
847 NULL, NULL, NULL, NULL);
848 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
849 more_data = FALSE;
850 if (ret != ERROR_NO_MORE_ITEMS) {
851 REGPROC_print_error();
853 } else {
854 HKEY subkey;
856 i++;
857 if (RegOpenKey(key, *reg_key_name_buf + curr_len + 1,
858 &subkey) == ERROR_SUCCESS) {
859 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
860 val_name_buf, val_name_len, val_buf, val_size);
861 RegCloseKey(subkey);
862 } else {
863 REGPROC_print_error();
867 (*reg_key_name_buf)[curr_len] = '\0';
870 /******************************************************************************
871 * Open file for export.
873 static FILE *REGPROC_open_export_file(CHAR *file_name)
875 FILE *file = fopen(file_name, "w");
876 if (!file) {
877 perror("");
878 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_name);
879 exit(1);
881 fputs("REGEDIT4\n", file);
882 return file;
885 /******************************************************************************
886 * Writes contents of the registry key to the specified file stream.
888 * Parameters:
889 * file_name - name of a file to export registry branch to.
890 * reg_key_name - registry branch to export. The whole registry is exported if
891 * reg_key_name is NULL or contains an empty string.
893 BOOL export_registry_key(CHAR *file_name, CHAR *reg_key_name)
895 HKEY reg_key_class;
897 CHAR *reg_key_name_buf;
898 CHAR *val_name_buf;
899 BYTE *val_buf;
900 DWORD reg_key_name_len = KEY_MAX_LEN;
901 DWORD val_name_len = KEY_MAX_LEN;
902 DWORD val_size = REG_VAL_BUF_SIZE;
903 FILE *file = NULL;
905 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
906 reg_key_name_len * sizeof(*reg_key_name_buf));
907 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
908 val_name_len * sizeof(*val_name_buf));
909 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
910 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
912 if (reg_key_name && reg_key_name[0]) {
913 CHAR *branch_name;
914 HKEY key;
916 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
917 strlen(reg_key_name));
918 strcpy(reg_key_name_buf, reg_key_name);
920 /* open the specified key */
921 if (!getRegClass(reg_key_name, &reg_key_class)) {
922 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
923 getAppName(), reg_key_name);
924 exit(1);
926 branch_name = getRegKeyName(reg_key_name);
927 CHECK_ENOUGH_MEMORY(branch_name);
928 if (!branch_name[0]) {
929 /* no branch - registry class is specified */
930 file = REGPROC_open_export_file(file_name);
931 export_hkey(file, reg_key_class,
932 &reg_key_name_buf, &reg_key_name_len,
933 &val_name_buf, &val_name_len,
934 &val_buf, &val_size);
935 } else if (RegOpenKey(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
936 file = REGPROC_open_export_file(file_name);
937 export_hkey(file, key,
938 &reg_key_name_buf, &reg_key_name_len,
939 &val_name_buf, &val_name_len,
940 &val_buf, &val_size);
941 RegCloseKey(key);
942 } else {
943 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
944 getAppName(), reg_key_name);
945 REGPROC_print_error();
947 HeapFree(GetProcessHeap(), 0, branch_name);
948 } else {
949 unsigned int i;
951 /* export all registry classes */
952 file = REGPROC_open_export_file(file_name);
953 for (i = 0; i < REG_CLASS_NUMBER; i++) {
954 /* do not export HKEY_CLASSES_ROOT */
955 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
956 reg_class_keys[i] != HKEY_CURRENT_USER &&
957 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
958 reg_class_keys[i] != HKEY_DYN_DATA) {
959 strcpy(reg_key_name_buf, reg_class_names[i]);
960 export_hkey(file, reg_class_keys[i],
961 &reg_key_name_buf, &reg_key_name_len,
962 &val_name_buf, &val_name_len,
963 &val_buf, &val_size);
968 if (file) {
969 fclose(file);
971 HeapFree(GetProcessHeap(), 0, reg_key_name);
972 HeapFree(GetProcessHeap(), 0, val_buf);
973 return TRUE;
976 /******************************************************************************
977 * Reads contents of the specified file into the registry.
979 BOOL import_registry_file(LPTSTR filename)
981 FILE* reg_file = fopen(filename, "r");
983 if (reg_file) {
984 processRegLines(reg_file);
985 return TRUE;
987 return FALSE;
990 /******************************************************************************
991 * Recursive function which removes the registry key with all subkeys.
993 static void delete_branch(HKEY key,
994 CHAR **reg_key_name_buf, DWORD *reg_key_name_len)
996 HKEY branch_key;
997 DWORD max_sub_key_len;
998 DWORD subkeys;
999 DWORD curr_len;
1000 LONG ret;
1001 long int i;
1003 if (RegOpenKey(key, *reg_key_name_buf, &branch_key) != ERROR_SUCCESS) {
1004 REGPROC_print_error();
1007 /* get size information and resize the buffers if necessary */
1008 if (RegQueryInfoKey(branch_key, NULL, NULL, NULL,
1009 &subkeys, &max_sub_key_len,
1010 NULL, NULL, NULL, NULL, NULL, NULL
1011 ) != ERROR_SUCCESS) {
1012 REGPROC_print_error();
1014 curr_len = strlen(*reg_key_name_buf);
1015 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1016 max_sub_key_len + curr_len + 1);
1018 (*reg_key_name_buf)[curr_len] = '\\';
1019 for (i = subkeys - 1; i >= 0; i--) {
1020 DWORD buf_len = *reg_key_name_len - curr_len;
1022 ret = RegEnumKeyEx(branch_key, i, *reg_key_name_buf + curr_len + 1,
1023 &buf_len, NULL, NULL, NULL, NULL);
1024 if (ret != ERROR_SUCCESS &&
1025 ret != ERROR_MORE_DATA &&
1026 ret != ERROR_NO_MORE_ITEMS) {
1027 REGPROC_print_error();
1028 } else {
1029 delete_branch(key, reg_key_name_buf, reg_key_name_len);
1032 (*reg_key_name_buf)[curr_len] = '\0';
1033 RegCloseKey(branch_key);
1034 RegDeleteKey(key, *reg_key_name_buf);
1037 /******************************************************************************
1038 * Removes the registry key with all subkeys. Parses full key name.
1040 * Parameters:
1041 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1042 * empty, points to register key class, does not exist.
1044 void delete_registry_key(CHAR *reg_key_name)
1046 CHAR *branch_name;
1047 DWORD branch_name_len;
1048 HKEY reg_key_class;
1049 HKEY branch_key;
1051 if (!reg_key_name || !reg_key_name[0])
1052 return;
1053 /* open the specified key */
1054 if (!getRegClass(reg_key_name, &reg_key_class)) {
1055 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1056 getAppName(), reg_key_name);
1057 exit(1);
1059 branch_name = getRegKeyName(reg_key_name);
1060 CHECK_ENOUGH_MEMORY(branch_name);
1061 branch_name_len = strlen(branch_name);
1062 if (!branch_name[0]) {
1063 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1064 getAppName(), reg_key_name);
1065 exit(1);
1067 if (RegOpenKey(reg_key_class, branch_name, &branch_key) == ERROR_SUCCESS) {
1068 /* check whether the key exists */
1069 RegCloseKey(branch_key);
1070 delete_branch(reg_key_class, &branch_name, &branch_name_len);
1072 HeapFree(GetProcessHeap(), 0, branch_name);