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