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