ws2_32: name is never NULL as array (Coverity).
[wine] / programs / regedit / regproc.c
1 /*
2  * Registry processing routines. Routines, common for registry
3  * processing frontends.
4  *
5  * Copyright 1999 Sylvain St-Germain
6  * Copyright 2002 Andriy Palamarchuk
7  * Copyright 2008 Alexander N. Sørnes <alex@thehandofagony.com>
8  *
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.
13  *
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.
18  *
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
22  */
23
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"
32
33 #define REG_VAL_BUF_SIZE        4096
34
35 /* maximal number of characters in hexadecimal data line,
36  * including the indentation, but not including the '\' character
37  */
38 #define REG_FILE_HEX_LINE_LEN   (2 + 25 * 3)
39
40 extern const WCHAR* reg_class_namesW[];
41
42 static HKEY reg_class_keys[] = {
43             HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
44             HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
45         };
46
47 #define REG_CLASS_NUMBER (sizeof(reg_class_keys) / sizeof(reg_class_keys[0]))
48
49 /* return values */
50 #define NOT_ENOUGH_MEMORY     1
51 #define IO_ERROR              2
52
53 /* processing macros */
54
55 /* common check of memory allocation results */
56 #define CHECK_ENOUGH_MEMORY(p) \
57 if (!(p)) \
58 { \
59     fprintf(stderr,"%s: file %s, line %d: Not enough memory\n", \
60             getAppName(), __FILE__, __LINE__); \
61     exit(NOT_ENOUGH_MEMORY); \
62 }
63
64 /******************************************************************************
65  * Allocates memory and converts input from multibyte to wide chars
66  * Returned string must be freed by the caller
67  */
68 WCHAR* GetWideString(const char* strA)
69 {
70     if(strA)
71     {
72         WCHAR* strW;
73         int len = MultiByteToWideChar(CP_ACP, 0, strA, -1, NULL, 0);
74
75         strW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
76         CHECK_ENOUGH_MEMORY(strW);
77         MultiByteToWideChar(CP_ACP, 0, strA, -1, strW, len);
78         return strW;
79     }
80     return NULL;
81 }
82
83 /******************************************************************************
84  * Allocates memory and converts input from multibyte to wide chars
85  * Returned string must be freed by the caller
86  */
87 static WCHAR* GetWideStringN(const char* strA, int chars, DWORD *len)
88 {
89     if(strA)
90     {
91         WCHAR* strW;
92         *len = MultiByteToWideChar(CP_ACP, 0, strA, chars, NULL, 0);
93
94         strW = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(WCHAR));
95         CHECK_ENOUGH_MEMORY(strW);
96         MultiByteToWideChar(CP_ACP, 0, strA, chars, strW, *len);
97         return strW;
98     }
99     *len = 0;
100     return NULL;
101 }
102
103 /******************************************************************************
104  * Allocates memory and converts input from wide chars to multibyte
105  * Returned string must be freed by the caller
106  */
107 char* GetMultiByteString(const WCHAR* strW)
108 {
109     if(strW)
110     {
111         char* strA;
112         int len = WideCharToMultiByte(CP_ACP, 0, strW, -1, NULL, 0, NULL, NULL);
113
114         strA = HeapAlloc(GetProcessHeap(), 0, len);
115         CHECK_ENOUGH_MEMORY(strA);
116         WideCharToMultiByte(CP_ACP, 0, strW, -1, strA, len, NULL, NULL);
117         return strA;
118     }
119     return NULL;
120 }
121
122 /******************************************************************************
123  * Allocates memory and converts input from wide chars to multibyte
124  * Returned string must be freed by the caller
125  */
126 static char* GetMultiByteStringN(const WCHAR* strW, int chars, DWORD* len)
127 {
128     if(strW)
129     {
130         char* strA;
131         *len = WideCharToMultiByte(CP_ACP, 0, strW, chars, NULL, 0, NULL, NULL);
132
133         strA = HeapAlloc(GetProcessHeap(), 0, *len);
134         CHECK_ENOUGH_MEMORY(strA);
135         WideCharToMultiByte(CP_ACP, 0, strW, chars, strA, *len, NULL, NULL);
136         return strA;
137     }
138     *len = 0;
139     return NULL;
140 }
141
142 /******************************************************************************
143  * Converts a hex representation of a DWORD into a DWORD.
144  */
145 static BOOL convertHexToDWord(WCHAR* str, DWORD *dw)
146 {
147     char buf[9];
148     char dummy;
149
150     WideCharToMultiByte(CP_ACP, 0, str, -1, buf, 9, NULL, NULL);
151     if (lstrlenW(str) > 8 || sscanf(buf, "%x%c", dw, &dummy) != 1) {
152         fprintf(stderr,"%s: ERROR, invalid hex value\n", getAppName());
153         return FALSE;
154     }
155     return TRUE;
156 }
157
158 /******************************************************************************
159  * Converts a hex comma separated values list into a binary string.
160  */
161 static BYTE* convertHexCSVToHex(WCHAR *str, DWORD *size)
162 {
163     WCHAR *s;
164     BYTE *d, *data;
165
166     /* The worst case is 1 digit + 1 comma per byte */
167     *size=(lstrlenW(str)+1)/2;
168     data=HeapAlloc(GetProcessHeap(), 0, *size);
169     CHECK_ENOUGH_MEMORY(data);
170
171     s = str;
172     d = data;
173     *size=0;
174     while (*s != '\0') {
175         UINT wc;
176         WCHAR *end;
177
178         wc = strtoulW(s,&end,16);
179         if (end == s || wc > 0xff || (*end && *end != ',')) {
180             char* strA = GetMultiByteString(s);
181             fprintf(stderr,"%s: ERROR converting CSV hex stream. Invalid value at '%s'\n",
182                     getAppName(), strA);
183             HeapFree(GetProcessHeap(), 0, data);
184             HeapFree(GetProcessHeap(), 0, strA);
185             return NULL;
186         }
187         *d++ =(BYTE)wc;
188         (*size)++;
189         if (*end) end++;
190         s = end;
191     }
192
193     return data;
194 }
195
196 /******************************************************************************
197  * This function returns the HKEY associated with the data type encoded in the
198  * value.  It modifies the input parameter (key value) in order to skip this
199  * "now useless" data type information.
200  *
201  * Note: Updated based on the algorithm used in 'server/registry.c'
202  */
203 static DWORD getDataType(LPWSTR *lpValue, DWORD* parse_type)
204 {
205     struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
206
207     static const WCHAR quote[] = {'"'};
208     static const WCHAR str[] = {'s','t','r',':','"'};
209     static const WCHAR str2[] = {'s','t','r','(','2',')',':','"'};
210     static const WCHAR hex[] = {'h','e','x',':'};
211     static const WCHAR dword[] = {'d','w','o','r','d',':'};
212     static const WCHAR hexp[] = {'h','e','x','('};
213
214     static const struct data_type data_types[] = {                   /* actual type */  /* type to assume for parsing */
215                 { quote,       1,   REG_SZ,              REG_SZ },
216                 { str,         5,   REG_SZ,              REG_SZ },
217                 { str2,        8,   REG_EXPAND_SZ,       REG_SZ },
218                 { hex,         4,   REG_BINARY,          REG_BINARY },
219                 { dword,       6,   REG_DWORD,           REG_DWORD },
220                 { hexp,        4,   -1,                  REG_BINARY },
221                 { NULL,        0,    0,                  0 }
222             };
223
224     const struct data_type *ptr;
225     int type;
226
227     for (ptr = data_types; ptr->tag; ptr++) {
228         if (strncmpW( ptr->tag, *lpValue, ptr->len ))
229             continue;
230
231         /* Found! */
232         *parse_type = ptr->parse_type;
233         type=ptr->type;
234         *lpValue+=ptr->len;
235         if (type == -1) {
236             WCHAR* end;
237
238             /* "hex(xx):" is special */
239             type = (int)strtoulW( *lpValue , &end, 16 );
240             if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
241                 type=REG_NONE;
242             } else {
243                 *lpValue = end + 2;
244             }
245         }
246         return type;
247     }
248     *parse_type=REG_NONE;
249     return REG_NONE;
250 }
251
252 /******************************************************************************
253  * Replaces escape sequences with the characters.
254  */
255 static void REGPROC_unescape_string(WCHAR* str)
256 {
257     int str_idx = 0;            /* current character under analysis */
258     int val_idx = 0;            /* the last character of the unescaped string */
259     int len = lstrlenW(str);
260     for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
261         if (str[str_idx] == '\\') {
262             str_idx++;
263             switch (str[str_idx]) {
264             case 'n':
265                 str[val_idx] = '\n';
266                 break;
267             case '\\':
268             case '"':
269                 str[val_idx] = str[str_idx];
270                 break;
271             default:
272                 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
273                         str[str_idx]);
274                 str[val_idx] = str[str_idx];
275                 break;
276             }
277         } else {
278             str[val_idx] = str[str_idx];
279         }
280     }
281     str[val_idx] = '\0';
282 }
283
284 static BOOL parseKeyName(LPWSTR lpKeyName, HKEY *hKey, LPWSTR *lpKeyPath)
285 {
286     WCHAR* lpSlash = NULL;
287     unsigned int i, len;
288
289     if (lpKeyName == NULL)
290         return FALSE;
291
292     for(i = 0; *(lpKeyName+i) != 0; i++)
293     {
294         if(*(lpKeyName+i) == '\\')
295         {
296             lpSlash = lpKeyName+i;
297             break;
298         }
299     }
300
301     if (lpSlash)
302     {
303         len = lpSlash-lpKeyName;
304     }
305     else
306     {
307         len = lstrlenW(lpKeyName);
308         lpSlash = lpKeyName+len;
309     }
310     *hKey = NULL;
311
312     for (i = 0; i < REG_CLASS_NUMBER; i++) {
313         if (CompareStringW(LOCALE_USER_DEFAULT, 0, lpKeyName, len, reg_class_namesW[i], len) == CSTR_EQUAL &&
314             len == lstrlenW(reg_class_namesW[i])) {
315             *hKey = reg_class_keys[i];
316             break;
317         }
318     }
319
320     if (*hKey == NULL)
321         return FALSE;
322
323
324     if (*lpSlash != '\0')
325         lpSlash++;
326     *lpKeyPath = lpSlash;
327     return TRUE;
328 }
329
330 /* Globals used by the setValue() & co */
331 static LPSTR currentKeyName;
332 static HKEY  currentKeyHandle = NULL;
333
334 /******************************************************************************
335  * Sets the value with name val_name to the data in val_data for the currently
336  * opened key.
337  *
338  * Parameters:
339  * val_name - name of the registry value
340  * val_data - registry value data
341  */
342 static LONG setValue(WCHAR* val_name, WCHAR* val_data, BOOL is_unicode)
343 {
344     LONG res;
345     DWORD  dwDataType, dwParseType;
346     LPBYTE lpbData;
347     DWORD  dwData, dwLen;
348     WCHAR del[] = {'-',0};
349
350     if ( (val_name == NULL) || (val_data == NULL) )
351         return ERROR_INVALID_PARAMETER;
352
353     if (lstrcmpW(val_data, del) == 0)
354     {
355         res=RegDeleteValueW(currentKeyHandle,val_name);
356         return (res == ERROR_FILE_NOT_FOUND ? ERROR_SUCCESS : res);
357     }
358
359     /* Get the data type stored into the value field */
360     dwDataType = getDataType(&val_data, &dwParseType);
361
362     if (dwParseType == REG_SZ)          /* no conversion for string */
363     {
364         REGPROC_unescape_string(val_data);
365         /* Compute dwLen after REGPROC_unescape_string because it may
366          * have changed the string length and we don't want to store
367          * the extra garbage in the registry.
368          */
369         dwLen = lstrlenW(val_data);
370         if(val_data[dwLen-1] != '"')
371             return ERROR_INVALID_DATA;
372         if (dwLen>0 && val_data[dwLen-1]=='"')
373         {
374             dwLen--;
375             val_data[dwLen]='\0';
376         }
377         lpbData = (BYTE*) val_data;
378         dwLen++;  /* include terminating null */
379         dwLen = dwLen * sizeof(WCHAR); /* size is in bytes */
380     }
381     else if (dwParseType == REG_DWORD)  /* Convert the dword types */
382     {
383         if (!convertHexToDWord(val_data, &dwData))
384             return ERROR_INVALID_DATA;
385         lpbData = (BYTE*)&dwData;
386         dwLen = sizeof(dwData);
387     }
388     else if (dwParseType == REG_BINARY) /* Convert the binary data */
389     {
390         lpbData = convertHexCSVToHex(val_data, &dwLen);
391         if (!lpbData)
392             return ERROR_INVALID_DATA;
393
394         if((dwDataType == REG_MULTI_SZ || dwDataType == REG_EXPAND_SZ) && !is_unicode)
395         {
396             LPBYTE tmp = lpbData;
397             lpbData = (LPBYTE)GetWideStringN((char*)lpbData, dwLen, &dwLen);
398             dwLen *= sizeof(WCHAR);
399             HeapFree(GetProcessHeap(), 0, tmp);
400         }
401     }
402     else                                /* unknown format */
403     {
404         fprintf(stderr,"%s: ERROR, unknown data format\n", getAppName());
405         return ERROR_INVALID_DATA;
406     }
407
408     res = RegSetValueExW(
409                currentKeyHandle,
410                val_name,
411                0,                  /* Reserved */
412                dwDataType,
413                lpbData,
414                dwLen);
415     if (dwParseType == REG_BINARY)
416         HeapFree(GetProcessHeap(), 0, lpbData);
417     return res;
418 }
419
420 /******************************************************************************
421  * A helper function for processRegEntry() that opens the current key.
422  * That key must be closed by calling closeKey().
423  */
424 static LONG openKeyW(WCHAR* stdInput)
425 {
426     HKEY keyClass;
427     WCHAR* keyPath;
428     DWORD dwDisp;
429     LONG res;
430
431     /* Sanity checks */
432     if (stdInput == NULL)
433         return ERROR_INVALID_PARAMETER;
434
435     /* Get the registry class */
436     if (!parseKeyName(stdInput, &keyClass, &keyPath))
437         return ERROR_INVALID_PARAMETER;
438
439     res = RegCreateKeyExW(
440                keyClass,                 /* Class     */
441                keyPath,                  /* Sub Key   */
442                0,                        /* MUST BE 0 */
443                NULL,                     /* object type */
444                REG_OPTION_NON_VOLATILE,  /* option, REG_OPTION_NON_VOLATILE ... */
445                KEY_ALL_ACCESS,           /* access mask, KEY_ALL_ACCESS */
446                NULL,                     /* security attribute */
447                &currentKeyHandle,        /* result */
448                &dwDisp);                 /* disposition, REG_CREATED_NEW_KEY or
449                                                         REG_OPENED_EXISTING_KEY */
450
451     if (res == ERROR_SUCCESS)
452         currentKeyName = GetMultiByteString(stdInput);
453     else
454         currentKeyHandle = NULL;
455
456     return res;
457
458 }
459
460 /******************************************************************************
461  * Close the currently opened key.
462  */
463 static void closeKey(void)
464 {
465     if (currentKeyHandle)
466     {
467         HeapFree(GetProcessHeap(), 0, currentKeyName);
468         RegCloseKey(currentKeyHandle);
469         currentKeyHandle = NULL;
470     }
471 }
472
473 /******************************************************************************
474  * This function is a wrapper for the setValue function.  It prepares the
475  * land and cleans the area once completed.
476  * Note: this function modifies the line parameter.
477  *
478  * line - registry file unwrapped line. Should have the registry value name and
479  *      complete registry value data.
480  */
481 static void processSetValue(WCHAR* line, BOOL is_unicode)
482 {
483     WCHAR* val_name;                   /* registry value name   */
484     WCHAR* val_data;                   /* registry value data   */
485     int line_idx = 0;                 /* current character under analysis */
486     LONG res;
487
488     /* get value name */
489     while ( isspaceW(line[line_idx]) ) line_idx++;
490     if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
491         line[line_idx] = '\0';
492         val_name = line;
493         line_idx++;
494     } else if (line[line_idx] == '\"') {
495         line_idx++;
496         val_name = line + line_idx;
497         while (line[line_idx]) {
498             if (line[line_idx] == '\\')   /* skip escaped character */
499             {
500                 line_idx += 2;
501             } else {
502                 if (line[line_idx] == '\"') {
503                     line[line_idx] = '\0';
504                     line_idx++;
505                     break;
506                 } else {
507                     line_idx++;
508                 }
509             }
510         }
511         while ( isspaceW(line[line_idx]) ) line_idx++;
512         if (!line[line_idx]) {
513             fprintf(stderr, "%s: warning: unexpected EOL\n", getAppName());
514             return;
515         }
516         if (line[line_idx] != '=') {
517             char* lineA;
518             line[line_idx] = '\"';
519             lineA = GetMultiByteString(line);
520             fprintf(stderr,"%s: warning: unrecognized line: '%s'\n", getAppName(), lineA);
521             HeapFree(GetProcessHeap(), 0, lineA);
522             return;
523         }
524
525     } else {
526         char* lineA = GetMultiByteString(line);
527         fprintf(stderr,"%s: warning: unrecognized line: '%s'\n", getAppName(), lineA);
528         HeapFree(GetProcessHeap(), 0, lineA);
529         return;
530     }
531     line_idx++;                   /* skip the '=' character */
532
533     while ( isspaceW(line[line_idx]) ) line_idx++;
534     val_data = line + line_idx;
535     /* trim trailing blanks */
536     line_idx = strlenW(val_data);
537     while (line_idx > 0 && isspaceW(val_data[line_idx-1])) line_idx--;
538     val_data[line_idx] = '\0';
539
540     REGPROC_unescape_string(val_name);
541     res = setValue(val_name, val_data, is_unicode);
542     if ( res != ERROR_SUCCESS )
543     {
544         char* val_nameA = GetMultiByteString(val_name);
545         char* val_dataA = GetMultiByteString(val_data);
546         fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
547                 getAppName(),
548                 currentKeyName,
549                 val_nameA,
550                 val_dataA);
551         HeapFree(GetProcessHeap(), 0, val_nameA);
552         HeapFree(GetProcessHeap(), 0, val_dataA);
553     }
554 }
555
556 /******************************************************************************
557  * This function receives the currently read entry and performs the
558  * corresponding action.
559  * isUnicode affects parsing of REG_MULTI_SZ values
560  */
561 static void processRegEntry(WCHAR* stdInput, BOOL isUnicode)
562 {
563     /*
564      * We encountered the end of the file, make sure we
565      * close the opened key and exit
566      */
567     if (stdInput == NULL) {
568         closeKey();
569         return;
570     }
571
572     if      ( stdInput[0] == '[')      /* We are reading a new key */
573     {
574         WCHAR* keyEnd;
575         closeKey();                    /* Close the previous key */
576
577         /* Get rid of the square brackets */
578         stdInput++;
579         keyEnd = strrchrW(stdInput, ']');
580         if (keyEnd)
581             *keyEnd='\0';
582
583         /* delete the key if we encounter '-' at the start of reg key */
584         if ( stdInput[0] == '-')
585         {
586             delete_registry_key(stdInput + 1);
587         } else if ( openKeyW(stdInput) != ERROR_SUCCESS )
588         {
589             char* stdInputA = GetMultiByteString(stdInput);
590             fprintf(stderr,"%s: setValue failed to open key %s\n",
591                     getAppName(), stdInputA);
592             HeapFree(GetProcessHeap(), 0, stdInputA);
593         }
594     } else if( currentKeyHandle &&
595                (( stdInput[0] == '@') || /* reading a default @=data pair */
596                 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
597     {
598         processSetValue(stdInput, isUnicode);
599     } else
600     {
601         /* Since we are assuming that the file format is valid we must be
602          * reading a blank line which indicates the end of this key processing
603          */
604         closeKey();
605     }
606 }
607
608 /******************************************************************************
609  * Processes a registry file.
610  * Correctly processes comments (in # form), line continuation.
611  *
612  * Parameters:
613  *   in - input stream to read from
614  *   first_chars - beginning of stream, read due to Unicode check
615  */
616 static void processRegLinesA(FILE *in, char* first_chars)
617 {
618     LPSTR line           = NULL;  /* line read from input stream */
619     ULONG lineSize       = REG_VAL_BUF_SIZE;
620
621     line = HeapAlloc(GetProcessHeap(), 0, lineSize);
622     CHECK_ENOUGH_MEMORY(line);
623     memcpy(line, first_chars, 2);
624
625     while (!feof(in)) {
626         LPSTR s; /* The pointer into line for where the current fgets should read */
627         WCHAR* lineW;
628         s = line;
629
630         if(first_chars)
631         {
632             s += 2;
633             first_chars = NULL;
634         }
635
636         for (;;) {
637             size_t size_remaining;
638             int size_to_get, i;
639             char *s_eol; /* various local uses */
640
641             /* Do we need to expand the buffer ? */
642             assert (s >= line && s <= line + lineSize);
643             size_remaining = lineSize - (s-line);
644             if (size_remaining < 2) /* room for 1 character and the \0 */
645             {
646                 char *new_buffer;
647                 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
648                 if (new_size > lineSize) /* no arithmetic overflow */
649                     new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
650                 else
651                     new_buffer = NULL;
652                 CHECK_ENOUGH_MEMORY(new_buffer);
653                 line = new_buffer;
654                 s = line + lineSize - size_remaining;
655                 lineSize = new_size;
656                 size_remaining = lineSize - (s-line);
657             }
658
659             /* Get as much as possible into the buffer, terminated either by
660              * eof, error, eol or getting the maximum amount.  Abort on error.
661              */
662             size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
663
664             /* get a single line. note that `i' must be one past the last
665              * meaningful character in `s' when this loop exits */
666             for(i = 0; i < size_to_get-1; ++i){
667                 int xchar;
668
669                 xchar = fgetc(in);
670                 s[i] = xchar;
671                 if(xchar == EOF){
672                     if(ferror(in)){
673                         perror("While reading input");
674                         exit(IO_ERROR);
675                     }else
676                         assert(feof(in));
677                     break;
678                 }
679                 if(s[i] == '\r'){
680                     /* read the next character iff it's \n */
681                     if(i+2 >= size_to_get){
682                         /* buffer too short, so put back the EOL char to
683                          * read next cycle */
684                         ungetc('\r', in);
685                         break;
686                     }
687                     s[i+1] = fgetc(in);
688                     if(s[i+1] != '\n'){
689                         ungetc(s[i+1], in);
690                         i = i+1;
691                     }else
692                         i = i+2;
693                     break;
694                 }
695                 if(s[i] == '\n'){
696                     i = i+1;
697                     break;
698                 }
699             }
700             s[i] = '\0';
701
702             /* If we didn't read the eol nor the eof go around for the rest */
703             s_eol = strpbrk (s, "\r\n");
704             if (!feof (in) && !s_eol) {
705                 s = strchr (s, '\0');
706                 continue;
707             }
708
709             /* If it is a comment line then discard it and go around again */
710             if (line [0] == '#') {
711                 s = line;
712                 continue;
713             }
714
715             /* Remove any line feed.  Leave s_eol on the first \0 */
716             if (s_eol) {
717                if (*s_eol == '\r' && *(s_eol+1) == '\n')
718                    *(s_eol+1) = '\0';
719                *s_eol = '\0';
720             } else
721                 s_eol = strchr (s, '\0');
722
723             /* If there is a concatenating \\ then go around again */
724             if (s_eol > line && *(s_eol-1) == '\\') {
725                 int c;
726                 s = s_eol-1;
727
728                 do
729                 {
730                     c = fgetc(in);
731                 } while(c == ' ' || c == '\t');
732
733                 if(c == EOF)
734                 {
735                     fprintf(stderr,"%s: ERROR - invalid continuation.\n",
736                             getAppName());
737                 }
738                 else
739                 {
740                     *s = c;
741                     s++;
742                 }
743                 continue;
744             }
745
746             lineW = GetWideString(line);
747
748             break; /* That is the full virtual line */
749         }
750
751         processRegEntry(lineW, FALSE);
752         HeapFree(GetProcessHeap(), 0, lineW);
753     }
754     processRegEntry(NULL, FALSE);
755
756     HeapFree(GetProcessHeap(), 0, line);
757 }
758
759 static void processRegLinesW(FILE *in)
760 {
761     WCHAR* buf           = NULL;  /* line read from input stream */
762     ULONG lineSize       = REG_VAL_BUF_SIZE;
763     size_t CharsInBuf = -1;
764
765     WCHAR* s; /* The pointer into buf for where the current fgets should read */
766     WCHAR* line; /* The start of the current line */
767
768     buf = HeapAlloc(GetProcessHeap(), 0, lineSize * sizeof(WCHAR));
769     CHECK_ENOUGH_MEMORY(buf);
770
771     s = buf;
772     line = buf;
773
774     while(!feof(in)) {
775         size_t size_remaining;
776         int size_to_get;
777         WCHAR *s_eol = NULL; /* various local uses */
778
779         /* Do we need to expand the buffer ? */
780         assert (s >= buf && s <= buf + lineSize);
781         size_remaining = lineSize - (s-buf);
782         if (size_remaining < 2) /* room for 1 character and the \0 */
783         {
784             WCHAR *new_buffer;
785             size_t new_size = lineSize + (REG_VAL_BUF_SIZE / sizeof(WCHAR));
786             if (new_size > lineSize) /* no arithmetic overflow */
787                 new_buffer = HeapReAlloc (GetProcessHeap(), 0, buf, new_size * sizeof(WCHAR));
788             else
789                 new_buffer = NULL;
790             CHECK_ENOUGH_MEMORY(new_buffer);
791             buf = new_buffer;
792             line = buf;
793             s = buf + lineSize - size_remaining;
794             lineSize = new_size;
795             size_remaining = lineSize - (s-buf);
796         }
797
798         /* Get as much as possible into the buffer, terminated either by
799         * eof, error or getting the maximum amount.  Abort on error.
800         */
801         size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
802
803         CharsInBuf = fread(s, sizeof(WCHAR), size_to_get - 1, in);
804         s[CharsInBuf] = 0;
805
806         if (CharsInBuf == 0) {
807             if (ferror(in)) {
808                 perror ("While reading input");
809                 exit (IO_ERROR);
810             } else {
811                 assert (feof(in));
812                 *s = '\0';
813                 /* It is not clear to me from the definition that the
814                 * contents of the buffer are well defined on detecting
815                 * an eof without managing to read anything.
816                 */
817             }
818         }
819
820         /* If we didn't read the eol nor the eof go around for the rest */
821         while(1)
822         {
823             const WCHAR line_endings[] = {'\r','\n',0};
824             s_eol = strpbrkW(line, line_endings);
825
826             if(!s_eol) {
827                 /* Move the stub of the line to the start of the buffer so
828                  * we get the maximum space to read into, and so we don't
829                  * have to recalculate 'line' if the buffer expands */
830                 MoveMemory(buf, line, (strlenW(line)+1) * sizeof(WCHAR));
831                 line = buf;
832                 s = strchrW(line, '\0');
833                 break;
834             }
835
836             /* If it is a comment line then discard it and go around again */
837             if (*line == '#') {
838                 if (*s_eol == '\r' && *(s_eol+1) == '\n')
839                     line = s_eol + 2;
840                 else
841                     line = s_eol + 1;
842                 continue;
843             }
844
845             /* If there is a concatenating \\ then go around again */
846             if (*(s_eol-1) == '\\') {
847                 WCHAR* NextLine = s_eol + 1;
848
849                 if(*s_eol == '\r' && *(s_eol+1) == '\n')
850                     NextLine++;
851
852                 while(*(NextLine+1) == ' ' || *(NextLine+1) == '\t')
853                     NextLine++;
854
855                 MoveMemory(s_eol - 1, NextLine, (CharsInBuf - (NextLine - s) + 1)*sizeof(WCHAR));
856                 CharsInBuf -= NextLine - s_eol + 1;
857                 s_eol = 0;
858                 continue;
859             }
860
861             /* Remove any line feed.  Leave s_eol on the last \0 */
862             if (*s_eol == '\r' && *(s_eol + 1) == '\n')
863                 *s_eol++ = '\0';
864             *s_eol = '\0';
865
866             processRegEntry(line, TRUE);
867             line = s_eol + 1;
868             s_eol = 0;
869             continue; /* That is the full virtual line */
870         }
871     }
872
873     processRegEntry(NULL, TRUE);
874
875     HeapFree(GetProcessHeap(), 0, buf);
876 }
877
878 /****************************************************************************
879  * REGPROC_print_error
880  *
881  * Print the message for GetLastError
882  */
883
884 static void REGPROC_print_error(void)
885 {
886     LPVOID lpMsgBuf;
887     DWORD error_code;
888     int status;
889
890     error_code = GetLastError ();
891     status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
892                            NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
893     if (!status) {
894         fprintf(stderr,"%s: Cannot display message for error %d, status %d\n",
895                 getAppName(), error_code, GetLastError());
896         exit(1);
897     }
898     puts(lpMsgBuf);
899     LocalFree(lpMsgBuf);
900     exit(1);
901 }
902
903 /******************************************************************************
904  * Checks whether the buffer has enough room for the string or required size.
905  * Resizes the buffer if necessary.
906  *
907  * Parameters:
908  * buffer - pointer to a buffer for string
909  * len - current length of the buffer in characters.
910  * required_len - length of the string to place to the buffer in characters.
911  *   The length does not include the terminating null character.
912  */
913 static void REGPROC_resize_char_buffer(WCHAR **buffer, DWORD *len, DWORD required_len)
914 {
915     required_len++;
916     if (required_len > *len) {
917         *len = required_len;
918         if (!*buffer)
919             *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
920         else
921             *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
922         CHECK_ENOUGH_MEMORY(*buffer);
923     }
924 }
925
926 /******************************************************************************
927  * Same as REGPROC_resize_char_buffer() but on a regular buffer.
928  *
929  * Parameters:
930  * buffer - pointer to a buffer
931  * len - current size of the buffer in bytes
932  * required_size - size of the data to place in the buffer in bytes
933  */
934 static void REGPROC_resize_binary_buffer(BYTE **buffer, DWORD *size, DWORD required_size)
935 {
936     if (required_size > *size) {
937         *size = required_size;
938         if (!*buffer)
939             *buffer = HeapAlloc(GetProcessHeap(), 0, *size);
940         else
941             *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *size);
942         CHECK_ENOUGH_MEMORY(*buffer);
943     }
944 }
945
946 /******************************************************************************
947  * Prints string str to file
948  */
949 static void REGPROC_export_string(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, WCHAR *str, DWORD str_len)
950 {
951     DWORD i, pos;
952     DWORD extra = 0;
953
954     REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + 10);
955
956     /* escaping characters */
957     pos = *line_len;
958     for (i = 0; i < str_len; i++) {
959         WCHAR c = str[i];
960         switch (c) {
961         case '\n':
962             extra++;
963             REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
964             (*line_buf)[pos++] = '\\';
965             (*line_buf)[pos++] = 'n';
966             break;
967
968         case '\\':
969         case '"':
970             extra++;
971             REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len + str_len + extra);
972             (*line_buf)[pos++] = '\\';
973             /* Fall through */
974
975         default:
976             (*line_buf)[pos++] = c;
977             break;
978         }
979     }
980     (*line_buf)[pos] = '\0';
981     *line_len = pos;
982 }
983
984 static void REGPROC_export_binary(WCHAR **line_buf, DWORD *line_buf_size, DWORD *line_len, DWORD type, BYTE *value, DWORD value_size, BOOL unicode)
985 {
986     DWORD hex_pos, data_pos;
987     const WCHAR *hex_prefix;
988     const WCHAR hex[] = {'h','e','x',':',0};
989     WCHAR hex_buf[17];
990     const WCHAR concat[] = {'\\','\n',' ',' ',0};
991     DWORD concat_prefix, concat_len;
992     const WCHAR newline[] = {'\n',0};
993     CHAR* value_multibyte = NULL;
994
995     if (type == REG_BINARY) {
996         hex_prefix = hex;
997     } else {
998         const WCHAR hex_format[] = {'h','e','x','(','%','u',')',':',0};
999         hex_prefix = hex_buf;
1000         sprintfW(hex_buf, hex_format, type);
1001         if ((type == REG_SZ || type == REG_EXPAND_SZ || type == REG_MULTI_SZ) && !unicode)
1002         {
1003             value_multibyte = GetMultiByteStringN((WCHAR*)value, value_size / sizeof(WCHAR), &value_size);
1004             value = (BYTE*)value_multibyte;
1005         }
1006     }
1007
1008     concat_len = lstrlenW(concat);
1009     concat_prefix = 2;
1010
1011     hex_pos = *line_len;
1012     *line_len += lstrlenW(hex_prefix);
1013     data_pos = *line_len;
1014     *line_len += value_size * 3;
1015     /* - The 2 spaces that concat places at the start of the
1016      *   line effectively reduce the space available for data.
1017      * - If the value name and hex prefix are very long
1018      *   ( > REG_FILE_HEX_LINE_LEN) then we may overestimate
1019      *   the needed number of lines by one. But that's ok.
1020      * - The trailing linefeed takes the place of a comma so
1021      *   it's accounted for already.
1022      */
1023     *line_len += *line_len / (REG_FILE_HEX_LINE_LEN - concat_prefix) * concat_len;
1024     REGPROC_resize_char_buffer(line_buf, line_buf_size, *line_len);
1025     lstrcpyW(*line_buf + hex_pos, hex_prefix);
1026     if (value_size)
1027     {
1028         const WCHAR format[] = {'%','0','2','x',0};
1029         DWORD i, column;
1030
1031         column = data_pos; /* no line wrap yet */
1032         i = 0;
1033         while (1)
1034         {
1035             sprintfW(*line_buf + data_pos, format, (unsigned int)value[i]);
1036             data_pos += 2;
1037             if (++i == value_size)
1038                 break;
1039
1040             (*line_buf)[data_pos++] = ',';
1041             column += 3;
1042
1043             /* wrap the line */
1044             if (column >= REG_FILE_HEX_LINE_LEN) {
1045                 lstrcpyW(*line_buf + data_pos, concat);
1046                 data_pos += concat_len;
1047                 column = concat_prefix;
1048             }
1049         }
1050     }
1051     lstrcpyW(*line_buf + data_pos, newline);
1052     HeapFree(GetProcessHeap(), 0, value_multibyte);
1053 }
1054
1055 /******************************************************************************
1056  * Writes the given line to a file, in multi-byte or wide characters
1057  */
1058 static void REGPROC_write_line(FILE *file, const WCHAR* str, BOOL unicode)
1059 {
1060     if(unicode)
1061     {
1062         fwrite(str, sizeof(WCHAR), lstrlenW(str), file);
1063     } else
1064     {
1065         char* strA = GetMultiByteString(str);
1066         fputs(strA, file);
1067         HeapFree(GetProcessHeap(), 0, strA);
1068     }
1069 }
1070
1071 /******************************************************************************
1072  * Writes contents of the registry key to the specified file stream.
1073  *
1074  * Parameters:
1075  * file - writable file stream to export registry branch to.
1076  * key - registry branch to export.
1077  * reg_key_name_buf - name of the key with registry class.
1078  *      Is resized if necessary.
1079  * reg_key_name_size - length of the buffer for the registry class in characters.
1080  * val_name_buf - buffer for storing value name.
1081  *      Is resized if necessary.
1082  * val_name_size - length of the buffer for storing value names in characters.
1083  * val_buf - buffer for storing values while extracting.
1084  *      Is resized if necessary.
1085  * val_size - size of the buffer for storing values in bytes.
1086  */
1087 static void export_hkey(FILE *file, HKEY key,
1088                  WCHAR **reg_key_name_buf, DWORD *reg_key_name_size,
1089                  WCHAR **val_name_buf, DWORD *val_name_size,
1090                  BYTE **val_buf, DWORD *val_size,
1091                  WCHAR **line_buf, DWORD *line_buf_size,
1092                  BOOL unicode)
1093 {
1094     DWORD max_sub_key_len;
1095     DWORD max_val_name_len;
1096     DWORD max_val_size;
1097     DWORD curr_len;
1098     DWORD i;
1099     BOOL more_data;
1100     LONG ret;
1101     WCHAR key_format[] = {'\n','[','%','s',']','\n',0};
1102
1103     /* get size information and resize the buffers if necessary */
1104     if (RegQueryInfoKeyW(key, NULL, NULL, NULL, NULL,
1105                         &max_sub_key_len, NULL,
1106                         NULL, &max_val_name_len, &max_val_size, NULL, NULL
1107                        ) != ERROR_SUCCESS) {
1108         REGPROC_print_error();
1109     }
1110     curr_len = strlenW(*reg_key_name_buf);
1111     REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size,
1112                                max_sub_key_len + curr_len + 1);
1113     REGPROC_resize_char_buffer(val_name_buf, val_name_size,
1114                                max_val_name_len);
1115     REGPROC_resize_binary_buffer(val_buf, val_size, max_val_size);
1116     REGPROC_resize_char_buffer(line_buf, line_buf_size, lstrlenW(*reg_key_name_buf) + 4);
1117     /* output data for the current key */
1118     sprintfW(*line_buf, key_format, *reg_key_name_buf);
1119     REGPROC_write_line(file, *line_buf, unicode);
1120
1121     /* print all the values */
1122     i = 0;
1123     more_data = TRUE;
1124     while(more_data) {
1125         DWORD value_type;
1126         DWORD val_name_size1 = *val_name_size;
1127         DWORD val_size1 = *val_size;
1128         ret = RegEnumValueW(key, i, *val_name_buf, &val_name_size1, NULL,
1129                            &value_type, *val_buf, &val_size1);
1130         if (ret == ERROR_MORE_DATA) {
1131             /* Increase the size of the buffers and retry */
1132             REGPROC_resize_char_buffer(val_name_buf, val_name_size, val_name_size1);
1133             REGPROC_resize_binary_buffer(val_buf, val_size, val_size1);
1134         } else if (ret != ERROR_SUCCESS) {
1135             more_data = FALSE;
1136             if (ret != ERROR_NO_MORE_ITEMS) {
1137                 REGPROC_print_error();
1138             }
1139         } else {
1140             DWORD line_len;
1141             i++;
1142
1143             if ((*val_name_buf)[0]) {
1144                 const WCHAR val_start[] = {'"','%','s','"','=',0};
1145
1146                 line_len = 0;
1147                 REGPROC_export_string(line_buf, line_buf_size, &line_len, *val_name_buf, lstrlenW(*val_name_buf));
1148                 REGPROC_resize_char_buffer(val_name_buf, val_name_size, lstrlenW(*line_buf) + 1);
1149                 lstrcpyW(*val_name_buf, *line_buf);
1150
1151                 line_len = 3 + lstrlenW(*val_name_buf);
1152                 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1153                 sprintfW(*line_buf, val_start, *val_name_buf);
1154             } else {
1155                 const WCHAR std_val[] = {'@','=',0};
1156                 line_len = 2;
1157                 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len);
1158                 lstrcpyW(*line_buf, std_val);
1159             }
1160
1161             switch (value_type) {
1162             case REG_SZ:
1163             {
1164                 WCHAR* wstr = (WCHAR*)*val_buf;
1165
1166                 if (val_size1 < sizeof(WCHAR) || val_size1 % sizeof(WCHAR) ||
1167                     wstr[val_size1 / sizeof(WCHAR) - 1]) {
1168                     REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1169                 } else {
1170                     const WCHAR start[] = {'"',0};
1171                     const WCHAR end[] = {'"','\n',0};
1172                     DWORD len;
1173
1174                     len = lstrlenW(start);
1175                     REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + len);
1176                     lstrcpyW(*line_buf + line_len, start);
1177                     line_len += len;
1178
1179                     /* At this point we know wstr is '\0'-terminated
1180                      * so we can substract 1 from the size
1181                      */
1182                     REGPROC_export_string(line_buf, line_buf_size, &line_len, wstr, val_size1 / sizeof(WCHAR) - 1);
1183
1184                     REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + lstrlenW(end));
1185                     lstrcpyW(*line_buf + line_len, end);
1186                 }
1187                 break;
1188             }
1189
1190             case REG_DWORD:
1191             {
1192                 WCHAR format[] = {'d','w','o','r','d',':','%','0','8','x','\n',0};
1193
1194                 REGPROC_resize_char_buffer(line_buf, line_buf_size, line_len + 15);
1195                 sprintfW(*line_buf + line_len, format, *((DWORD *)*val_buf));
1196                 break;
1197             }
1198
1199             default:
1200             {
1201                 char* key_nameA = GetMultiByteString(*reg_key_name_buf);
1202                 char* value_nameA = GetMultiByteString(*val_name_buf);
1203                 fprintf(stderr,"%s: warning - unsupported registry format '%d', "
1204                         "treat as binary\n",
1205                         getAppName(), value_type);
1206                 fprintf(stderr,"key name: \"%s\"\n", key_nameA);
1207                 fprintf(stderr,"value name:\"%s\"\n\n", value_nameA);
1208                 HeapFree(GetProcessHeap(), 0, key_nameA);
1209                 HeapFree(GetProcessHeap(), 0, value_nameA);
1210             }
1211                 /* falls through */
1212             case REG_EXPAND_SZ:
1213             case REG_MULTI_SZ:
1214                 /* falls through */
1215             case REG_BINARY:
1216                 REGPROC_export_binary(line_buf, line_buf_size, &line_len, value_type, *val_buf, val_size1, unicode);
1217             }
1218             REGPROC_write_line(file, *line_buf, unicode);
1219         }
1220     }
1221
1222     i = 0;
1223     more_data = TRUE;
1224     (*reg_key_name_buf)[curr_len] = '\\';
1225     while(more_data) {
1226         DWORD buf_size = *reg_key_name_size - curr_len - 1;
1227
1228         ret = RegEnumKeyExW(key, i, *reg_key_name_buf + curr_len + 1, &buf_size,
1229                            NULL, NULL, NULL, NULL);
1230         if (ret == ERROR_MORE_DATA) {
1231             /* Increase the size of the buffer and retry */
1232             REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_size, curr_len + 1 + buf_size);
1233         } else if (ret != ERROR_SUCCESS) {
1234             more_data = FALSE;
1235             if (ret != ERROR_NO_MORE_ITEMS) {
1236                 REGPROC_print_error();
1237             }
1238         } else {
1239             HKEY subkey;
1240
1241             i++;
1242             if (RegOpenKeyW(key, *reg_key_name_buf + curr_len + 1,
1243                            &subkey) == ERROR_SUCCESS) {
1244                 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_size,
1245                             val_name_buf, val_name_size, val_buf, val_size,
1246                             line_buf, line_buf_size, unicode);
1247                 RegCloseKey(subkey);
1248             } else {
1249                 REGPROC_print_error();
1250             }
1251         }
1252     }
1253     (*reg_key_name_buf)[curr_len] = '\0';
1254 }
1255
1256 /******************************************************************************
1257  * Open file for export.
1258  */
1259 static FILE *REGPROC_open_export_file(WCHAR *file_name, BOOL unicode)
1260 {
1261     FILE *file;
1262     WCHAR dash = '-';
1263
1264     if (strncmpW(file_name,&dash,1)==0)
1265         file=stdout;
1266     else
1267     {
1268         CHAR* file_nameA = GetMultiByteString(file_name);
1269         file = fopen(file_nameA, "w");
1270         if (!file) {
1271             perror("");
1272             fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_nameA);
1273             HeapFree(GetProcessHeap(), 0, file_nameA);
1274             exit(1);
1275         }
1276         HeapFree(GetProcessHeap(), 0, file_nameA);
1277     }
1278     if(unicode)
1279     {
1280         const BYTE unicode_seq[] = {0xff,0xfe};
1281         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'};
1282         fwrite(unicode_seq, sizeof(BYTE), sizeof(unicode_seq)/sizeof(unicode_seq[0]), file);
1283         fwrite(header, sizeof(WCHAR), sizeof(header)/sizeof(header[0]), file);
1284     } else
1285     {
1286         fputs("REGEDIT4\n", file);
1287     }
1288
1289     return file;
1290 }
1291
1292 /******************************************************************************
1293  * Writes contents of the registry key to the specified file stream.
1294  *
1295  * Parameters:
1296  * file_name - name of a file to export registry branch to.
1297  * reg_key_name - registry branch to export. The whole registry is exported if
1298  *      reg_key_name is NULL or contains an empty string.
1299  */
1300 BOOL export_registry_key(WCHAR *file_name, WCHAR *reg_key_name, DWORD format)
1301 {
1302     WCHAR *reg_key_name_buf;
1303     WCHAR *val_name_buf;
1304     BYTE *val_buf;
1305     WCHAR *line_buf;
1306     DWORD reg_key_name_size = KEY_MAX_LEN;
1307     DWORD val_name_size = KEY_MAX_LEN;
1308     DWORD val_size = REG_VAL_BUF_SIZE;
1309     DWORD line_buf_size = KEY_MAX_LEN + REG_VAL_BUF_SIZE;
1310     FILE *file = NULL;
1311     BOOL unicode = (format == REG_FORMAT_5);
1312
1313     reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1314                                  reg_key_name_size  * sizeof(*reg_key_name_buf));
1315     val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1316                              val_name_size * sizeof(*val_name_buf));
1317     val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1318     line_buf = HeapAlloc(GetProcessHeap(), 0, line_buf_size * sizeof(*line_buf));
1319     CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf && line_buf);
1320
1321     if (reg_key_name && reg_key_name[0]) {
1322         HKEY reg_key_class;
1323         WCHAR *branch_name = NULL;
1324         HKEY key;
1325
1326         REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_size,
1327                                    lstrlenW(reg_key_name));
1328         lstrcpyW(reg_key_name_buf, reg_key_name);
1329
1330         /* open the specified key */
1331         if (!parseKeyName(reg_key_name, &reg_key_class, &branch_name)) {
1332             CHAR* key_nameA = GetMultiByteString(reg_key_name);
1333             fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1334                     getAppName(), key_nameA);
1335             HeapFree(GetProcessHeap(), 0, key_nameA);
1336             exit(1);
1337         }
1338         if (!branch_name[0]) {
1339             /* no branch - registry class is specified */
1340             file = REGPROC_open_export_file(file_name, unicode);
1341             export_hkey(file, reg_key_class,
1342                         &reg_key_name_buf, &reg_key_name_size,
1343                         &val_name_buf, &val_name_size,
1344                         &val_buf, &val_size, &line_buf,
1345                         &line_buf_size, unicode);
1346         } else if (RegOpenKeyW(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1347             file = REGPROC_open_export_file(file_name, unicode);
1348             export_hkey(file, key,
1349                         &reg_key_name_buf, &reg_key_name_size,
1350                         &val_name_buf, &val_name_size,
1351                         &val_buf, &val_size, &line_buf,
1352                         &line_buf_size, unicode);
1353             RegCloseKey(key);
1354         } else {
1355             CHAR* key_nameA = GetMultiByteString(reg_key_name);
1356             fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1357                     getAppName(), key_nameA);
1358             HeapFree(GetProcessHeap(), 0, key_nameA);
1359             REGPROC_print_error();
1360         }
1361     } else {
1362         unsigned int i;
1363
1364         /* export all registry classes */
1365         file = REGPROC_open_export_file(file_name, unicode);
1366         for (i = 0; i < REG_CLASS_NUMBER; i++) {
1367             /* do not export HKEY_CLASSES_ROOT */
1368             if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1369                     reg_class_keys[i] != HKEY_CURRENT_USER &&
1370                     reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1371                     reg_class_keys[i] != HKEY_DYN_DATA) {
1372                 lstrcpyW(reg_key_name_buf, reg_class_namesW[i]);
1373                 export_hkey(file, reg_class_keys[i],
1374                             &reg_key_name_buf, &reg_key_name_size,
1375                             &val_name_buf, &val_name_size,
1376                             &val_buf, &val_size, &line_buf,
1377                             &line_buf_size, unicode);
1378             }
1379         }
1380     }
1381
1382     if (file) {
1383         fclose(file);
1384     }
1385     HeapFree(GetProcessHeap(), 0, reg_key_name);
1386     HeapFree(GetProcessHeap(), 0, val_name_buf);
1387     HeapFree(GetProcessHeap(), 0, val_buf);
1388     HeapFree(GetProcessHeap(), 0, line_buf);
1389     return TRUE;
1390 }
1391
1392 /******************************************************************************
1393  * Reads contents of the specified file into the registry.
1394  */
1395 BOOL import_registry_file(FILE* reg_file)
1396 {
1397     if (reg_file)
1398     {
1399         BYTE s[2];
1400         if (fread( s, 2, 1, reg_file) == 1)
1401         {
1402             if (s[0] == 0xff && s[1] == 0xfe)
1403             {
1404                 processRegLinesW(reg_file);
1405             } else
1406             {
1407                 processRegLinesA(reg_file, (char*)s);
1408             }
1409         }
1410         return TRUE;
1411     }
1412     return FALSE;
1413 }
1414
1415 /******************************************************************************
1416  * Removes the registry key with all subkeys. Parses full key name.
1417  *
1418  * Parameters:
1419  * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1420  *      empty, points to register key class, does not exist.
1421  */
1422 void delete_registry_key(WCHAR *reg_key_name)
1423 {
1424     WCHAR *key_name = NULL;
1425     HKEY key_class;
1426
1427     if (!reg_key_name || !reg_key_name[0])
1428         return;
1429
1430     if (!parseKeyName(reg_key_name, &key_class, &key_name)) {
1431         char* reg_key_nameA = GetMultiByteString(reg_key_name);
1432         fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1433                 getAppName(), reg_key_nameA);
1434         HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1435         exit(1);
1436     }
1437     if (!*key_name) {
1438         char* reg_key_nameA = GetMultiByteString(reg_key_name);
1439         fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1440                 getAppName(), reg_key_nameA);
1441         HeapFree(GetProcessHeap(), 0, reg_key_nameA);
1442         exit(1);
1443     }
1444
1445     RegDeleteTreeW(key_class, key_name);
1446 }