1 /*
2  * Copyright 2017 Hugh McMaster
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18 
19 #include <windows.h>
20 #include <errno.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 
24 #include <wine/unicode.h>
25 #include <wine/debug.h>
26 #include <wine/heap.h>
27 
28 #include "reg.h"
29 
30 WINE_DEFAULT_DEBUG_CHANNEL(reg);
31 
32 static WCHAR *GetWideString(const char *strA)
33 {
34     if (strA)
35     {
36         WCHAR *strW;
37         int len = MultiByteToWideChar(CP_ACP, 0, strA, -1, NULL, 0);
38 
39         strW = heap_xalloc(len * sizeof(WCHAR));
40         MultiByteToWideChar(CP_ACP, 0, strA, -1, strW, len);
41         return strW;
42     }
43     return NULL;
44 }
45 
46 static WCHAR *GetWideStringN(const char *strA, int size, DWORD *len)
47 {
48     if (strA)
49     {
50         WCHAR *strW;
51         *len = MultiByteToWideChar(CP_ACP, 0, strA, size, NULL, 0);
52 
53         strW = heap_xalloc(*len * sizeof(WCHAR));
54         MultiByteToWideChar(CP_ACP, 0, strA, size, strW, *len);
55         return strW;
56     }
57     *len = 0;
58     return NULL;
59 }
60 
61 static WCHAR *(*get_line)(FILE *);
62 
63 /* parser definitions */
64 enum parser_state
65 {
66     HEADER,              /* parsing the registry file version header */
67     PARSE_WIN31_LINE,    /* parsing a Windows 3.1 registry line */
68     LINE_START,          /* at the beginning of a registry line */
69     KEY_NAME,            /* parsing a key name */
70     DELETE_KEY,          /* deleting a registry key */
71     DEFAULT_VALUE_NAME,  /* parsing a default value name */
72     QUOTED_VALUE_NAME,   /* parsing a double-quoted value name */
73     DATA_START,          /* preparing for data parsing operations */
74     DELETE_VALUE,        /* deleting a registry value */
75     DATA_TYPE,           /* parsing the registry data type */
76     STRING_DATA,         /* parsing REG_SZ data */
77     DWORD_DATA,          /* parsing DWORD data */
78     HEX_DATA,            /* parsing REG_BINARY, REG_NONE, REG_EXPAND_SZ or REG_MULTI_SZ data */
79     EOL_BACKSLASH,       /* preparing to parse multiple lines of hex data */
80     HEX_MULTILINE,       /* parsing multiple lines of hex data */
81     UNKNOWN_DATA,        /* parsing an unhandled or invalid data type */
82     SET_VALUE,           /* adding a value to the registry */
83     NB_PARSER_STATES
84 };
85 
86 struct parser
87 {
88     FILE              *file;           /* pointer to a registry file */
89     WCHAR              two_wchars[2];  /* first two characters from the encoding check */
90     BOOL               is_unicode;     /* parsing Unicode or ASCII data */
91     short int          reg_version;    /* registry file version */
92     HKEY               hkey;           /* current registry key */
93     WCHAR             *key_name;       /* current key name */
94     WCHAR             *value_name;     /* value name */
95     DWORD              parse_type;     /* generic data type for parsing */
96     DWORD              data_type;      /* data type */
97     void              *data;           /* value data */
98     DWORD              data_size;      /* size of the data (in bytes) */
99     BOOL               backslash;      /* TRUE if the current line contains a backslash */
100     enum parser_state  state;          /* current parser state */
101 };
102 
103 typedef WCHAR *(*parser_state_func)(struct parser *parser, WCHAR *pos);
104 
105 /* parser state machine functions */
106 static WCHAR *header_state(struct parser *parser, WCHAR *pos);
107 static WCHAR *parse_win31_line_state(struct parser *parser, WCHAR *pos);
108 static WCHAR *line_start_state(struct parser *parser, WCHAR *pos);
109 static WCHAR *key_name_state(struct parser *parser, WCHAR *pos);
110 static WCHAR *delete_key_state(struct parser *parser, WCHAR *pos);
111 static WCHAR *default_value_name_state(struct parser *parser, WCHAR *pos);
112 static WCHAR *quoted_value_name_state(struct parser *parser, WCHAR *pos);
113 static WCHAR *data_start_state(struct parser *parser, WCHAR *pos);
114 static WCHAR *delete_value_state(struct parser *parser, WCHAR *pos);
115 static WCHAR *data_type_state(struct parser *parser, WCHAR *pos);
116 static WCHAR *string_data_state(struct parser *parser, WCHAR *pos);
117 static WCHAR *dword_data_state(struct parser *parser, WCHAR *pos);
118 static WCHAR *hex_data_state(struct parser *parser, WCHAR *pos);
119 static WCHAR *eol_backslash_state(struct parser *parser, WCHAR *pos);
120 static WCHAR *hex_multiline_state(struct parser *parser, WCHAR *pos);
121 static WCHAR *unknown_data_state(struct parser *parser, WCHAR *pos);
122 static WCHAR *set_value_state(struct parser *parser, WCHAR *pos);
123 
124 static const parser_state_func parser_funcs[NB_PARSER_STATES] =
125 {
126     header_state,              /* HEADER */
127     parse_win31_line_state,    /* PARSE_WIN31_LINE */
128     line_start_state,          /* LINE_START */
129     key_name_state,            /* KEY_NAME */
130     delete_key_state,          /* DELETE_KEY */
131     default_value_name_state,  /* DEFAULT_VALUE_NAME */
132     quoted_value_name_state,   /* QUOTED_VALUE_NAME */
133     data_start_state,          /* DATA_START */
134     delete_value_state,        /* DELETE_VALUE */
135     data_type_state,           /* DATA_TYPE */
136     string_data_state,         /* STRING_DATA */
137     dword_data_state,          /* DWORD_DATA */
138     hex_data_state,            /* HEX_DATA */
139     eol_backslash_state,       /* EOL_BACKSLASH */
140     hex_multiline_state,       /* HEX_MULTILINE */
141     unknown_data_state,        /* UNKNOWN_DATA */
142     set_value_state,           /* SET_VALUE */
143 };
144 
145 /* set the new parser state and return the previous one */
146 static inline enum parser_state set_state(struct parser *parser, enum parser_state state)
147 {
148     enum parser_state ret = parser->state;
149     parser->state = state;
150     return ret;
151 }
152 
153 /******************************************************************************
154  * Converts a hex representation of a DWORD into a DWORD.
155  */
156 static BOOL convert_hex_to_dword(WCHAR *str, DWORD *dw)
157 {
158     WCHAR *p, *end;
159     int count = 0;
160 
161     while (*str == ' ' || *str == '\t') str++;
162     if (!*str) goto error;
163 
164     p = str;
165     while (isxdigitW(*p))
166     {
167         count++;
168         p++;
169     }
170     if (count > 8) goto error;
171 
172     end = p;
173     while (*p == ' ' || *p == '\t') p++;
174     if (*p && *p != ';') goto error;
175 
176     *end = 0;
177     *dw = strtoulW(str, &end, 16);
178     return TRUE;
179 
180 error:
181     return FALSE;
182 }
183 
184 /******************************************************************************
185  * Converts comma-separated hex data into a binary string and modifies
186  * the input parameter to skip the concatenating backslash, if found.
187  *
188  * Returns TRUE or FALSE to indicate whether parsing was successful.
189  */
190 static BOOL convert_hex_csv_to_hex(struct parser *parser, WCHAR **str)
191 {
192     size_t size;
193     BYTE *d;
194     WCHAR *s;
195 
196     parser->backslash = FALSE;
197 
198     /* The worst case is 1 digit + 1 comma per byte */
199     size = ((lstrlenW(*str) + 1) / 2) + parser->data_size;
200     parser->data = heap_xrealloc(parser->data, size);
201 
202     s = *str;
203     d = (BYTE *)parser->data + parser->data_size;
204 
205     while (*s)
206     {
207         WCHAR *end;
208         unsigned long wc;
209 
210         wc = strtoulW(s, &end, 16);
211         if (wc > 0xff) return FALSE;
212 
213         if (s == end && wc == 0)
214         {
215             while (*end == ' ' || *end == '\t') end++;
216             if (*end == '\\')
217             {
218                 parser->backslash = TRUE;
219                 *str = end + 1;
220                 return TRUE;
221             }
222             else if (*end == ';')
223                 return TRUE;
224             return FALSE;
225         }
226 
227         *d++ = wc;
228         parser->data_size++;
229 
230         if (*end && *end != ',')
231         {
232             while (*end == ' ' || *end == '\t') end++;
233             if (*end && *end != ';') return FALSE;
234             return TRUE;
235         }
236 
237         if (*end) end++;
238         s = end;
239     }
240 
241     return TRUE;
242 }
243 
244 /******************************************************************************
245  * Parses the data type of the registry value being imported and modifies
246  * the input parameter to skip the string representation of the data type.
247  *
248  * Returns TRUE or FALSE to indicate whether a data type was found.
249  */
250 static BOOL parse_data_type(struct parser *parser, WCHAR **line)
251 {
252     struct data_type { const WCHAR *tag; int len; int type; int parse_type; };
253 
254     static const WCHAR quote[] = {'"'};
255     static const WCHAR hex[] = {'h','e','x',':'};
256     static const WCHAR dword[] = {'d','w','o','r','d',':'};
257     static const WCHAR hexp[] = {'h','e','x','('};
258 
259     static const struct data_type data_types[] = {
260     /*    tag    len  type         parse type    */
261         { quote,  1,  REG_SZ,      REG_SZ },
262         { hex,    4,  REG_BINARY,  REG_BINARY },
263         { dword,  6,  REG_DWORD,   REG_DWORD },
264         { hexp,   4,  -1,          REG_BINARY }, /* REG_NONE, REG_EXPAND_SZ, REG_MULTI_SZ */
265         { NULL,   0,  0,           0 }
266     };
267 
268     const struct data_type *ptr;
269 
270     for (ptr = data_types; ptr->tag; ptr++)
271     {
272         if (strncmpW(ptr->tag, *line, ptr->len))
273             continue;
274 
275         parser->parse_type = ptr->parse_type;
276         parser->data_type = ptr->parse_type;
277         *line += ptr->len;
278 
279         if (ptr->type == -1)
280         {
281             WCHAR *end;
282             DWORD val;
283 
284             if (!**line || tolowerW((*line)[1]) == 'x')
285                 return FALSE;
286 
287             /* "hex(xx):" is special */
288             val = wcstoul(*line, &end, 16);
289             if (*end != ')' || *(end + 1) != ':' || (val == ~0u && errno == ERANGE))
290                 return FALSE;
291 
292             parser->data_type = val;
293             *line = end + 2;
294         }
295         return TRUE;
296     }
297     return FALSE;
298 }
299 
300 /******************************************************************************
301  * Replaces escape sequences with their character equivalents and
302  * null-terminates the string on the first non-escaped double quote.
303  *
304  * Assigns a pointer to the remaining unparsed data in the line.
305  * Returns TRUE or FALSE to indicate whether a closing double quote was found.
306  */
307 static BOOL unescape_string(WCHAR *str, WCHAR **unparsed)
308 {
309     int str_idx = 0;            /* current character under analysis */
310     int val_idx = 0;            /* the last character of the unescaped string */
311     int len = lstrlenW(str);
312     BOOL ret;
313 
314     for (str_idx = 0; str_idx < len; str_idx++, val_idx++)
315     {
316         if (str[str_idx] == '\\')
317         {
318             str_idx++;
319             switch (str[str_idx])
320             {
321             case 'n':
322                 str[val_idx] = '\n';
323                 break;
324             case 'r':
325                 str[val_idx] = '\r';
326                 break;
327             case '0':
328                 str[val_idx] = '\0';
329                 break;
330             case '\\':
331             case '"':
332                 str[val_idx] = str[str_idx];
333                 break;
334             default:
335                 if (!str[str_idx]) return FALSE;
336                 output_message(STRING_ESCAPE_SEQUENCE, str[str_idx]);
337                 str[val_idx] = str[str_idx];
338                 break;
339             }
340         }
341         else if (str[str_idx] == '"')
342             break;
343         else
344             str[val_idx] = str[str_idx];
345     }
346 
347     ret = (str[str_idx] == '"');
348     *unparsed = str + str_idx + 1;
349     str[val_idx] = '\0';
350     return ret;
351 }
352 
353 static HKEY parse_key_name(WCHAR *key_name, WCHAR **key_path)
354 {
355     if (!key_name) return 0;
356 
357     *key_path = strchrW(key_name, '\\');
358     if (*key_path) (*key_path)++;
359 
360     return path_get_rootkey(key_name);
361 }
362 
363 static void close_key(struct parser *parser)
364 {
365     if (parser->hkey)
366     {
367         heap_free(parser->key_name);
368         parser->key_name = NULL;
369 
370         RegCloseKey(parser->hkey);
371         parser->hkey = NULL;
372     }
373 }
374 
375 static LONG open_key(struct parser *parser, WCHAR *path)
376 {
377     HKEY key_class;
378     WCHAR *key_path;
379     LONG res;
380 
381     close_key(parser);
382 
383     /* Get the registry class */
384     if (!path || !(key_class = parse_key_name(path, &key_path)))
385         return ERROR_INVALID_PARAMETER;
386 
387     res = RegCreateKeyExW(key_class, key_path, 0, NULL, REG_OPTION_NON_VOLATILE,
388                           KEY_ALL_ACCESS, NULL, &parser->hkey, NULL);
389 
390     if (res == ERROR_SUCCESS)
391     {
392         parser->key_name = heap_xalloc((lstrlenW(path) + 1) * sizeof(WCHAR));
393         lstrcpyW(parser->key_name, path);
394     }
395     else
396         parser->hkey = NULL;
397 
398     return res;
399 }
400 
401 static void free_parser_data(struct parser *parser)
402 {
403     if (parser->parse_type == REG_DWORD || parser->parse_type == REG_BINARY)
404         heap_free(parser->data);
405 
406     parser->data = NULL;
407     parser->data_size = 0;
408 }
409 
410 static void prepare_hex_string_data(struct parser *parser)
411 {
412     if (parser->data_type == REG_EXPAND_SZ || parser->data_type == REG_MULTI_SZ)
413     {
414         if (parser->is_unicode)
415         {
416             WCHAR *data = parser->data;
417             DWORD len = parser->data_size / sizeof(WCHAR);
418 
419             if (data[len - 1] != 0)
420             {
421                 data[len] = 0;
422                 parser->data_size += sizeof(WCHAR);
423             }
424         }
425         else
426         {
427             BYTE *data = parser->data;
428 
429             if (data[parser->data_size - 1] != 0)
430             {
431                 data[parser->data_size] = 0;
432                 parser->data_size++;
433             }
434 
435             parser->data = GetWideStringN(parser->data, parser->data_size, &parser->data_size);
436             parser->data_size *= sizeof(WCHAR);
437             heap_free(data);
438         }
439     }
440 }
441 
442 enum reg_versions {
443     REG_VERSION_31,
444     REG_VERSION_40,
445     REG_VERSION_50,
446     REG_VERSION_FUZZY,
447     REG_VERSION_INVALID
448 };
449 
450 static enum reg_versions parse_file_header(const WCHAR *s)
451 {
452     static const WCHAR header_31[] = {'R','E','G','E','D','I','T',0};
453     static const WCHAR header_40[] = {'R','E','G','E','D','I','T','4',0};
454     static const WCHAR header_50[] = {'W','i','n','d','o','w','s',' ',
455                                       'R','e','g','i','s','t','r','y',' ','E','d','i','t','o','r',' ',
456                                       'V','e','r','s','i','o','n',' ','5','.','0','0',0};
457 
458     while (*s == ' ' || *s == '\t') s++;
459 
460     if (!strcmpW(s, header_31))
461         return REG_VERSION_31;
462 
463     if (!strcmpW(s, header_40))
464         return REG_VERSION_40;
465 
466     if (!strcmpW(s, header_50))
467         return REG_VERSION_50;
468 
469     /* The Windows version accepts registry file headers beginning with "REGEDIT" and ending
470      * with other characters, as long as "REGEDIT" appears at the start of the line. For example,
471      * "REGEDIT 4", "REGEDIT9" and "REGEDIT4FOO" are all treated as valid file headers.
472      * In all such cases, however, the contents of the registry file are not imported.
473      */
474     if (!strncmpW(s, header_31, 7)) /* "REGEDIT" without NUL */
475         return REG_VERSION_FUZZY;
476 
477     return REG_VERSION_INVALID;
478 }
479 
480 /* handler for parser HEADER state */
481 static WCHAR *header_state(struct parser *parser, WCHAR *pos)
482 {
483     WCHAR *line, *header;
484 
485     if (!(line = get_line(parser->file)))
486         return NULL;
487 
488     if (!parser->is_unicode)
489     {
490         header = heap_xalloc((lstrlenW(line) + 3) * sizeof(WCHAR));
491         header[0] = parser->two_wchars[0];
492         header[1] = parser->two_wchars[1];
493         lstrcpyW(header + 2, line);
494         parser->reg_version = parse_file_header(header);
495         heap_free(header);
496     }
497     else parser->reg_version = parse_file_header(line);
498 
499     switch (parser->reg_version)
500     {
501     case REG_VERSION_31:
502         set_state(parser, PARSE_WIN31_LINE);
503         break;
504     case REG_VERSION_40:
505     case REG_VERSION_50:
506         set_state(parser, LINE_START);
507         break;
508     default:
509         get_line(NULL); /* Reset static variables */
510         return NULL;
511     }
512 
513     return line;
514 }
515 
516 /* handler for parser PARSE_WIN31_LINE state */
517 static WCHAR *parse_win31_line_state(struct parser *parser, WCHAR *pos)
518 {
519     WCHAR *line, *value;
520     static WCHAR hkcr[] = {'H','K','E','Y','_','C','L','A','S','S','E','S','_','R','O','O','T'};
521     unsigned int key_end = 0;
522 
523     if (!(line = get_line(parser->file)))
524         return NULL;
525 
526     if (strncmpW(line, hkcr, ARRAY_SIZE(hkcr)))
527         return line;
528 
529     /* get key name */
530     while (line[key_end] && !isspaceW(line[key_end])) key_end++;
531 
532     value = line + key_end;
533     while (*value == ' ' || *value == '\t') value++;
534 
535     if (*value == '=') value++;
536     if (*value == ' ') value++; /* at most one space is skipped */
537 
538     line[key_end] = 0;
539 
540     if (open_key(parser, line) != ERROR_SUCCESS)
541     {
542         output_message(STRING_OPEN_KEY_FAILED, line);
543         return line;
544     }
545 
546     parser->value_name = NULL;
547     parser->data_type = REG_SZ;
548     parser->data = value;
549     parser->data_size = (lstrlenW(value) + 1) * sizeof(WCHAR);
550 
551     set_state(parser, SET_VALUE);
552     return value;
553 }
554 
555 /* handler for parser LINE_START state */
556 static WCHAR *line_start_state(struct parser *parser, WCHAR *pos)
557 {
558     WCHAR *line, *p;
559 
560     if (!(line = get_line(parser->file)))
561         return NULL;
562 
563     for (p = line; *p; p++)
564     {
565         switch (*p)
566         {
567         case '[':
568             set_state(parser, KEY_NAME);
569             return p + 1;
570         case '@':
571             set_state(parser, DEFAULT_VALUE_NAME);
572             return p;
573         case '"':
574             set_state(parser, QUOTED_VALUE_NAME);
575             return p + 1;
576         case ' ':
577         case '\t':
578             break;
579         default:
580             return p;
581         }
582     }
583 
584     return p;
585 }
586 
587 /* handler for parser KEY_NAME state */
588 static WCHAR *key_name_state(struct parser *parser, WCHAR *pos)
589 {
590     WCHAR *p = pos, *key_end;
591 
592     if (*p == ' ' || *p == '\t' || !(key_end = strrchrW(p, ']')))
593         goto done;
594 
595     *key_end = 0;
596 
597     if (*p == '-')
598     {
599         set_state(parser, DELETE_KEY);
600         return p + 1;
601     }
602     else if (open_key(parser, p) != ERROR_SUCCESS)
603         output_message(STRING_OPEN_KEY_FAILED, p);
604 
605 done:
606     set_state(parser, LINE_START);
607     return p;
608 }
609 
610 /* handler for parser DELETE_KEY state */
611 static WCHAR *delete_key_state(struct parser *parser, WCHAR *pos)
612 {
613     WCHAR *p = pos;
614 
615     close_key(parser);
616 
617     if (*p == 'H' || *p == 'h')
618     {
619         HKEY root;
620         WCHAR *path;
621 
622         root = parse_key_name(p, &path);
623 
624         if (root && path && *path)
625             RegDeleteTreeW(root, path);
626     }
627 
628     set_state(parser, LINE_START);
629     return p;
630 }
631 
632 /* handler for parser DEFAULT_VALUE_NAME state */
633 static WCHAR *default_value_name_state(struct parser *parser, WCHAR *pos)
634 {
635     heap_free(parser->value_name);
636     parser->value_name = NULL;
637 
638     set_state(parser, DATA_START);
639     return pos + 1;
640 }
641 
642 /* handler for parser QUOTED_VALUE_NAME state */
643 static WCHAR *quoted_value_name_state(struct parser *parser, WCHAR *pos)
644 {
645     WCHAR *val_name = pos, *p;
646 
647     if (parser->value_name)
648     {
649         heap_free(parser->value_name);
650         parser->value_name = NULL;
651     }
652 
653     if (!unescape_string(val_name, &p))
654         goto invalid;
655 
656     /* copy the value name in case we need to parse multiple lines and the buffer is overwritten */
657     parser->value_name = heap_xalloc((lstrlenW(val_name) + 1) * sizeof(WCHAR));
658     lstrcpyW(parser->value_name, val_name);
659 
660     set_state(parser, DATA_START);
661     return p;
662 
663 invalid:
664     set_state(parser, LINE_START);
665     return val_name;
666 }
667 
668 /* handler for parser DATA_START state */
669 static WCHAR *data_start_state(struct parser *parser, WCHAR *pos)
670 {
671     WCHAR *p = pos;
672     unsigned int len;
673 
674     while (*p == ' ' || *p == '\t') p++;
675     if (*p != '=') goto invalid;
676     p++;
677     while (*p == ' ' || *p == '\t') p++;
678 
679     /* trim trailing whitespace */
680     len = strlenW(p);
681     while (len > 0 && (p[len - 1] == ' ' || p[len - 1] == '\t')) len--;
682     p[len] = 0;
683 
684     if (*p == '-')
685         set_state(parser, DELETE_VALUE);
686     else
687         set_state(parser, DATA_TYPE);
688     return p;
689 
690 invalid:
691     set_state(parser, LINE_START);
692     return p;
693 }
694 
695 /* handler for parser DELETE_VALUE state */
696 static WCHAR *delete_value_state(struct parser *parser, WCHAR *pos)
697 {
698     WCHAR *p = pos + 1;
699 
700     while (*p == ' ' || *p == '\t') p++;
701     if (*p && *p != ';') goto done;
702 
703     RegDeleteValueW(parser->hkey, parser->value_name);
704 
705 done:
706     set_state(parser, LINE_START);
707     return p;
708 }
709 
710 /* handler for parser DATA_TYPE state */
711 static WCHAR *data_type_state(struct parser *parser, WCHAR *pos)
712 {
713     WCHAR *line = pos;
714 
715     if (!parse_data_type(parser, &line))
716     {
717         set_state(parser, LINE_START);
718         return line;
719     }
720 
721     switch (parser->parse_type)
722     {
723     case REG_SZ:
724         set_state(parser, STRING_DATA);
725         break;
726     case REG_DWORD:
727         set_state(parser, DWORD_DATA);
728         break;
729     case REG_BINARY: /* all hex data types, including undefined */
730         set_state(parser, HEX_DATA);
731         break;
732     default:
733         set_state(parser, UNKNOWN_DATA);
734     }
735 
736     return line;
737 }
738 
739 /* handler for parser STRING_DATA state */
740 static WCHAR *string_data_state(struct parser *parser, WCHAR *pos)
741 {
742     WCHAR *line;
743 
744     parser->data = pos;
745 
746     if (!unescape_string(parser->data, &line))
747         goto invalid;
748 
749     while (*line == ' ' || *line == '\t') line++;
750     if (*line && *line != ';') goto invalid;
751 
752     parser->data_size = (lstrlenW(parser->data) + 1) * sizeof(WCHAR);
753 
754     set_state(parser, SET_VALUE);
755     return line;
756 
757 invalid:
758     free_parser_data(parser);
759     set_state(parser, LINE_START);
760     return line;
761 }
762 
763 /* handler for parser DWORD_DATA state */
764 static WCHAR *dword_data_state(struct parser *parser, WCHAR *pos)
765 {
766     WCHAR *line = pos;
767 
768     parser->data = heap_xalloc(sizeof(DWORD));
769 
770     if (!convert_hex_to_dword(line, parser->data))
771         goto invalid;
772 
773     parser->data_size = sizeof(DWORD);
774 
775     set_state(parser, SET_VALUE);
776     return line;
777 
778 invalid:
779     free_parser_data(parser);
780     set_state(parser, LINE_START);
781     return line;
782 }
783 
784 /* handler for parser HEX_DATA state */
785 static WCHAR *hex_data_state(struct parser *parser, WCHAR *pos)
786 {
787     WCHAR *line = pos;
788 
789     if (!*line)
790         goto set_value;
791 
792     if (!convert_hex_csv_to_hex(parser, &line))
793         goto invalid;
794 
795     if (parser->backslash)
796     {
797         set_state(parser, EOL_BACKSLASH);
798         return line;
799     }
800 
801     prepare_hex_string_data(parser);
802 
803 set_value:
804     set_state(parser, SET_VALUE);
805     return line;
806 
807 invalid:
808     free_parser_data(parser);
809     set_state(parser, LINE_START);
810     return line;
811 }
812 
813 /* handler for parser EOL_BACKSLASH state */
814 static WCHAR *eol_backslash_state(struct parser *parser, WCHAR *pos)
815 {
816     WCHAR *p = pos;
817 
818     while (*p == ' ' || *p == '\t') p++;
819     if (*p && *p != ';') goto invalid;
820 
821     set_state(parser, HEX_MULTILINE);
822     return pos;
823 
824 invalid:
825     free_parser_data(parser);
826     set_state(parser, LINE_START);
827     return p;
828 }
829 
830 /* handler for parser HEX_MULTILINE state */
831 static WCHAR *hex_multiline_state(struct parser *parser, WCHAR *pos)
832 {
833     WCHAR *line;
834 
835     if (!(line = get_line(parser->file)))
836     {
837         prepare_hex_string_data(parser);
838         set_state(parser, SET_VALUE);
839         return pos;
840     }
841 
842     while (*line == ' ' || *line == '\t') line++;
843     if (!*line || *line == ';') return line;
844 
845     if (!isxdigitW(*line)) goto invalid;
846 
847     set_state(parser, HEX_DATA);
848     return line;
849 
850 invalid:
851     free_parser_data(parser);
852     set_state(parser, LINE_START);
853     return line;
854 }
855 
856 /* handler for parser UNKNOWN_DATA state */
857 static WCHAR *unknown_data_state(struct parser *parser, WCHAR *pos)
858 {
859     FIXME("Unknown registry data type [0x%x]\n", parser->data_type);
860 
861     set_state(parser, LINE_START);
862     return pos;
863 }
864 
865 /* handler for parser SET_VALUE state */
866 static WCHAR *set_value_state(struct parser *parser, WCHAR *pos)
867 {
868     RegSetValueExW(parser->hkey, parser->value_name, 0, parser->data_type,
869                    parser->data, parser->data_size);
870 
871     free_parser_data(parser);
872 
873     if (parser->reg_version == REG_VERSION_31)
874         set_state(parser, PARSE_WIN31_LINE);
875     else
876         set_state(parser, LINE_START);
877 
878     return pos;
879 }
880 
881 #define REG_VAL_BUF_SIZE  4096
882 
883 static WCHAR *get_lineA(FILE *fp)
884 {
885     static WCHAR *lineW;
886     static size_t size;
887     static char *buf, *next;
888     char *line;
889 
890     heap_free(lineW);
891 
892     if (!fp) goto cleanup;
893 
894     if (!size)
895     {
896         size = REG_VAL_BUF_SIZE;
897         buf = heap_xalloc(size);
898         *buf = 0;
899         next = buf;
900     }
901     line = next;
902 
903     while (next)
904     {
905         char *p = strpbrk(line, "\r\n");
906         if (!p)
907         {
908             size_t len, count;
909             len = strlen(next);
910             memmove(buf, next, len + 1);
911             if (size - len < 3)
912             {
913                 size *= 2;
914                 buf = heap_xrealloc(buf, size);
915             }
916             if (!(count = fread(buf + len, 1, size - len - 1, fp)))
917             {
918                 next = NULL;
919                 lineW = GetWideString(buf);
920                 return lineW;
921             }
922             buf[len + count] = 0;
923             next = buf;
924             line = buf;
925             continue;
926         }
927         next = p + 1;
928         if (*p == '\r' && *(p + 1) == '\n') next++;
929         *p = 0;
930         lineW = GetWideString(line);
931         return lineW;
932     }
933 
934 cleanup:
935     lineW = NULL;
936     if (size) heap_free(buf);
937     size = 0;
938     return NULL;
939 }
940 
941 static WCHAR *get_lineW(FILE *fp)
942 {
943     static size_t size;
944     static WCHAR *buf, *next;
945     WCHAR *line;
946 
947     if (!fp) goto cleanup;
948 
949     if (!size)
950     {
951         size = REG_VAL_BUF_SIZE;
952         buf = heap_xalloc(size * sizeof(WCHAR));
953         *buf = 0;
954         next = buf;
955     }
956     line = next;
957 
958     while (next)
959     {
960         static const WCHAR line_endings[] = {'\r','\n',0};
961         WCHAR *p = strpbrkW(line, line_endings);
962         if (!p)
963         {
964             size_t len, count;
965             len = strlenW(next);
966             memmove(buf, next, (len + 1) * sizeof(WCHAR));
967             if (size - len < 3)
968             {
969                 size *= 2;
970                 buf = heap_xrealloc(buf, size * sizeof(WCHAR));
971             }
972             if (!(count = fread(buf + len, sizeof(WCHAR), size - len - 1, fp)))
973             {
974                 next = NULL;
975                 return buf;
976             }
977             buf[len + count] = 0;
978             next = buf;
979             line = buf;
980             continue;
981         }
982         next = p + 1;
983         if (*p == '\r' && *(p + 1) == '\n') next++;
984         *p = 0;
985         return line;
986     }
987 
988 cleanup:
989     if (size) heap_free(buf);
990     size = 0;
991     return NULL;
992 }
993 
994 int reg_import(const WCHAR *filename)
995 {
996     FILE *fp;
997     static const WCHAR rb_mode[] = {'r','b',0};
998     BYTE s[2];
999     struct parser parser;
1000     WCHAR *pos;
1001 
1002     fp = _wfopen(filename, rb_mode);
1003     if (!fp)
1004     {
1005         output_message(STRING_FILE_NOT_FOUND, filename);
1006         return 1;
1007     }
1008 
1009     if (fread(s, sizeof(WCHAR), 1, fp) != 1)
1010         goto error;
1011 
1012     parser.is_unicode = (s[0] == 0xff && s[1] == 0xfe);
1013     get_line = parser.is_unicode ? get_lineW : get_lineA;
1014 
1015     parser.file          = fp;
1016     parser.two_wchars[0] = s[0];
1017     parser.two_wchars[1] = s[1];
1018     parser.reg_version   = -1;
1019     parser.hkey          = NULL;
1020     parser.key_name      = NULL;
1021     parser.value_name    = NULL;
1022     parser.parse_type    = 0;
1023     parser.data_type     = 0;
1024     parser.data          = NULL;
1025     parser.data_size     = 0;
1026     parser.backslash     = FALSE;
1027     parser.state         = HEADER;
1028 
1029     pos = parser.two_wchars;
1030 
1031     /* parser main loop */
1032     while (pos)
1033         pos = (parser_funcs[parser.state])(&parser, pos);
1034 
1035     if (parser.reg_version == REG_VERSION_INVALID)
1036         goto error;
1037 
1038     heap_free(parser.value_name);
1039     close_key(&parser);
1040 
1041     fclose(fp);
1042     return 0;
1043 
1044 error:
1045     fclose(fp);
1046     return 1;
1047 }
1048